SpringMVC杂记(九) 模拟其他类型(非GET,POST)的请求

1) 以前一个小兄弟问我,SpringMVC是否可以使用很多浏览器不支持的(DELETE, HEAD等)请求。
我依稀记得有个Filter可以把请求模拟成Delete方式。我直接回答说org.springframework.web.filter.HiddenHttpMethodFilter可以干这个事情。

2) 今日偶尔看到这个类的源代码发现根本不是如此。它只能将POST请求转换为其他请求。

if ("POST".equals(request.getMethod()) && StringUtils.hasLength(paramValue)) {// 只转换POST求情
String method = paramValue.toUpperCase(Locale.ENGLISH);
HttpServletRequest wrapper = new HttpMethodRequestWrapper(request, method);
filterChain.doFilter(wrapper, response);
}

看来以后回答别人的问题还是应该自己先查文档或者看一看源代码,要不然很有可能要出错的。

3) 为了让所有请求都可以模拟成DELETE等请求,只有自己写一个Filter实现和一个HttpServletRequest的装饰器

import java.io.IOException;
import java.util.Locale;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.util.Assert;
import org.springframework.web.filter.OncePerRequestFilter;

public class HttpMethodSupportFilter extends OncePerRequestFilter {

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 {

String parameterValue = request.getParameter(methodParam);

if (parameterValue != null) {
String method = parameterValue.toUpperCase(Locale.ENGLISH);
System.out.println(method);
filterChain.doFilter(new HttpServletRequestWrapper(request, method), response);
}
else {
filterChain.doFilter(request, response);
}
}

public void setMethodParam(String methodParam) {
Assert.hasLength(methodParam);
this.methodParam = methodParam;
}

// Servlet装饰器
private static class HttpServletRequestWrapper extends javax.servlet.http.HttpServletRequestWrapper {

private String method;

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

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

}
}


4) 最后一点,如果使用Form提交模拟DELETE请求等时候,要注意到Form是否有文件上传,如果有的话,也不能忘记把
org.springframework.web.multipart.support.MultipartFilter
配置在HttpMethodSupportFilter前面。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值