为什么找不到@Component Spring Filter?

时间:2014-10-27 21:17:37

标签: java spring spring-mvc filter

我已经实现了COrs Filter来处理CORS。但Spring没有找到过滤器。所以我仍然有以下错误:

XMLHttpRequest cannot load http://localhost:8080/app-web/user/create. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.

这是Cors Filter:包com.day.jobly.web.filters;

@Component
public class SimpleCORSFilter implements Filter {


    @Override
    public void destroy() {

    }


    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException,
            ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST,PUT, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
        System.out.println("DO FILTER 
        chain.doFilter(req, res);

    }


    @Override
    public void init(FilterConfig config) throws ServletException {

    }

} 

这是我的Spring Config:

应用-servlet.xml中

<?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:util="http://www.springframework.org/schema/util"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans

http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/util
http://www.springframework.org/schema/util/spring-util.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">

<!-- activates various annotations to be detected in bean classes -->
<context:annotation-config />
    <!-- Scans the classpath of this application for @Bean to deploy as beans -->
    <context:component-scan
        base-package="com.day.jobly.web.controllers,com.day.jobly.web.security,com.day.jobly.web.filters,com.day.jobly.services" />
    <!-- Configures Handler Interceptors -->
    <mvc:interceptors>
        <!-- Changes the locale when a 'locale' request parameter is sent; e.g. 
            /?locale=de -->
        <bean class="org.springframework.web.servlet.i18n.LocaleChangeInterceptor" />
    </mvc:interceptors>

    <!-- Saves a locale change using a cookie -->
    <bean id="localeResolver"
        class="org.springframework.web.servlet.i18n.CookieLocaleResolver" />
    <!-- Application Message Bundle -->
    <bean id="messageSource"
        class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
        <property name="basenames">
            <list>
                <value>../resources/properties/clientMessages</value>
            </list>
        </property>
        <property name="cacheSeconds" value="0" />
    </bean>


    <!-- all resources inside folder src/main/webapp/resources are mapped so 
        they can be refered to inside JSP files (see header.jsp for more details) -->
    <mvc:resources mapping="/**" location="/" />

    <mvc:annotation-driven>
  <mvc:message-converters>
   <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
  </mvc:message-converters>
    </mvc:annotation-driven> 


</beans>

应用-daos.xml

<?xml version="1.0" encoding="UTF-8"?>
<!-- Repository and Service layers -->
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
    xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:jpa="http://www.springframework.org/schema/data/jpa"
    xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/data/jpa http://www.springframework.org/schema/data/jpa/spring-jpa.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">


    <jpa:repositories base-package="com.day.jobly.dao"  entity-manager-factory-ref="myEmf"/>

    <alias alias="entityManagerFactory" name="myEmf"/>

        <bean id="myEmf"
        class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        <property name="dataSource" ref="dataSource" />
        <property name="jpaVendorAdapter">
            <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
                <property name="showSql" value="true" />
                <property name="databasePlatform" value="org.hibernate.dialect.HSQLDialect" />
                <property name="generateDdl" value="true" />
            </bean>
        </property>
        <property name="packagesToScan" value="com.day.jobly.entities" />
    </bean>

    <bean id="dataSource"
        class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="org.hsqldb.jdbcDriver" />
        <property name="url" value="jdbc:hsqldb:file:db/jobly" />
        <property name="username" value="sa" />
        <property name="password" value="" />
    </bean>


    <bean class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor" />


    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
        <property name="entityManagerFactory" ref="myEmf"/>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean   class="org.springframework.dao.annotation.PersistenceExceptionTranslationPostProcessor"/>

    <bean   class="org.springframework.orm.jpa.support.PersistenceAnnotationBeanPostProcessor"/>

    <bean class="com.day.jobly.web.debug.HsqlManager" init-method="init"
        depends-on="myEmf" /> 


</beans>

这是web.xml

<web-app id="WebApp_ID" version="2.4"  xmlns="http://java.sun.com/xml/ns/j2ee"
 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

 <display-name>Archetype Created Web Application</display-name>

 <listener>
<listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>
</listener>
  <listener>
 <listener-class>
 org.springframework.web.context.ContextLoaderListener
 </listener-class>
 </listener>
<listener>
<listener-class>
org.springframework.security.web.session.HttpSessionEventPublisher
</listener-class>
</listener>

 <servlet>
 <servlet-name>app</servlet-name>
 <servlet-class>
 org.springframework.web.servlet.DispatcherServlet
 </servlet-class>
       <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring/app-servlet.xml,classpath:spring/app-daos.xml</param-value>
        </init-param>
 <load-on-startup>1</load-on-startup>
 </servlet>

 <servlet-mapping>
 <servlet-name>app</servlet-name>
 <url-pattern>/</url-pattern>
 </servlet-mapping>


 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>
 classpath:spring/app-servlet.xml, classpath:spring/app-daos.xml
 </param-value>
 </context-param>


<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
<init-param>
<param-name>forceEncoding</param-name>
<param-value>true</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



</web-app>

为什么此配置<context:annotation-config />不起作用?

1 个答案:

答案 0 :(得分:0)

您需要在web.xml中注册过滤器,而不是在spring上下文中注册。

要在web.xml中注册,请添加类似于characterEncodingFilter的xml片段:

<filter>
  <filter-name>corsFilter</filter-name>
  <filter-class>com.day.jobly.web.filters.SimpleCORSFilter</filter-class>
</filter> 
<filter-mapping>
  <filter-name>corsFilter</filter-name>
  <url-pattern>/*</url-pattern>
</filter-mapping> 

如果您需要添加“spring-bean”作为网络过滤器:

  1. 您可以使用delegating filter proxylike spring-security does
  2. 您也可以使用WebAppInitializer,但这更复杂。