示例:
/order/1 HTTP GET:得到id=1的order
/order/1 HTTP DELETE:删除id=1的order
/order/1 HTTP PUT:更新id=1的order
/order/ HTTP POST:新增order
HiddenHttpMethodFilter:
浏览器form表单只支持GET,POST请求,而DELETE,PUT等method并不支持,Spring3.0添加了一个过滤器,可以把POST请求转为DELETE,PUT请求使得支持GET,POST,PUT,DELETE请求;
步骤:
- web.xml中添加HiddenHttpMethodFilter
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 前端表单添加隐藏域
<form action="springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<button type="submit">testRest-DELETE</button>
</form><br>
<form action="springmvc/testRest/2" method="post">
<input type="hidden" name="_method" value="PUT">
<button type="submit">testRest-PUT</button>
</form><br>
<form action="springmvc/testRest/3" method="post">
<button type="submit">testRest-POST</button>
</form><br>
<a href="springmvc/testRest/4">testRest-GET</a>
- 类
public class Rest {
private String SUCCESS = "success";
@RequestMapping(value="/testRest/{id}",method=RequestMethod.DELETE)
public String testRest_delete(@PathVariable("id") Integer id){
System.out.println("删除成功:"+id);
return SUCCESS;
}
@RequestMapping(value="/testRest/{id}",method=RequestMethod.PUT)
public String testRest_put(@PathVariable("id") Integer id){
System.out.println("更新成功:"+id);
return SUCCESS;
}
@RequestMapping(value="/testRest/{id}",method=RequestMethod.POST)
public String testRest_post(@PathVariable("id") Integer id){
System.out.println("添加成功:"+id);
return SUCCESS;
}
@RequestMapping(value="/testRest/{id}",method=RequestMethod.GET)
public String testRest_get(@PathVariable("id") Integer id){
System.out.println("获取成功:"+id);
return SUCCESS;
}
}