Spring Interceptor Tutorial
06.15.2012
   Email
inShare0
Views: 1941


         Tweet


         0
         inShare




Spring Interceptors has the ability to pre-handle and post-handle the web requests. Each
interceptor class should extend the HandlerInterceptorAdapter class. Here we will create a
Logger Interceptor by extending the HandlerInterceptorAdapter class. You can override any
of the three callback methods preHandle(), postHandle() and afterCompletion(). As the
names indicate the preHandle() method will be called before handling the request, the
postHandle() method will be called after handling the request and the afterCompletion()
method will be called after rendering the view.

In each method we will log information using log4j. First instantiate the logger in the static
context, then set up the basic configuration so that the log messages will be logged on the
console.

The LoggerInterceptor class is shown below.

package com.vaannila.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import    org.apache.log4j.BasicConfigurator;
import    org.apache.log4j.Logger;
import    org.springframework.web.servlet.ModelAndView;
import    org.springframework.web.servlet.handler. HandlerInterceptorAdapter;

public class LoggerInterceptor extends HandlerInterceptorAdapter {

           static Logger logger = Logger.getLogger(LoggerInterceptor.class);

           static{
                     BasicConfigurator.configure();
           }

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

         @Override
         public void postHandle(HttpServletRequest request,
                         HttpServletResponse response, Object handler,
                         ModelAndView modelAndView) throws Exception {
                 logger.info("After handling the request");
                 super.postHandle(request, response, handler, modelAndView);
         }

        @Override
        public void afterCompletion(HttpServletRequest request,
                        HttpServletResponse response, Object handler,
Exception ex)
                        throws Exception {
                logger.info("After rendering the view");
                super.afterCompletion(request, response, handler, ex);
        }
}

 Now the logger interceptor is created you need to associate this interceptor with the handler
mapping. Here we use BeanNameUrlHandlerMapping, incase you are using more than one
handler mapping you need to associate the interceptor with each one of them. The code below
shows how to associate an interceptor with the handler mapping.

<?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:p="http://www.springframework.org/schema/p"
        xsi:schemaLocation="http://www.springframework.org/schema/beans
    http://www.springframework.org/schema/beans/spring-beans.xsd">

       <bean id="viewResolver" class="org.springframework.web.servlet.view.
InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

    <bean id="handlerMapping"
class="org.springframework.web.servlet.handler. BeanNameUrlHandlerMapping"
p:interceptors-ref="loggerInterceptor" />

    <bean id="loggerInterceptor"
class="com.vaannila.interceptor.LoggerInterceptor" />

     <bean id="userService" class="com.vaannila.service.UserServiceImpl" />

        <bean name="/userRegistration.htm"
class="com.vaannila.web.UserController" p:userService-ref="userService"
p:formView="userForm" p:successView="userSuccess" />

</beans>

When you execute the example you can see the log messages getting dispalyed on the
console.

You can download and try the example here.
Spring Interceptor Using Annotation
Tutorial
06.15.2012

   Email




Views: 701




If you are using annotated Spring controllers, the only change that you need to do to the
previous interceptor example is the configuration. In the Spring bean configuration file
instead of using BeanNameUrlHandlerMapping or any other handler mapping use
DefaultAnnotationHandlerMapping. The configuration file is shown below.

view source



print?

01.<?xml version="1.0" encoding="UTF-8"?>

02.<beans xmlns="http://www.springframework.org/schema/beans"

03.    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"

04.        xmlns:context="http://www.springframework.org/schema/context"

05.        xsi:schemaLocation="http://www.springframework.org/schema/beans ;

06.        http://www.springframework.org/schema/beans/spring-beans.xsd

07.        http://www.springframework.org/schema/context ;

08.        http://www.springframework.org/schema/context/spring-context.xsd">

09.
10.    <bean id="viewResolver" class="org.springframework.web.servlet.view.
InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />

11.

12.    <bean class="org.springframework.web.servlet.mvc.annotation.
DefaultAnnotationHandlerMapping" p:interceptors-ref="loggerInterceptor" />

13.

14.    <context:component-scan base-package="com.vaannila.web" />

15.

16.    <bean id="loggerInterceptor"
class="com.vaannila.interceptor.LoggerInterceptor" />

17.

18.    <bean id="userService" class="com.vaannila.service.UserServiceImpl"
/>

19.

20.</beans>

More Related Content

PDF
XamarinとAWSをつないでみた話
PDF
Javascript Frameworks for Joomla
PPTX
AngularJS $http Interceptors (Explanation and Examples)
PDF
20140510 Twitter Authentication by WebAuthentictionBroker in Windows Phone 8....
PPTX
Retrofit Web Forms with MVC & T4
PDF
Patterns Are Good For Managers
DOCX
MVest Spring Job Execution
PDF
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
XamarinとAWSをつないでみた話
Javascript Frameworks for Joomla
AngularJS $http Interceptors (Explanation and Examples)
20140510 Twitter Authentication by WebAuthentictionBroker in Windows Phone 8....
Retrofit Web Forms with MVC & T4
Patterns Are Good For Managers
MVest Spring Job Execution
#30.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...

What's hot (20)

PPTX
AngularJS - $http & $resource Services
PDF
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
PDF
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
PDF
스프링 시큐리티로 시작하는 웹 어플리케이션 보안
PDF
Neues aus dem Tindergarten: Auswertung "privater" APIs mit Apache Ignite
PDF
Complex Architectures in Ember
PDF
PDF
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
DOCX
javascript code for mysql database connection
PDF
What happens in laravel 4 bootstraping
PDF
Getting Started-with-Laravel
PDF
Mastering Spring Boot's Actuator with Madhura Bhave
TXT
Conexcion java mysql
PDF
Swift Delhi: Practical POP
PPTX
Asp.net identity 2.0
PDF
Angular promises and http
PPTX
Jsp session 3
PPTX
AngularJS Routing
PDF
Struts database access
AngularJS - $http & $resource Services
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
스프링 시큐리티로 시작하는 웹 어플리케이션 보안
Neues aus dem Tindergarten: Auswertung "privater" APIs mit Apache Ignite
Complex Architectures in Ember
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
javascript code for mysql database connection
What happens in laravel 4 bootstraping
Getting Started-with-Laravel
Mastering Spring Boot's Actuator with Madhura Bhave
Conexcion java mysql
Swift Delhi: Practical POP
Asp.net identity 2.0
Angular promises and http
Jsp session 3
AngularJS Routing
Struts database access
Ad

Viewers also liked (8)

PPTX
Creativity
DOCX
DOCX
Akash gupta
PDF
Carta al director del sri y reacciones mediáticas
PPT
Primary health-care-2-1232967837997879-3
PDF
Nasa hukay ang isang paa ng manganganak
PPT
An approach to a child with abnormal movement
PDF
Informe CIP 2015
Creativity
Akash gupta
Carta al director del sri y reacciones mediáticas
Primary health-care-2-1232967837997879-3
Nasa hukay ang isang paa ng manganganak
An approach to a child with abnormal movement
Informe CIP 2015
Ad

Similar to Spring 3.0 (20)

PDF
Struts tutorial
PPT
Jsp/Servlet
PDF
Trustparency web doc spring 2.5 & hibernate
PDF
Rich Portlet Development in uPortal
PDF
HTTP, JSP, and AJAX.pdf
PDF
PDF
Building Applications Using Ajax
PPTX
Spine.js
PDF
Servletand sessiontracking
PDF
Ember.js - A JavaScript framework for creating ambitious web applications
PDF
What's new in jQuery 1.5
PDF
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
PDF
Bonnes pratiques de développement avec Node js
PPS
Struts Java I I Lecture 8
PPTX
Request dispacther interface ppt
PDF
May 2010 - RestEasy
PPT
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
PDF
MeetJS Summit 2016: React.js enlightenment
PPT
Servlet 3.0
Struts tutorial
Jsp/Servlet
Trustparency web doc spring 2.5 & hibernate
Rich Portlet Development in uPortal
HTTP, JSP, and AJAX.pdf
Building Applications Using Ajax
Spine.js
Servletand sessiontracking
Ember.js - A JavaScript framework for creating ambitious web applications
What's new in jQuery 1.5
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Bonnes pratiques de développement avec Node js
Struts Java I I Lecture 8
Request dispacther interface ppt
May 2010 - RestEasy
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
MeetJS Summit 2016: React.js enlightenment
Servlet 3.0

Recently uploaded (20)

PDF
A novel scalable deep ensemble learning framework for big data classification...
PDF
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
PDF
August Patch Tuesday
PDF
Taming the Chaos: How to Turn Unstructured Data into Decisions
PPT
Geologic Time for studying geology for geologist
PDF
sustainability-14-14877-v2.pddhzftheheeeee
PDF
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
PDF
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
PDF
NewMind AI Weekly Chronicles – August ’25 Week III
PPTX
observCloud-Native Containerability and monitoring.pptx
PPTX
Tartificialntelligence_presentation.pptx
PDF
STKI Israel Market Study 2025 version august
PDF
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
PDF
A comparative study of natural language inference in Swahili using monolingua...
PDF
1 - Historical Antecedents, Social Consideration.pdf
PDF
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
PDF
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
PDF
Univ-Connecticut-ChatGPT-Presentaion.pdf
PPTX
Modernising the Digital Integration Hub
PDF
CloudStack 4.21: First Look Webinar slides
A novel scalable deep ensemble learning framework for big data classification...
How ambidextrous entrepreneurial leaders react to the artificial intelligence...
August Patch Tuesday
Taming the Chaos: How to Turn Unstructured Data into Decisions
Geologic Time for studying geology for geologist
sustainability-14-14877-v2.pddhzftheheeeee
Transform Your ITIL® 4 & ITSM Strategy with AI in 2025.pdf
ENT215_Completing-a-large-scale-migration-and-modernization-with-AWS.pdf
NewMind AI Weekly Chronicles – August ’25 Week III
observCloud-Native Containerability and monitoring.pptx
Tartificialntelligence_presentation.pptx
STKI Israel Market Study 2025 version august
Microsoft Solutions Partner Drive Digital Transformation with D365.pdf
A comparative study of natural language inference in Swahili using monolingua...
1 - Historical Antecedents, Social Consideration.pdf
From MVP to Full-Scale Product A Startup’s Software Journey.pdf
TrustArc Webinar - Click, Consent, Trust: Winning the Privacy Game
Univ-Connecticut-ChatGPT-Presentaion.pdf
Modernising the Digital Integration Hub
CloudStack 4.21: First Look Webinar slides

Spring 3.0

  • 1. Spring Interceptor Tutorial 06.15.2012 Email inShare0 Views: 1941 Tweet 0 inShare Spring Interceptors has the ability to pre-handle and post-handle the web requests. Each interceptor class should extend the HandlerInterceptorAdapter class. Here we will create a Logger Interceptor by extending the HandlerInterceptorAdapter class. You can override any of the three callback methods preHandle(), postHandle() and afterCompletion(). As the names indicate the preHandle() method will be called before handling the request, the postHandle() method will be called after handling the request and the afterCompletion() method will be called after rendering the view. In each method we will log information using log4j. First instantiate the logger in the static context, then set up the basic configuration so that the log messages will be logged on the console. The LoggerInterceptor class is shown below. package com.vaannila.interceptor; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.log4j.BasicConfigurator; import org.apache.log4j.Logger; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.handler. HandlerInterceptorAdapter; public class LoggerInterceptor extends HandlerInterceptorAdapter { static Logger logger = Logger.getLogger(LoggerInterceptor.class); static{ BasicConfigurator.configure(); } @Override public boolean preHandle(HttpServletRequest request,
  • 2. HttpServletResponse response, Object handler) throws Exception { logger.info("Before handling the request"); return super.preHandle(request, response, handler); } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { logger.info("After handling the request"); super.postHandle(request, response, handler, modelAndView); } @Override public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception { logger.info("After rendering the view"); super.afterCompletion(request, response, handler, ex); } } Now the logger interceptor is created you need to associate this interceptor with the handler mapping. Here we use BeanNameUrlHandlerMapping, incase you are using more than one handler mapping you need to associate the interceptor with each one of them. The code below shows how to associate an interceptor with the handler mapping. <?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:p="http://www.springframework.org/schema/p" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <bean id="viewResolver" class="org.springframework.web.servlet.view. InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> <bean id="handlerMapping" class="org.springframework.web.servlet.handler. BeanNameUrlHandlerMapping" p:interceptors-ref="loggerInterceptor" /> <bean id="loggerInterceptor" class="com.vaannila.interceptor.LoggerInterceptor" /> <bean id="userService" class="com.vaannila.service.UserServiceImpl" /> <bean name="/userRegistration.htm" class="com.vaannila.web.UserController" p:userService-ref="userService" p:formView="userForm" p:successView="userSuccess" /> </beans> When you execute the example you can see the log messages getting dispalyed on the console. You can download and try the example here.
  • 3. Spring Interceptor Using Annotation Tutorial 06.15.2012 Email Views: 701 If you are using annotated Spring controllers, the only change that you need to do to the previous interceptor example is the configuration. In the Spring bean configuration file instead of using BeanNameUrlHandlerMapping or any other handler mapping use DefaultAnnotationHandlerMapping. The configuration file is shown below. view source print? 01.<?xml version="1.0" encoding="UTF-8"?> 02.<beans xmlns="http://www.springframework.org/schema/beans" 03. xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p" 04. xmlns:context="http://www.springframework.org/schema/context" 05. xsi:schemaLocation="http://www.springframework.org/schema/beans ; 06. http://www.springframework.org/schema/beans/spring-beans.xsd 07. http://www.springframework.org/schema/context ; 08. http://www.springframework.org/schema/context/spring-context.xsd"> 09.
  • 4. 10. <bean id="viewResolver" class="org.springframework.web.servlet.view. InternalResourceViewResolver" p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" /> 11. 12. <bean class="org.springframework.web.servlet.mvc.annotation. DefaultAnnotationHandlerMapping" p:interceptors-ref="loggerInterceptor" /> 13. 14. <context:component-scan base-package="com.vaannila.web" /> 15. 16. <bean id="loggerInterceptor" class="com.vaannila.interceptor.LoggerInterceptor" /> 17. 18. <bean id="userService" class="com.vaannila.service.UserServiceImpl" /> 19. 20.</beans>