浏览器只能发起get,post请求,通过添加Filter改变请求类型
package com;
import java.io.IOException;
import java.util.Locale;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
public class HiddenHttpMethodFilter implements javax.servlet.Filter {
/**
* 默认请求名称
* Default method parameter: <code>_method</code>
*/
public static final String DEFAULT_METHOD_PARAM = "_method";
/**
* 支持转换的类型
*/
public static final String[] SUPPORT_METHODS =new String[]{"PUT","DELETE"};
private String methodParam = DEFAULT_METHOD_PARAM;
public void destroy() {
}
public void doFilter(ServletRequest servletrequest,
ServletResponse servletresponse, FilterChain filterchain)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletrequest;
HttpServletResponse response = (HttpServletResponse) servletresponse;
String paramValue = request.getParameter(this.methodParam);
if ("POST".equals(request.getMethod())
&& StringUtils.isNotBlank(paramValue)) {
String method = paramValue.toUpperCase(Locale.ENGLISH);
if(isSupportMethod(method)){
request = new HttpMethodRequestWrapper(request,method);
}
filterchain.doFilter(request, response);
} else {
filterchain.doFilter(request, response);
}
}
public void init(FilterConfig filterconfig) throws ServletException {
String initMethodParam = filterconfig.getInitParameter("methodParam");
methodParam = StringUtils.isNotBlank(initMethodParam) ? initMethodParam
: DEFAULT_METHOD_PARAM;
}
public void setMethodParam(String methodParam) {
this.methodParam = methodParam;
}
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;
}
}
/**
* 是否是支持的转换类型
* @param method
* @return
*/
private static boolean isSupportMethod(String method){
for (int i = 0; i < SUPPORT_METHODS.length; i++) {
String support_method = SUPPORT_METHODS[i];
if(support_method.equalsIgnoreCase(method)){
return true;
}
}
return false;
}
}
Web.xml配置
<filter>
<filter-name>HiddenHttpMethodFilter</filter-name>
<filter-class>com.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>HiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
页面发起请求时在页面加入隐藏域,只有当请求为Post时,才进行转换
<input type="hidden" name="_method" value="PUT">