根据http://patrickgrimard.com/2013/12/12/cross-origin-resource-sharing-cors-requests-with-spring-mvc/,我正在尝试处理SOP,我需要设置一个过滤器和一个拦截器。
我在web.xml中设置了过滤器:
<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>base.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<servlet-name>rest</servlet-name>
</filter-mapping>
SimpleCORSFilter在哪里
@Component
public class SimpleCORSFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res, FilterChain filterChain)
throws ServletException, IOException {
HttpServletResponse response = (HttpServletResponse) res;
response.setHeader("Access-Control-Allow-Origin", "*");
response.setHeader("Access-Control-Allow-Methods",
"POST, GET, OPTIONS, DELETE");
response.setHeader("Access-Control-Max-Age", "3600");
response.setHeader("Access-Control-Allow-Headers", "x-requested-with,Content-Type");
filterChain.doFilter(req, res);
}
之所以有效,是因为我的测试POST请求已被捕获和处理。现在,我尝试配置以下拦截器:
@Component
public class SimpleCORSInterceptor extends HandlerInterceptorAdapter {
@Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
response.addHeader("Access-Control-Allow-Origin", "*");
return true;
}
}
并且我在rest-servlet.xml中添加了以下配置(由于正确调用了REST服务,因此可以使用):
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.0.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">
<context:component-scan base-package="com.lh.clte.web" />
<mvc:annotation-driven />
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/*" />
<bean class="base.SimpleCORSInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
但是,未调用重写的方法。我想念什么?
最佳答案
在本文中,过滤器仅用于使用OPTION
方法的请求,而拦截器则用于“实际”调用。在您的示例中,所有请求都将由过滤器和拦截器处理。因此,您不需要拦截器。
此外,仅在存在处理请求的控制器方法时才调用拦截器。当您调用未映射的URL时,则不会调用拦截器。
顺便说一句:不需要@Component
。
关于java - 在Spring MVC中设置拦截器,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/25503061/