Spring拦截器不叫

时间:2015-10-25 10:58:30

标签: java spring interceptor

我正在尝试构建一个Spring应用程序,我想记录所有请求/响应。我找到了一些例子,但没有一个例子有帮助。我试图创建拦截器来记录我需要的所有信息,但拦截器永远不会被调用 有人可以解释为什么我的拦截器不起作用吗?

我的web.xml文件

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="
        http://java.sun.com/xml/ns/javaee
        http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
         version="3.0">

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring/business-config.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <servlet>
        <servlet-name>mvc-dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>

    <servlet-mapping>
        <servlet-name>mvc-dispatcher</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

这是我的配置。

    <beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
        http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
        http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd">


    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        ...
    </bean>

    <bean id="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
        ...enter code here
    </bean>

    <mvc:annotation-driven/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*"/>
            <bean class="ltp.core.security.RequestProcessingInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

    <tx:annotation-driven/>

    <bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager"/>

    <context:component-scan base-package="ltp.core.services.impl"/>
    <context:component-scan base-package="ltp.core.security"/>
    <context:component-scan base-package="ltp.core.repositories.jpa"/>
    <context:component-scan base-package="ltp.core.utils"/>
</beans>

我的拦截器:

public class RequestProcessingInterceptor extends HandlerInterceptorAdapter      {

    private final Logger logger = Logger.getLogger(RequestProcessingInterceptor.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.info("TRALALALLALAL");
        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.info("[" + LocalDateTime.now().toString() + "] URL: " + request.getRequestURL().toString() + " Send to handler " + handler.toString());
        request.setAttribute("startTime", System.currentTimeMillis());
        super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.info("[" + LocalDateTime.now().toString() + "] Completed in " + (System.currentTimeMillis() - (Long) request.getAttribute("startTime")) + "ms ");
        super.afterCompletion(request, response, handler, ex);
    }
}

修改:
我通过移动所有与mvc相关的东西来创建mvc-dispatcher-servlet.xml。但是没有<mvc:default-servlet-handler/>它没有工作,拦截器仍然是一个问题。

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <mvc:default-servlet-handler/>
    <mvc:annotation-driven/>
    <mvc:interceptors>
        <mvc:interceptor>
            <mvc:mapping path="/*"/>
            <bean class="ltp.core.security.RequestProcessingInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>
</beans>

1 个答案:

答案 0 :(得分:0)

古老而金问题,我在春季MVC中遇到了与拦截器相同的问题,他们只是没有被调用。 找到解决方案,你应该检查几件事。首先确保将<mvc:interceptors>放入dispatcher-servlet.xml(而不是applicationContext.xml)。扩展HandlerInterceptorAdapter的拦截器类不需要任何像@Component这样的注释的Bean(因为你在xml配置中这样做了)。

一件重要的事情就是检查一下: xmlns:mvc="http://www.springframework.org/schema/mvc"

它不应该是由Intellij自动添加的/schema/c/schema/p或者......!/ / p>

这些是我的代码,以便检查所有内容:

public class MyCustomInterceptor extends HandlerInterceptorAdapter {


@Autowired
private IpClientService ipClientService;


@Override
public boolean preHandle(HttpServletRequest request, 
HttpServletResponse response, Object handler) throws Exception {

    // ------ your code here --------

    String reqUri = request.getRequestURI();
    String serviceName = reqUri.substring(reqUri.lastIndexOf("/") +1, reqUri.length());

    ......



    return super.preHandle(request, response, handler);
}

@Override
public void postHandle(HttpServletRequest request,
                       HttpServletResponse response, Object handler,
                       ModelAndView modelAndView) throws Exception {

    super.postHandle(request, response, handler, modelAndView);
}
}

我的dispatcher-servlet.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:task="http://www.springframework.org/schema/task" xmlns:mvc="http://www.springframework.org/schema/mvc"
       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/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">


    <mvc:interceptors>
        <bean class="...MyCustomInterceptor"/>
    </mvc:interceptors>


    <context:component-scan base-package="... main package"/>

    <!--this will say we are using annotations-->
    <mvc:annotation-driven/>

    <!--this will add the ability to use @Transactional-->
    <tx:annotation-driven/>

    <!--scheduling tasks-->
    <task:annotation-driven/>


    <!--adding resource directory-->
    <mvc:resources mapping="/resources/**" location="/WEB-INF/resources/"/>



    <!--in here we specify the view resolver and where it should look for views and what it should add
    as suffix to returning value in @RequestMapping (like index.jsp)-->
    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/views/"/>
        <property name="suffix" value=".jsp"/>
    </bean>




</beans>

我的web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">





    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml,
                    /WEB-INF/dispatcher-servlet.xml
        </param-value>
    </context-param>


    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>


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





</web-app>