简体   繁体   English

未调用 Spring 拦截器

[英]Spring interceptor not called

I am trying to build a Spring application and I want to log all requests/responses.我正在尝试构建一个 Spring 应用程序,并且我想记录所有请求/响应。 I found some examples, but none of them helped.我找到了一些例子,但没有一个有帮助。 Am trying to create interceptor that will log all informations I need, but interceptor is never called.我正在尝试创建将记录我需要的所有信息的拦截器,但从未调用过拦截器。
Can someone explain why my interceptor in not working?有人可以解释为什么我的拦截器不起作用吗?

My web.xml file我的 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>

This is my config.这是我的配置。

    <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>

And my interceptor:还有我的拦截器:

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);
    }
}

EDIT:编辑:
I created mvc-dispatcher-servlet.xml by moving all mvc related stuff in it.我通过在其中移动所有与 mvc 相关的东西来创建mvc-dispatcher-servlet.xml But without <mvc:default-servlet-handler/> it wasn't working and interceptor is still a problem.但是如果没有<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>

Old but Gold question, I had same problem with interceptors in spring MVC, they just weren't being called. 老但黄金的问题,我在春季MVC中对拦截器也有同样的问题,只是没有被调用。 found the solution, you should just check several things. 找到解决方案后,您应该检查几件事。 first of all make sure you are putting <mvc:interceptors> into dispatcher-servlet.xml (not applicationContext.xml). 首先,确保将<mvc:interceptors>放入dispatcher-servlet.xml(而不是applicationContext.xml)中。 your interceptor class that is extending HandlerInterceptorAdapter doesn't need any Bean like annotations like @Component (because you're doing this in xml config). 您扩展HandlerInterceptorAdapter的拦截器类不需要像@Component这样的Bean之类的注释(因为您在xml配置中执行此操作)。

one important thing is to check this : xmlns:mvc="http://www.springframework.org/schema/mvc" 一件重要的事情是检查: xmlns:mvc="http://www.springframework.org/schema/mvc"

it shouldn't be /schema/c or /schema/p that are added auto by Intellij or sth! 不应是Intellij或sth自动添加的/schema/c/schema/p

these are my codes in order to check everything : 这些是我的代码,以便检查所有内容:

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);
}
}

my dispatcher-servlet.xml : 我的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>

my web.xml : 我的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>

Using XML configuration, ensure you defined the interceptors in the correct context.使用 XML 配置,确保您在正确的上下文中定义了拦截器。 Moving config from servlet context(*-servlet.xml) to main context (web.xml) made it work.将配置从 servlet 上下文 (*-servlet.xml) 移动到主上下文 (web.xml) 使其工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM