行。所以问题是当我在调试模式下运行应用程序时,它确实进入enabled
的setter并且设置为false,但是当调用doFilter
时enabled
总是为真。 / p>
为了清楚起见,我删除了一些评论; - )。
public class CorsFilter extends GenericFilterBean {
private String allowedOrigins = "^(https?://([a-zA-Z][a-zA-Z0-9\\-]*\\.)?(local|localhost)(:[0-9]+)?$";
private boolean enabled = true;
@Value("${cors.enabled}")
public void setEnabled(String enabled) {
if (enabled != null) {
this.enabled = enabled.matches("^[ \\t]*(true|1|yes)[ \\t]*$");
}
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException
{
if (isEnabled()) {
HttpServletResponse res = (HttpServletResponse) response;
HttpServletRequest req = (HttpServletRequest) request;
String requestOrigin = req.getHeader("Origin");
// ignore when origin empty or not given or not matched
if (requestOrigin != null && !requestOrigin.isEmpty() && requestOrigin.matches(getAllowedOrigins())) {
res.addHeader("Access-Control-Allow-Origin", requestOrigin);
res.addHeader("Access-Control-Allow-Credentials", "true");
res.addHeader("Access-Control-Allow-Headers", "Accept,Authorization,Origin,Content-type");
}
}
chain.doFilter(request, response);
}
public String getAllowedOrigins() {
return allowedOrigins;
}
public boolean isEnabled() {
return enabled;
}
}
在beans.xml中:
<bean id="CorsFilter" class="saas.web.filter.CorsFilter" />
在属性文件中:
cors.enabled=false
在web.xml中
<!-- CORS -->
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>saas.web.filter.CorsFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CorsFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
答案 0 :(得分:2)
webapplication使用的实际过滤器不是当前配置中spring创建的过滤器。你必须使用DelegatingFilterProxy来使用spring创建的bean。
如下更改web.xml文件中的过滤器可能会起到作用:
<filter>
<filter-name>CorsFilter</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>