SlideShare a Scribd company logo
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

What's hot

AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource Services
Eyal Vardi
 
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
#29.스프링프레임워크 & 마이바티스 (Spring Framework, MyBatis)_스프링프레임워크 강좌, 재직자환급교육,실업자국비지원...
탑크리에듀(구로디지털단지역3번출구 2분거리)
 
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
[Srijan Wednesday Webinars] Ruling Drupal 8 with #d8rules
Srijan Technologies
 
스프링 시큐리티로 시작하는 웹 어플리케이션 보안
스프링 시큐리티로 시작하는 웹 어플리케이션 보안스프링 시큐리티로 시작하는 웹 어플리케이션 보안
스프링 시큐리티로 시작하는 웹 어플리케이션 보안
HyungTae Lim
 
Neues aus dem Tindergarten: Auswertung "privater" APIs mit Apache Ignite
Neues aus dem Tindergarten: Auswertung "privater" APIs mit Apache IgniteNeues aus dem Tindergarten: Auswertung "privater" APIs mit Apache Ignite
Neues aus dem Tindergarten: Auswertung "privater" APIs mit Apache Ignite
QAware GmbH
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in Ember
Matthew Beale
 
Fw1
Fw1Fw1
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.SundaySpout - Building a RESTful web app with Angular.js and BEAR.Sunday
Spout - Building a RESTful web app with Angular.js and BEAR.Sunday
Richard McIntyre
 
javascript code for mysql database connection
javascript code for mysql database connectionjavascript code for mysql database connection
javascript code for mysql database connection
Hitesh Kumar Markam
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstraping
Jace Ju
 
Getting Started-with-Laravel
Getting Started-with-LaravelGetting Started-with-Laravel
Getting Started-with-Laravel
Mindfire Solutions
 
Mastering Spring Boot's Actuator with Madhura Bhave
Mastering Spring Boot's Actuator with Madhura BhaveMastering Spring Boot's Actuator with Madhura Bhave
Mastering Spring Boot's Actuator with Madhura Bhave
VMware Tanzu
 
Conexcion java mysql
Conexcion java mysqlConexcion java mysql
Conexcion java mysql
jbersosa
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POP
Natasha Murashev
 
Asp.net identity 2.0
Asp.net identity 2.0Asp.net identity 2.0
Asp.net identity 2.0
Gelis Wu
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and http
Alexe Bogdan
 
Jsp session 3
Jsp   session 3Jsp   session 3
Jsp session 3
Anuj Singh Rajput
 
PHP MVC
PHP MVCPHP MVC
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS Routing
Eyal Vardi
 
Struts database access
Struts database accessStruts database access
Struts database access
Abass Ndiaye
 

What's hot (20)

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

Viewers also liked

Creativity
Creativity Creativity
Creativity
demi0523
 
Sania
SaniaSania
Akash gupta
Akash guptaAkash gupta
Akash gupta
Akash Gupta
 
Carta al director del sri y reacciones mediáticas
Carta al director del sri y reacciones mediáticasCarta al director del sri y reacciones mediáticas
Carta al director del sri y reacciones mediáticas
CámaraCIP
 
Primary health-care-2-1232967837997879-3
Primary health-care-2-1232967837997879-3Primary health-care-2-1232967837997879-3
Primary health-care-2-1232967837997879-3
Carmen Columna
 
Nasa hukay ang isang paa ng manganganak
Nasa hukay ang isang paa ng manganganakNasa hukay ang isang paa ng manganganak
Nasa hukay ang isang paa ng manganganak
Carmen Columna
 
An approach to a child with abnormal movement
An approach to a child with abnormal movementAn approach to a child with abnormal movement
An approach to a child with abnormal movement
Sunil Agrawal
 
Informe CIP 2015
Informe CIP 2015Informe CIP 2015
Informe CIP 2015
CámaraCIP
 

Viewers also liked (8)

Creativity
Creativity Creativity
Creativity
 
Sania
SaniaSania
Sania
 
Akash gupta
Akash guptaAkash gupta
Akash gupta
 
Carta al director del sri y reacciones mediáticas
Carta al director del sri y reacciones mediáticasCarta al director del sri y reacciones mediáticas
Carta al director del sri y reacciones mediáticas
 
Primary health-care-2-1232967837997879-3
Primary health-care-2-1232967837997879-3Primary health-care-2-1232967837997879-3
Primary health-care-2-1232967837997879-3
 
Nasa hukay ang isang paa ng manganganak
Nasa hukay ang isang paa ng manganganakNasa hukay ang isang paa ng manganganak
Nasa hukay ang isang paa ng manganganak
 
An approach to a child with abnormal movement
An approach to a child with abnormal movementAn approach to a child with abnormal movement
An approach to a child with abnormal movement
 
Informe CIP 2015
Informe CIP 2015Informe CIP 2015
Informe CIP 2015
 

Similar to Spring 3.0

Struts tutorial
Struts tutorialStruts tutorial
Struts tutorial
OPENLANE
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
Sunil OS
 
Trustparency web doc spring 2.5 & hibernate
Trustparency web doc   spring 2.5 & hibernateTrustparency web doc   spring 2.5 & hibernate
Trustparency web doc spring 2.5 & hibernate
trustparency
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortal
Jennifer Bourey
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdf
Arumugam90
 
RESTEasy
RESTEasyRESTEasy
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajax
s_pradeep
 
Spine.js
Spine.jsSpine.js
Spine.js
wearefractal
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontracking
vamsi krishna
 
Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications  Ember.js - A JavaScript framework for creating ambitious web applications
Ember.js - A JavaScript framework for creating ambitious web applications
Juliana Lucena
 
What's new in jQuery 1.5
What's new in jQuery 1.5What's new in jQuery 1.5
What's new in jQuery 1.5
Martin Kleppe
 
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Servlets 3.0 - Asynchronous, Extensibility, Ease-of-use @ JavaOne Brazil 2010
Arun Gupta
 
Bonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node jsBonnes pratiques de développement avec Node js
Bonnes pratiques de développement avec Node js
Francois Zaninotto
 
Struts Java I I Lecture 8
Struts  Java  I I  Lecture 8Struts  Java  I I  Lecture 8
Struts Java I I Lecture 8
patinijava
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
Taha Malampatti
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
JBug Italy
 
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...Project Description Of Incident Management System Developed by PRS (CRIS) , N...
Project Description Of Incident Management System Developed by PRS (CRIS) , N...
varunsunny21
 
Ajax
AjaxAjax
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenment
Artur Szott
 
Servlet 3.0
Servlet 3.0Servlet 3.0
Servlet 3.0
Minh Hoang
 

Similar to Spring 3.0 (20)

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

Recently uploaded

Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
Hiroshi SHIBATA
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Neo4j
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
c5vrf27qcz
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
Chart Kalyan
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
MichaelKnudsen27
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
Zilliz
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Edge AI and Vision Alliance
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
AstuteBusiness
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Tosin Akinosho
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
Fwdays
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
Neo4j
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
Zilliz
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
DianaGray10
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
akankshawande
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
Safe Software
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
Ajin Abraham
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
Neo4j
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
Jakub Marek
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
saastr
 

Recently uploaded (20)

Introduction of Cybersecurity with OSS at Code Europe 2024
Introduction of Cybersecurity with OSS  at Code Europe 2024Introduction of Cybersecurity with OSS  at Code Europe 2024
Introduction of Cybersecurity with OSS at Code Europe 2024
 
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and BioinformaticiansBiomedical Knowledge Graphs for Data Scientists and Bioinformaticians
Biomedical Knowledge Graphs for Data Scientists and Bioinformaticians
 
Y-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PPY-Combinator seed pitch deck template PP
Y-Combinator seed pitch deck template PP
 
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfHow to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdf
 
Nordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptxNordic Marketo Engage User Group_June 13_ 2024.pptx
Nordic Marketo Engage User Group_June 13_ 2024.pptx
 
Generating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and MilvusGenerating privacy-protected synthetic data using Secludy and Milvus
Generating privacy-protected synthetic data using Secludy and Milvus
 
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
 
Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |Astute Business Solutions | Oracle Cloud Partner |
Astute Business Solutions | Oracle Cloud Partner |
 
Monitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdfMonitoring and Managing Anomaly Detection on OpenShift.pdf
Monitoring and Managing Anomaly Detection on OpenShift.pdf
 
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk"Frontline Battles with DDoS: Best practices and Lessons Learned",  Igor Ivaniuk
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor Ivaniuk
 
Leveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and StandardsLeveraging the Graph for Clinical Trials and Standards
Leveraging the Graph for Clinical Trials and Standards
 
Fueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte WebinarFueling AI with Great Data with Airbyte Webinar
Fueling AI with Great Data with Airbyte Webinar
 
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectorsConnector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
Connector Corner: Seamlessly power UiPath Apps, GenAI with prebuilt connectors
 
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development ProvidersYour One-Stop Shop for Python Success: Top 10 US Python Development Providers
Your One-Stop Shop for Python Success: Top 10 US Python Development Providers
 
Essentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation ParametersEssentials of Automations: Exploring Attributes & Automation Parameters
Essentials of Automations: Exploring Attributes & Automation Parameters
 
AppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSFAppSec PNW: Android and iOS Application Security with MobSF
AppSec PNW: Android and iOS Application Security with MobSF
 
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge GraphGraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
GraphRAG for LifeSciences Hands-On with the Clinical Knowledge Graph
 
Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving | Nameplate Manufacturing Process - 2024
Northern Engraving | Nameplate Manufacturing Process - 2024
 
Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)Main news related to the CCS TSI 2023 (2023/1695)
Main news related to the CCS TSI 2023 (2023/1695)
 
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
Deep Dive: AI-Powered Marketing to Get More Leads and Customers with HyperGro...
 

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>