SpringMVC注解@RequestMapping注解除了params,header属性,还有一个非常重要的属性——method,method的四种取值GET,POST,DELETE,PUT方式刚好对应了SpringMVC的四种请求方式。
SpringMVC的四种请求方式
通过rest风格占位符方式,利用@PathVariable注解将占位符的值赋给调用方法参数,GET请求方式
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.GET)
public String testRest(@PathVariable("id") Integer id) {
System.out.println("testRest get " + id);
return SUCCESS;
}
POST请求方式
@RequestMapping(value = "/testRest", method = RequestMethod.POST)
public String testRest() {
System.out.println("testRest post");
return SUCCESS;
}
DELETE请求方式
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.DELETE)
public String testRestDelete(@PathVariable Integer id) {
System.out.println("testRestDelete " + id);
return SUCCESS;
}
PUT请求方式
@RequestMapping(value = "/testRest/{id}", method = RequestMethod.PUT)
public String testRestPut(@PathVariable Integer id) {
System.out.println("testRestPut " + id);
return SUCCESS;
}
- 上面有些请求路径是一样的,比如delete请求和get请求,都为springmvc/testRest/1,但是RequestMapping的method属性限制了请求方式,对应的请求方式对应了相应的请求路径
- rest url方式试图消除传统的url传递参数的模式
- PUT与DELETE请求方式是基于POST请求方式的
- GET:/xxx/{id} 表示通过id得到一条数据
- POST:/xxx 表示新增一条数据
- DELETE:/xxx/{id} 表示通过id删除一条数据
- PUT:/xxx/{id} 表示通过id修改一条数据
GET,POST,DELETE,PUT 刚好对应数据库crud操作
如何使用DELETE,PUT请求方式
<!-- rest风格put 表示修改一条数据-->
<form action="springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="PUT"/>
<input type="submit" value="testRest PUT"/>
</form>
<!-- rest风格delete 表示删除一条数据-->
<form action="springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="DELETE"/>
<input type="submit" value="testRest DELETE"/>
</form>
基于上面的java代码,以及DELETE,PUT请求方式是基于POST请求方式,必须在表单提交中写上一个隐藏域,而且必须将name设置为_method,value属性值写上对应的请求方式。