首页 > 编程语言 > 详细

spring web put与delete方法的调用

时间:2014-11-25 02:22:33      阅读:495      评论:0      收藏:0      [点我收藏+]

?

在form中,method只用GET/POST。如果使用PUT/DELETE呢

在spring 的web应用中使用PUT/DELETE访问方式:代码如下:

	<form th:action="@{/app/account/update}" method="post">
			<input type="hidden" name="_method" value="PUT" />
			<input type="submit" value="submit" />
		</form>

?将你要的访问方式如下<input type="hidden" name="_method" value="PUT" />放到form中,并设置form的方式method="post"。

为什么是这样呢?

因为在页面访问要通过一个spring过滤器:HiddenHttpMethodFilter

代码如下:

public class HiddenHttpMethodFilter extends OncePerRequestFilter {

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

	private String methodParam = DEFAULT_METHOD_PARAM;


      @Override
	protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
			throws ServletException, IOException {
               //当method的方式为post并且_method不为空
		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);
		}
	}

        //method转换
	/**
	 * 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;
		}
	}

}

?这样一看就明明白白了。。。

?

?

@RequestMapping(value="/update",method=RequestMethod.PUT)
	public String update() throws Exception{
		System.out.println("test");
		return "account/get";
	}

?

spring web put与delete方法的调用

原文:http://dk05408.iteye.com/blog/2159714

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!