我在我的应用程序中添加了一个CORS过滤器,但似乎没有执行(没有打印)。
过滤器是:
@Component
public class SimpleCORSFilter extends OncePerRequestFilter {
@Override
protected void doFilterInternal(HttpServletRequest req,
HttpServletResponse res, FilterChain filterChain)
throws ServletException, IOException {
System.out.println("EXECUTING");
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);
}
}
然后我在web.xml中添加了过滤器,其中包括:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<!-- The definition of the Root Spring Container shared by all Servlets
and Filters -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/spring/servlet-context.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>rest</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>rest</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>org.lh.gestorepazienti.web.SimpleCORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>simpleCORSFilter</filter-name>
<servlet-name>rest</servlet-name>
</filter-mapping>
<filter>
<filter-name>OpenSessionInViewFilter</filter-name>
<filter-class>org.springframework.orm.jpa.support.OpenEntityManagerInViewFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>OpenSessionInViewFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
哪里可能错了?
答案 0 :(得分:1)
首先,命名Root Spring Container xml文件servlet-context.xml
是 uncommon 。使用spring-mvc时,此名称通常用于DispatcherServlet
配置。您最好使用applicationContext.xml
。
但无论如何,您应该使用DelegatingProxyFilter
来正确初始化弹簧滤镜:
<filter>
<filter-name>simpleCORSFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
DelegatingProxyFilter
将在根上下文中搜索名为simpleCORSFilter
的bean,并将doFilter
方法委托给它。
答案 1 :(得分:0)
您也可以使用 URLMapping