注解:
- @RestController:Spring 4的新注解。 她自动为每个方法加上 @ResponseBody. @RestController可以看做是 @Controller 和@ResponseBody两个注解的组合。
- @RequestBody: 如果一个方法申明了@RequestBody注解, Spring会基于请求头中的Content-Type使用HTTP Message converters将request body反序列化成对象。
- @ResponseBody:是在方法的上注解,如果一个方法申明了@ResponseBody, Spring会基于请求头中的Accept使用HTTP Message converters将对象序列化成response body。在Spring 4中如果使用了@RestController,则可以不用再声明此注解。
返回类型:
- ResponseEntity:ResponseEntity很重要。 她代表了整个HTTP response. 你可以指定status code, response headers, response body.。她有几种构造方法可以在HTTP Response中传递信息。
- MediaType:随@RequestMapping一起使用, 你可以指定生产和消费的类型(使用@Produces或@Consumes属性) 。
例如:
@RequestMapping(value = "/say/{msg}", produces="application/json;charset=UTF-8")
仅当request请求头中的(Accept)类型中包含该指定类型才返回。
@RequestMapping(produces={"text/html", "application/json"})
将匹配Accept:text/html或Accept:application/json。
当你有如下Accept头“Accept:text/html,application/xml,application/json”,将按照顺序进行produces的匹配
作为服务端,@Produces 标注用于指定返回的MIME媒体类型,@Consumes 标注服务端只可接受此MIME媒体类型的请求。。
作为客户端,Content-Type 请求头用于指定返回的MIME媒体类型。**Accept **请求头用于标注客户端只可接受此MIME媒体类型的请求。
//请求的地址
String url = "http://localhost:9080/springmvc-chapter6/request/ContentType";
//①创建Http Request(内部使用HttpURLConnection)
ClientHttpRequest request = new SimpleClientHttpRequestFactory().createRequest(new URI(url), HttpMethod.POST);
//②设置请求头的内容类型头和内容编码(GBK)
request.getHeaders().set("Content-Type", "application/json;charset=gbk");
//③以GBK编码写出请求内容体
String jsonData = "{\"username\":\"zhang\", \"password\":\"123\"}";
request.getBody().write(jsonData.getBytes("gbk"));
//④发送请求并得到响应
ClientHttpResponse response = request.execute();
System.out.println(response.getStatusCode());
添加jackson相关包
如果导入jackson-databind.jar,则@ResponseBody注解的方法或@RestController注解的Controller默认返回JSON格式。另外再倒入jackson-dataformat-xml.jar的话默认返回XML,此时如需返回JSON可在请求最后加上".json"。
注:org.codehaus.jackson是旧版本的com.fasterxml.jackson。如果项目中需要jackson-databind,则只需要引入它。jackson-core和jackson-annotations会随它自动引入。
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>${jackson.library}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.dataformat</groupId>
<artifactId>jackson-dataformat-xml</artifactId>
<version>${jackson.library}</version>
</dependency>
使用@RestController:
服务端:
package com.zzhblh.resource.impl;
import com.zzhblh.entity.account.User;
import com.zzhblh.resource.UserResource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.*;
import java.util.Map;
/**
* Created by chen on 2016/9/2.
*/
@RestController
@RequestMapping("api/user_resource")
public class UserResourceImpl implements UserResource{
@Override
@RequestMapping(value = "/user_query", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public User queryUserInfoById(@RequestParam(value="id") String id) {
return new User("123","abc");
}
@Override
@RequestMapping(value = "/user_update/{id}", method = RequestMethod.PUT)
public User updateUserInfo(@PathVariable("id") String id, @RequestBody User user) {
user.setUserName("new");
return user;
}
@Override
@RequestMapping(value = "/user_update/map", method = RequestMethod.PUT)
public User updateUserInfoByMap(@RequestBody Map map) {
User user = new User();
user.setUserName(map.get("name").toString());
return user;
}
@Override
@RequestMapping(value = "/user_create", method = RequestMethod.POST)
public User createUserInfo(@RequestBody User user) {
user.setUserName("new");
return user;
}
@Override
@RequestMapping(value = "/user_delete", method = RequestMethod.DELETE)
public User deleteUserInfo(@RequestParam(value="id") String id) {
User user = new User();
user.setUserName("someone deleted");
return user;
}
}
客户端:
package com.zzhblh.sample;
import com.zzhblh.entity.account.User;
import org.springframework.http.*;
import org.springframework.web.client.RestTemplate;
import java.net.URI;
import java.util.HashMap;
import java.util.Map;
/**
* Created by chen on 2016/9/2.
*/
public class testRest {
static String REST_SERVICE_URI = "http://localhost:8080/practice-web/api/user_resource";
private static void getUser(){
System.out.println("Testing getUser API----------");
RestTemplate restTemplate = new RestTemplate();
User user = restTemplate.getForObject(REST_SERVICE_URI+"/user_query?id=123", User.class);
System.out.println(user);
}
private static void updateUser(){
System.out.println("Testing updateUser API----------");
RestTemplate restTemplate = new RestTemplate();
User user = new User("123","old");
restTemplate.put(REST_SERVICE_URI+"/user_update/123", user, User.class);
//使用resttemplate的put方法得不到返回值
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> userRequest = new HttpEntity<User>(user, headers);
ResponseEntity<User> responseEntity = restTemplate.exchange(REST_SERVICE_URI+"/user_update/123", HttpMethod.PUT, userRequest, User.class);
System.out.println(responseEntity.getBody().toString());
}
private static void updateUserMap(){
System.out.println("Testing updateUserMap API----------");
RestTemplate restTemplate = new RestTemplate();
Map map = new HashMap<String,String>();
map.put("name","mm");
restTemplate.put(REST_SERVICE_URI+"/user_update/map", map, Map.class);
}
/* POST */
private static void createUser() {
System.out.println("Testing create User API----------");
RestTemplate restTemplate = new RestTemplate();
User user = new User("123","old");
user = restTemplate.postForObject(REST_SERVICE_URI+"/user_create", user, User.class);
System.out.println(user.toString());
ResponseEntity<User> responseEntity = restTemplate.postForEntity(REST_SERVICE_URI+"/user_create", user, User.class);
System.out.println(responseEntity.getBody().toString());
}
/* DELETE */
private static void deleteUser() {
System.out.println("Testing delete User API----------");
RestTemplate restTemplate = new RestTemplate();
restTemplate.delete(REST_SERVICE_URI+"/user_delete?id=123");
System.out.println("deleted");
//使用resttemplate的put方法得不到返回值
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);
HttpEntity<User> userRequest = new HttpEntity<User>(headers);
ResponseEntity<User> responseEntity = restTemplate.exchange(REST_SERVICE_URI+"/user_delete", HttpMethod.DELETE, userRequest, User.class);
System.out.println(responseEntity.getBody().toString());
}
public static void main(String args[]){
getUser();
updateUser();
updateUserMap();
createUser();
deleteUser();
}
}
使用@Controller:
服务端:
package com.citic.test.action;
import java.util.ArrayList;
import java.util.List;
import net.sf.json.JSONObject;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.citic.test.entity.Person;
/**
* 基于Restful风格架构测试
*
* @author dekota
* @since JDK1.5
* @version V1.0
* @history 2014-2-15 下午3:00:12 dekota 新建
*/
@Controller
@Scope("prototype")//改为多列模式
public class DekotaAction {
/** 日志实例 */
private static final Logger logger = Logger.getLogger(DekotaAction.class);
@RequestMapping(value = "/hello", produces = "text/plain;charset=UTF-8")
public @ResponseBody
String hello() {
return "你好!hello";
}
@RequestMapping(value = "/say/{msg}", produces = "application/json;charset=UTF-8")
public @ResponseBody
String say(@PathVariable(value = "msg") String msg) {
return "{\"msg\":\"you say:'" + msg + "'\"}";
}
@RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.GET)
public @ResponseBody
Person getPerson(@PathVariable("id") int id) {
logger.info("获取人员信息id=" + id);
Person person = new Person();
person.setName("张三");
person.setSex("男");
person.setAge(30);
person.setId(id);
return person;
}
@RequestMapping(value = "/person/{id:\\d+}", method = RequestMethod.DELETE)
public @ResponseBody
Object deletePerson(@PathVariable("id") int id) {
logger.info("删除人员信息id=" + id);
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "删除人员信息成功");
return jsonObject;
}
@RequestMapping(value = "/person", method = RequestMethod.POST)
public @ResponseBody
Object addPerson(Person person) {
logger.info("注册人员信息成功id=" + person.getId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "注册人员信息成功");
return jsonObject;
}
@RequestMapping(value = "/person", method = RequestMethod.PUT)
public @ResponseBody
Object updatePerson(Person person) {
logger.info("更新人员信息id=" + person.getId());
JSONObject jsonObject = new JSONObject();
jsonObject.put("msg", "更新人员信息成功");
return jsonObject;
}
@RequestMapping(value = "/person", method = RequestMethod.PATCH)
public @ResponseBody
List<Person> listPerson(@RequestParam(value = "name", required = false, defaultValue = "") String name) {
logger.info("查询人员name like " + name);
List<Person> lstPersons = new ArrayList<Person>();
Person person = new Person();
person.setName("张三");
person.setSex("男");
person.setAge(25);
person.setId(101);
lstPersons.add(person);
Person person2 = new Person();
person2.setName("李四");
person2.setSex("女");
person2.setAge(23);
person2.setId(102);
lstPersons.add(person2);
Person person3 = new Person();
person3.setName("王五");
person3.setSex("男");
person3.setAge(27);
person3.setId(103);
lstPersons.add(person3);
return lstPersons;
}
}
客户端:
<script type="text/javascript">
(function(window,$){
var dekota={
url:'',
init:function(){
dekota.url='<%=basePath%>';
$.UIkit.notify("页面初始化完成", {status:'info',timeout:500});
$("#btnGet").click(dekota.getPerson);
$("#btnAdd").click(dekota.addPerson);
$("#btnDel").click(dekota.delPerson);
$("#btnUpdate").click(dekota.updatePerson);
$("#btnList").click(dekota.listPerson);
},
getPerson:function(){
$.ajax({
url: dekota.url + 'person/101/',
type: 'GET',
dataType: 'json'
}).done(function(data, status, xhr) {
$.UIkit.notify("获取人员信息成功", {status:'success',timeout:1000});
}).fail(function(xhr, status, error) {
$.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
});
},
addPerson:function(){
$.ajax({
url: dekota.url + 'person',
type: 'POST',
dataType: 'json',
data: {id: 1,name:'张三',sex:'男',age:23}
}).done(function(data, status, xhr) {
$.UIkit.notify(data.msg, {status:'success',timeout:1000});
}).fail(function(xhr, status, error) {
$.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
});
},
delPerson:function(){
$.ajax({
url: dekota.url + 'person/109',
type: 'DELETE',
dataType: 'json'
}).done(function(data, status, xhr) {
$.UIkit.notify(data.msg, {status:'success',timeout:1000});
}).fail(function(xhr, status, error) {
$.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
});
},
updatePerson:function(){
$.ajax({
url: dekota.url + 'person',
type: 'POST',//注意在传参数时,加:_method:'PUT' 将对应后台的PUT请求方法
dataType: 'json',
data: {_method:'PUT',id: 221,name:'王五',sex:'男',age:23}
}).done(function(data, status, xhr) {
$.UIkit.notify(data.msg, {status:'success',timeout:1000});
}).fail(function(xhr, status, error) {
$.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
});
},
listPerson:function(){
$.ajax({
url: dekota.url + 'person',
type: 'POST',//注意在传参数时,加:_method:'PATCH' 将对应后台的PATCH请求方法
dataType: 'json',
data: {_method:'PATCH',name: '张三'}
}).done(function(data, status, xhr) {
$.UIkit.notify("查询人员信息成功", {status:'success',timeout:1000});
}).fail(function(xhr, status, error) {
$.UIkit.notify("请求失败!", {status:'danger',timeout:2000});
});
}
};
window.dekota=(window.dekota)?window.dekota:dekota;
$(function(){
dekota.init();
});
})(window,jQuery);
</script>
要点:服务端在类上加上@RestController注解。客户端请求时获取数据用GET,更新用PUT,创建用POST,删除用DELETE。
参考:
http://www.iteye.com/topic/1127120
http://websystique.com/springmvc/spring-mvc-4-restful-web-services-crud-example-resttemplate/
http://www.cnblogs.com/yjmyzz/p/javaee-jax-rs-tutorial.html
关于和jersey可参考:
http://waylau.com/categories/)