使用过滤器时AutoWire问题

时间:2016-03-22 06:12:32

标签: java spring hibernate url servlet-filters

我正在使用过滤器类但在会话的自动接线期间出现了工厂空指针异常,我的代码如下:

@Repository
public class UrlDaoImpl implements UrlDao{

    @Autowired
    SessionFactory sessionFactory;

    @Override
    public MerchnatDetails getMerchantByUrl(String enterdUrl) {




    MerchnatDetails merDetails=null;

    try{
        System.out.println("inside Dao");



    merDetails=new MerchnatDetails();
    Session session=sessionFactory.openSession();

    session=sessionFactory.getCurrentSession();
    Criteria  criteria=session.createCriteria(MerchnatDetails.class);

    //criteria.add(Restrictions.ilike("merchantSubUrl", enterdUrl));

    merDetails=(MerchnatDetails) criteria.uniqueResult();
    }catch(Exception e){
        e.printStackTrace();
    }


        System.out.println(merDetails.getMerchantId());
        return merDetails;
    }

这是控制台中显示的错误:

java.lang.NullPointerException
    at com.its.ecommerce.dao.UrlDaoImpl.getMerchantByUrl(UrlDaoImpl.java:37)
    at com.its.ecommerce.service.UrlServiceImpl.getCorrespodingUrl(UrlServiceImpl.java:34)
    at com.its.ecommerce.controller.AuthenticationFilter.doFilter(AuthenticationFilter.java:44)
    at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
    at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
    at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
    at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
    at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:505)
    at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:169)
    at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
    at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:956)
    at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
    at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:423)
    at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1079)
    at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:625)
    at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
    at java.lang.Thread.run(Thread.java:745)

我的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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>EcomUrl</display-name>
    <!-- The definition of the Root Spring Container shared by all Servlets 
        and Filters -->
        <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <!-- Creates the Spring Container shared by all Servlets and Filters -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <filter>
        <filter-name>AuthenticationFilter</filter-name>
        <filter-class>com.its.ecommerce.controller.AuthenticationFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>AuthenticationFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

   <filter>
        <filter-name>charsetFilter</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>
    <servlet>
        <servlet-name>appServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>/WEB-INF/applicationContext.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>appServlet</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <session-config>
        <session-timeout>25</session-timeout>
    </session-config>
  <welcome-file-list> 
    <welcome-file>index.jsp</welcome-file>
   </welcome-file-list>
</web-app>

控制器就像这样

public class AuthenticationFilter implements Filter {

    private ServletContext context;

    public void init(final FilterConfig fConfig) throws ServletException {
        this.context = fConfig.getServletContext();
        this.context.log("AuthenticationFilter initialized");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse res = (HttpServletResponse) response;
        String uri = req.getRequestURI();
        HttpSession session = req.getSession(false);
        res.setHeader("Pragma", "No-cache");
        res.setHeader("Cache-Control", "no-cache, no-store, must-revalidate");
        res.setDateHeader("Expires", 0);
        try {
            UrlServiceImpl url = new UrlServiceImpl();
            String outPutUrl = url.getCorrespodingUrl(uri);

        } catch (Exception e) {

            e.printStackTrace();
        }

        chain.doFilter(request, response);


    }

    @Override
    public void destroy() {
        // close any resources here
    }

申请背景:

<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns:beans="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
              http://www.springframework.org/schema/beans/spring-beans-4.1.xsd 
              http://www.springframework.org/schema/jdbc 
              http://www.springframework.org/schema/jdbc/spring-jdbc-4.1.xsd
              http://www.springframework.org/schema/tx 
              http://www.springframework.org/schema/tx/spring-tx-4.1.xsd
              http://www.springframework.org/schema/context
              http://www.springframework.org/schema/context/spring-context-4.1.xsd
              http://www.springframework.org/schema/mvc
              http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd">
    <context:property-placeholder location="classpath:application.properties"/>
    <context:component-scan base-package="com.its.ecommerce.*"/>
    <context:annotation-config/>
    <context:spring-configured/>
    <mvc:annotation-driven/>
    <mvc:resources mapping="/resources/**" location="/resources/"/>
    <!-- Data Source Declaration for Hibernate-->
    <beans:bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <beans:property name="driverClassName" value="${jdbc.driverClassName}"/>
        <beans:property name="url" value="${jdbc.url}"/>
        <beans:property name="username" value="${jdbc.username}"/>
        <beans:property name="password" value="${jdbc.password}"/>
    </beans:bean>
    <beans:bean id="sessionFactory" class="org.springframework.orm.hibernate4.LocalSessionFactoryBean">
        <beans:property name="dataSource" ref="dataSource"></beans:property>
        <beans:property name="packagesToScan" value="com.its.ecommerce.model"/>
        <beans:property name="hibernateProperties">
            <beans:props>
                <beans:prop key="hibernate.dialect">${hibernate.dialect}</beans:prop>
                <!-- <beans:prop key="hibernate.default_schema">dbo</beans:prop>-->
                <beans:prop key="hibernate.c3p0.min_size">${hibernate.minpool}</beans:prop>
                <beans:prop key="hibernate.c3p0.max_size">${hibernate.maxpool}</beans:prop>
                <beans:prop key="hibernate.show_sql">${hibernate.show_sql}</beans:prop>
                <beans:prop key="hibernate.format_sql">${hibernate.format_sql}</beans:prop>      
            </beans:props>
        </beans:property>
    </beans:bean>
    <!-- Enable the configuration of transactional behavior based on annotations -->
    <tx:annotation-driven transaction-manager="transactionManager"/>
    <!-- Transaction Manager is defined -->
    <beans:bean id="transactionManager" class="org.springframework.orm.hibernate4.HibernateTransactionManager">
        <beans:property name="sessionFactory" ref="sessionFactory"/>
    </beans:bean> 
    <beans:bean id="jspViewResolver"
          class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <beans:property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <beans:property name="prefix" value="/WEB-INF/view/"/>
        <beans:property name="suffix" value=".jsp"/>
    </beans:bean>
</beans:beans>

1 个答案:

答案 0 :(得分:0)

您的过滤器不是由春天管理的,因此dao不适用于自动装配

您应该使用DelegatingFilterProxy并将过滤器声明为弹簧组件。