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

步骤:

  1. 在web.xml文件配置过滤器HiddenHttpMethodFilter
  2. 在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(@PathVariable Integer id){
		System.out.println("testRestDelete:"+id);
		return SUCCESS;
	}
	
}


猜你喜欢

转载自blog.csdn.net/Luke_R/article/details/78339469