您的位置:首页 > 编程语言 > Java开发

RESTful架构与SpringMVC框架的结合使用以及PUT、DELETE

2017-10-25 11:38 483 查看
步骤:

在web.xml文件配置过滤器HiddenHttpMethodFilter

在controller中设置与调用
详细讲解:

配置过滤器HiddenHttpMethodFilter

<filter>
<filter-name>methodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>methodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>




关注源码中的doFilterInternal

protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
throws ServletException, IOException {

HttpServletRequest requestToUse = request;

if ("POST".equals(request.getMethod()) && request.getAttribute(WebUtils.ERROR_EXCEPTION_ATTRIBUTE) == null) {
String paramValue = request.getParameter(this.methodParam);
if (StringUtils.hasLength(paramValue)) {
requestToUse = new HttpMethodRequestWrapper(request, paramValue);
}
}

filterChain.doFilter(requestToUse, response);
}
里面高亮的代码就是获取请求方式,默认是get



而这个methodParam就是通过前端参数传过来的值来判断PUT、DELETE的

以下是前端页面表格中_method的值,对应的是DELETE

<form action="springmvc/testRest/1" method="post">
<input type="hidden" name="_method" value="DELETE">
<input type="submit" value="restDelete">
</form>

在SpringMVC中调用

@Controller
@RequestMapping("/springmvc")
public class Hello {
private static final String SUCCESS = "success";
/**
* 最终的视图:
* 	prefix+returnValue+suffix
* 	/WEB-INF/views/success.jsp
*/
/**
* https://www.douyu.com/485503 restful风格
* {roomId}占位符
* 两种命名情况
* 1.参数的名字和占位符的名字保持一致
* 2.@PathVariable中的名字和占位符中的名字一致,参数的名字就任意
* @return
*/
/**
*  /testRest    POST  新增
* /testRest/1   GET 获取
* /testRest/1   PUT 更新
* /testRest/1   DELETE 删除
*
* @param id
* @return
*/
@RequestMapping("/testRest/{id}")
public String testRestGet(@PathVariable Integer id){
System.out.println("testRestGet:"+id);
return SUCCESS;
}
@RequestMapping(value = "/testRest",method = RequestMethod.POST)
public String testRestPost(){
System.out.println("testRestPost:");
return SUCCESS;
}

@RequestMapping(value = "/testRest/{id}",method = RequestMethod.PUT)
public String testRestPut(@PathVariable Integer id){
System.out.println("testRestPut:"+id);
return SUCCESS;
}
@RequestMapping(value = "/testRest/{id}",method = RequestMethod.DELETE)
public String testRestDelete(@
9e3b
PathVariable Integer id){
System.out.println("testRestDelete:"+id);
return SUCCESS;
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐