Spring MVC restful风格之put and delete

由于浏览器不支持PUT和DELETE方法,那么我们如何通过Spring实现PUT和DELETE的rest风格呢?

步骤一:

        在web.xml中添加一个Spring的过滤器HiddenHttpMethodFilter,对DispatcherServlet进行预处理

        <!-- spring mvc 实现delete、put的restful风格过滤器 start-->
	<filter>
		<filter-name>HiddenHttpMethodFilter</filter-name>
		<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
	</filter>

	<filter-mapping>
		<filter-name>HiddenHttpMethodFilter</filter-name>
                <!-- DispatcherServlet 对应的servlet-name-->
                <servlet-name>dispatcher</servlet-name>
        </filter-mapping>
        <!-- spring mvc 实现delete、put的restful风格过滤器 end-->

 步骤二: 

      向后台提交请求时,将请求类型设置为“POST”,同时向后台传递一个参数"_method",参数值可以设置为PUT或DELETE

Demo:ajax 删除restful风格

       deleteById:function(id,callback){
		//基础验证
		var url = controllerUtil.controllers.deleteById;
		if(url.trim().length<=0){
			throw new Error("please init controllerUtil.controllers.deleteById first.");
		}
		console.log("id:"+id);
		$.ajax({
			url : url+"/"+id,
			type : "POST",
			data : {_method:"DELETE"},
			dataType : "json",
			async : true,
			success : function(ajaxResult) {
				callback(ajaxResult);
			},
			error : function(error) {
				alert("error");
			}
	});
	}

    /**
     * 删除节点
     * @param node
     * @return
     */
    @RequestMapping(value="/node/{id}",method=RequestMethod.DELETE)
    @ResponseBody
    public AjaxResult deleteTreeNode(@PathVariable("id")Long id) {
        getService().deleteById(id);
        return AjaxResult.getInstance();
    }

以下是Spring过滤器的实现:

 
public class HiddenHttpMethodFilter extends OncePerRequestFilter {

	/** Default method parameter: {@code _method} */
	public static final String DEFAULT_METHOD_PARAM = "_method";

	private String methodParam = DEFAULT_METHOD_PARAM;


	/**
	 * Set the parameter name to look for HTTP methods.
	 * @see #DEFAULT_METHOD_PARAM
	 */
	public void setMethodParam(String methodParam) {
		Assert.hasText(methodParam, "'methodParam' must not be empty");
		this.methodParam = methodParam;
	}

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

		String paramValue = request.getParameter(this.methodParam);
		if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {
			String method = paramValue.toUpperCase(Locale.ENGLISH);
			HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
			filterChain.doFilter(wrapper, response);
		}
		else {
			filterChain.doFilter(request, response);
		}
	}


	/**
	 * Simple {@link HttpServletRequest} wrapper that returns the supplied method for
	 * {@link HttpServletRequest#getMethod()}.
	 */
	private static class HttpMethodRequestWrapper extends HttpServletRequestWrapper {

		private final String method;

		public HttpMethodRequestWrapper(HttpServletRequest request, String method) {
			super(request);
			this.method = method;
		}

		@Override
		public String getMethod() {
			return this.method;
		}
	}

}


 




  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值