Tomcat java web 禁用HTTP 方法
配置tomcat,conf/web.xml 或 應用的web.xml
<security-constraint> <web-resource-collection> <url-pattern>/*</url-pattern> <http-method>PUT</http-method> <http-method>DELETE</http-method> <http-method>HEAD</http-method> <http-method>OPTIONS</http-method> <http-method>TRACE</http-method> </web-resource-collection> <auth-constraint></auth-constraint> </security-constraint>
此方法,適用於靜態資源和實現了doGet、doPost方法的servelt類的服務。一般現代web應用大多採用Spring MVC架構,DispatchServelet的父類重org.springframework.web.servlet.FrameworkServlet重寫了javax.servlet.http.HttpServlet的doGet、doPost、doPut、doDelete、doOptions、doTrace,對應HTTP 的標準方法。
DispatchServelet處理每一個請求時,由javax.servlet.http.HttpServlet的service方法進行處理,因此,HTTP的標準方法都會被處理。單純的配置web.xml無法禁用掉HTTP方法。
Spring MVC 禁用HTTP OPTIONS方法 在應用的web.xml中修改spring mvc的配置:
<servlet> <servlet-name>springServlet</servlet-name> <servlet-class>s2jh.biz.util.CustomerDispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring-mvc.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> <async-supported>true</async-supported> </servlet> <servlet-mapping> <servlet-name>springServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
重寫DispatcherServlet的doOptions方法:
/** * 自訂 Spring MVC DispatcherServlet * Disabled HTTP OPTIONS METHOD */public class CustomerDispatcherServlet extends DispatcherServlet {private static final Logger LOGGER = LoggerFactory.getLogger(CustomerDispatcherServlet.class);private static final long serialVersionUID = 8018418118826214565L; private static final ResourceBundle lStrings = ResourceBundle.getBundle("javax.servlet.http.LocalStrings"); private static final String METHOD_OPTIONS = "OPTIONS"; @Overrideprotected void doOptions(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {methodNotAllowed(METHOD_OPTIONS, response);LOGGER.warn("HTTP OPTIONS DISABLED.");}/** * DISABLED HTTP METHOD * * @param methodName * @param response * @throws IOException */private void methodNotAllowed(String methodName, HttpServletResponse response) throws IOException { String errMsg = lStrings.getString("http.method_post_not_supported"); Object[] errArgs = new Object[1]; errArgs[0] = methodName; errMsg = MessageFormat.format(errMsg, errArgs); response.sendError(HttpServletResponse.SC_METHOD_NOT_ALLOWED, errMsg);}}
使用命令測試:
curl -v -X OPTIONS http:/localhost:8080/test.htm