相信大家对spring-mvc(下面直接使用mvc代替)不陌生了。本文为大家详尽讲述mvc为大家提供的各种注解,方便开发,除了某些特定场景,基本可以完全和servlet api解耦,其中很多地方可能困扰大家很久。本文使用的mvc为spring-mvc-3.2,使用maven构建,如果没有用过maven的同学,可以先去看看maven的使用,附上demo源码地址:
https://github.com/a953924393/spring-mvc-annotation.git
RequestMapping
用于类和方法上,只是作用于不同,参数的意义相同,
- value[]:请求路径名,可以匹配多个
- method[]:接受的Request的类型,参考org.springframework.web.bind.annotation.RequestMethod
- params[]:用于窄化请求,即请求中必须匹配param中含有的参数才能映射成功
- headers[]:同样用于匹配必须请求头中必须包含headers中特定的请求头信息的请求
- consumes[]:mvc的controller是作为http请求的消费者,请求方是生产者,同样用于限定请求,如consumes = "application/json"
- produces[]:生产即返回的类型如:produces = "text/plain"
<span style="font-size:14px;">@Controller
@RequestMapping(
value = {"request"},
method = {RequestMethod.GET, RequestMethod.POST},
params = {"create","!add"},
consumes = {"application/*"},
produces = {"text/*"}
)
public class RequestMappingController {
@RequestMapping("mapping")
public void mapping(String create) {
System.out.println(create);
}
}</span>
在上面的demo中,可以使用http://localhost:8080/request/mapping?create=aaa请求,可以接受post和get请求,请求参数中必须含有create,不能含有add参数,只能消费application/*类型的请求,如头信息中包含
<span style="font-size:14px;">Accept:text/html,<strong>application/xhtml+xml,application/xml</strong>;q=0.9,image/webp,*/*;q=0.8</span>
RequestParm
用来处理简单类型的绑定,处理Content-Type: 为 application/x-www-form-urlencoded
编码的内容,提交方式GET、POST;处理复杂对象
- value,参数名
- required,该参数是否必须
- defaultValue,设置他的默认值
@RequestMapping("requestParam")
public void requestParam(@RequestParam(value = "name", required = true, defaultValue = "hello") String name) {
System.out.println(name);
}
RequestBody
用来处理复杂json对象,常用来处理Content-Type: 不是
application/x-www-form-urlencoded
编码的内容,例如application/json, application/xml等;- required,该参数是否必须
var submitRequestBody = function() {
$.ajax({
type: "POST",
url: "hello/requestBody",
contentType: "application/json",
//注意,这里必须是string类型,下面注释中的提交方式不能被RequestBody正确映射,注意单引号
//data: {"id":1,"name":"cxh","password":"cxh123","bookList":[{"id":123,"name":"java core"}]},
data: '{"id":1,"name":"cxh","password":"cxh123","bookList":[{"id":123,"name":"java core"}]}',
success: function(data) {
alert(data);
}
})
}
一般会遇到以下错误:
HTTP Status 415 -
type Status report
message
description The server refused this request because the request entity is in a format not supported by the requested resource for the requested method.
这种错误一般发生于
- 没有json的解析包,所需包,请看源码,或者查看日志打印的信息,添加所需的jar
- 没有设置content-Type:"application/json"
- json不够标准,会发生400错误,spring所使用的json解析包需要非常标准的json,如:{name:"jack"}是不标准的,必须是{"name":"jack"},
@RequestMapping(value = "requestBody", consumes = "application/json")
@ResponseBody
public User requestBody(@RequestBody User user) {
System.out.println(user);
return user;
}
User对象
public class User {
private Integer id;
private String name;
private String password;
private List<Book> bookList;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public List<Book> getBookList() {
return bookList;
}
public void setBookList(List<Book> bookList) {
this.bookList = bookList;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", bookList=" + bookList +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
User user = (User) o;
if (bookList != null ? !bookList.equals(user.bookList) : user.bookList != null) return false;
if (id != null ? !id.equals(user.id) : user.id != null) return false;
if (name != null ? !name.equals(user.name) : user.name != null) return false;
if (password != null ? !password.equals(user.password) : user.password != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (password != null ? password.hashCode() : 0);
result = 31 * result + (bookList != null ? bookList.hashCode() : 0);
return result;
}
}
Book对象
public class Book {
private Integer id;
private String name;
private Date publication;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getPublication() {
return publication;
}
public void setPublication(Date publication) {
this.publication = publication;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
", publication=" + publication +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Book book = (Book) o;
if (id != null ? !id.equals(book.id) : book.id != null) return false;
if (name != null ? !name.equals(book.name) : book.name != null) return false;
if (publication != null ? !publication.equals(book.publication) : book.publication != null) return false;
return true;
}
@Override
public int hashCode() {
int result = id != null ? id.hashCode() : 0;
result = 31 * result + (name != null ? name.hashCode() : 0);
result = 31 * result + (publication != null ? publication.hashCode() : 0);
return result;
}
}
PathVariable
这个注解用于参数上,让你很容易构建restful的url
- value,参数名
后台代码
@RequestMapping(value = "pathVariable/{id}/{name}")
public String pathVariable(@PathVariable Integer id, @PathVariable String name) {
System.out.println(id + name);
return "hello";
}
ResponseBody
用在方法上,用于返回一个json类型的字符串
前台请求
Request Headersview
GET /hello/responseBody HTTP/1.1
Host: localhost:8080
Connection: keep-alive
Cache-Control: max-age=0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
User-Agent: Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/37.0.2062.120 Safari/537.36
Accept-Encoding: gzip,deflate,sdch
Accept-Language: zh-CN,zh;q=0.8
Cookie: JSESSIONID=C09D6923C357C127CA408BF68B7FF8A9
Response Headersview
Content-Type:application/json;charset=UTF-8
Date:Sun, 07 Dec 2014 08:56:15 GMT
Server:Apache-Coyote/1.1
Transfer-Encoding:chunked
后台代码返回一个user对象
@RequestMapping("responseBody")
@ResponseBody
public User responseBody() {
User user = new User();
Book book = new Book();
book.setName("java core");
book.setId(1);
book.setPublication(new Date());
ArrayList<Book> books = new ArrayList<Book>();
books.add(book);
user.setId(1);
user.setName("jack");
user.setPassword("123asd");
user.setBookList(books);
return user;
}
CookieValue
用于参数上,按照名称获取一个cookie值,源码中采用foreach循环得到cookie,
CookieValue的参数列表
- value,参数名
- required,该参数是否必须
- defaultValue,设置他的默认值
@RequestMapping("cookieValue")
public String cookieValue(@CookieValue("JSESSIONID") String jsessionId) {
System.out.println(jsessionId);
return "hello";
}
RequestHeader
获取http头信息中的内容,参数同CookieValue,value的大小写不明感,比如Accept和accept都可以得到accept的值
后台代码
@RequestMapping("requestHeader")
public String requestHeader(@RequestHeader String accept) {
System.out.println(accept);
return "hello";
}