REST风格
REST:即Representational State Transfer。(资源)表现层状态转化。是目前最流行的一种互联网软件架构。它的结构清晰,符合标准,容易理解,扩展方便。• 具体说,就是 HTTP 协议里面,四个表示操作方式的动词:GET、POST、PUT、DELETE。它们分别对应四种基本操作:GET 用来获取资源,POST 用来新建资源,PUT 用来更新资源,DELETE 用来删除资源。
注意:浏览器的form标签只支持GET与POST请求,而PUT,DELETE等请求方法并不支持。Spring3.0添加了一个过滤器,可以将这些请求转换为标准的http方法,使得支持GET,POST,PUT与DELETE请求。
HiddenHttpMethodFilter过滤器
HiddenHttpMethodFilter:可以将PUT,DELETE等请求方法转换为标准的http方法。
<!--支持REST风格的过滤器:可以将POST请求转换为PUT或DELETE请求 -->
<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>
HiddenHttpMethodFilter源码解析:
private String methodParam = "_method";
protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
HttpServletRequest requestToUse = request;
//判断表单的请求方法为POST
if ("POST".equals(request.getMethod()) && request.getAttribute("javax.servlet.error.exception") == null) {
//this.methodParam="_method",获取到表单中的_method值
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
//将_method值大写
String method = paramValue.toUpperCase(Locale.ENGLISH);
if (ALLOWED_METHODS.contains(method)) {
//重写request。getMethod方法
requestToUse = new HiddenHttpMethodFilter.HttpMethodRequestWrapper(request, method);
}
}
}
filterChain.doFilter((ServletRequest)requestToUse, response);
}
REST风格的增删改查简单实现
发送PUT,DELETE请求的流程:
- 配置HiddenHttpMethodFilter
- 需要发送POST请求
- 需要在发送POST请求时携带一个 name="_method"的隐含域,值为PUT或DELETE
<a href="book/1">查询一号图书</a>
<form action="book/1" method="post" >
<input type="submit" value="添加一号图书"/>
</form>
<form action="book/1" method="post" >
<input type="hidden" name="_method" value="put"/>
<input type="submit" value="修改一号图书"/>
</form>
<form action="book/1" method="post" >
<input type="hidden" name="_method" value="delete"/>
<input type="submit" value="删除一号图书"/>
</form>
@RequestMapping(value = "/book/{bid}",method = RequestMethod.GET)
public String bookGet(@PathVariable(value = "bid") Integer id){
System.out.println("Get:"+id);
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.POST)
public String bookPost(@PathVariable(value = "bid") Integer id){
System.out.println("Post:"+id);
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.PUT)
public String bookPut(@PathVariable(value = "bid") Integer id){
System.out.println("Put:"+id);
return "success";
}
@RequestMapping(value = "/book/{bid}",method = RequestMethod.DELETE)
public String bookDelete(@PathVariable(value = "bid") Integer id){
System.out.println("Delete:"+id);
return "success";
}
注意:高版本的Tomcat的Rest-jsp不接受DELETE,PUT形式请求问题。
解决方法:在JSP页面声明上加入 isErrorPage=“true”:
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>