2

I am trying to build a Spring application and I want to log all requests/responses. 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-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. But without <mvc:default-servlet-handler/> it wasn't working and interceptor is still a problem.

<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>
Peter Javorka
  • 21
  • 1
  • 3

2 Answers2

0

Old but Gold question, I had same problem with interceptors in spring MVC, they just weren't being called. 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). your interceptor class that is extending HandlerInterceptorAdapter doesn't need any Bean like annotations like @Component (because you're doing this in xml config).

one important thing is to check this : 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!

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 :

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

<?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>
Samrun0
  • 76
  • 1
  • 5
  • can I ask the reason to have the namespaces mcv and avc in dispatcher-servlet.xml while both of them point to "http://www.springframework.org/schema/mvc" – user3366706 Jun 22 '17 at 23:36
  • @user3366706 you are right, namespaces are being used for solving name conflict in xml files. and both are the same in this case, i was using them randomly no big deal. as you can see i've edited the code too. thanks. – Samrun0 Jun 23 '17 at 08:03
0

Using XML configuration, ensure you defined the interceptors in the correct context. Moving config from servlet context(*-servlet.xml) to main context (web.xml) made it work.

Michael Laffargue
  • 10,116
  • 6
  • 42
  • 76