一、tomcat层面禁用
从tomcat来禁用,表示tomcat中所有运行的应用都禁用这些请求方法
修改apache-tomcat/conf/web.xml,在<session-config></session-config>节点后面新增禁用配置:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>BDC</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>HEAD</http-method>
<http-method>TRACE</http-method>
<http-method>OPTIONS</http-method>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
二、应用层的web.xml中禁用(不推荐)
如果项目含web.xml的传统应用,按照从tomcat层禁用方式一样:
<session-config>
<session-timeout>30</session-timeout>
</session-config>
<security-constraint>
<web-resource-collection>
<web-resource-name>BDC</web-resource-name>
<url-pattern>/*</url-pattern>
<http-method>PUT</http-method>
<http-method>DELETE</http-method>
<http-method>HEAD</http-method>
<http-method>TRACE</http-method>
<http-method>OPTIONS</http-method>
</web-resource-collection>
<auth-constraint/>
</security-constraint>
三、springboot类型过滤器禁用(推荐)
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.Filter;
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.HttpServletResponse;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
@Component
@Order(Ordered.HIGHEST_PRECEDENCE)
public class CorsFilter implements Filter {
private static List<String> FORBIDDEN_METHOD = new ArrayList<String>();
static {
FORBIDDEN_METHOD.add("PUT");
FORBIDDEN_METHOD.add("DELETE");
FORBIDDEN_METHOD.add("HEAD");
FORBIDDEN_METHOD.add("TRACE");
FORBIDDEN_METHOD.add("OPTIONS");
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
if (FORBIDDEN_METHOD.contains(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_FORBIDDEN);
return;
}
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig filterConfig) {
// not needed
}
@Override
public void destroy() {
// not needed
}
}