您的位置:首页 > 理论基础 > 计算机网络

Tomcat java web 禁用HTTP 方法

2016-07-12 13:44 281 查看

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";

@Override
protected 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: