SlideShare une entreprise Scribd logo
1  sur  4
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>

Contenu connexe

Tendances

AngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesAngularJS - $http & $resource Services
AngularJS - $http & $resource ServicesEyal 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 #d8rulesSrijan 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 IgniteQAware GmbH
 
Complex Architectures in Ember
Complex Architectures in EmberComplex Architectures in Ember
Complex Architectures in EmberMatthew Beale
 
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.SundayRichard McIntyre
 
javascript code for mysql database connection
javascript code for mysql database connectionjavascript code for mysql database connection
javascript code for mysql database connectionHitesh Kumar Markam
 
What happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingWhat happens in laravel 4 bootstraping
What happens in laravel 4 bootstrapingJace Ju
 
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 BhaveVMware Tanzu
 
Conexcion java mysql
Conexcion java mysqlConexcion java mysql
Conexcion java mysqljbersosa
 
Swift Delhi: Practical POP
Swift Delhi: Practical POPSwift Delhi: Practical POP
Swift Delhi: Practical POPNatasha Murashev
 
Asp.net identity 2.0
Asp.net identity 2.0Asp.net identity 2.0
Asp.net identity 2.0Gelis Wu
 
Angular promises and http
Angular promises and httpAngular promises and http
Angular promises and httpAlexe Bogdan
 
AngularJS Routing
AngularJS RoutingAngularJS Routing
AngularJS RoutingEyal Vardi
 
Struts database access
Struts database accessStruts database access
Struts database accessAbass Ndiaye
 

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

En vedette

Creativity
Creativity Creativity
Creativity demi0523
 
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áticasCámaraCIP
 
Primary health-care-2-1232967837997879-3
Primary health-care-2-1232967837997879-3Primary health-care-2-1232967837997879-3
Primary health-care-2-1232967837997879-3Carmen 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 manganganakCarmen 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 movementSunil Agrawal
 
Informe CIP 2015
Informe CIP 2015Informe CIP 2015
Informe CIP 2015CámaraCIP
 

En vedette (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
 

Similaire à Spring 3.0

Struts tutorial
Struts tutorialStruts tutorial
Struts tutorialOPENLANE
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil 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 & hibernatetrustparency
 
Rich Portlet Development in uPortal
Rich Portlet Development in uPortalRich Portlet Development in uPortal
Rich Portlet Development in uPortalJennifer Bourey
 
HTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfHTTP, JSP, and AJAX.pdf
HTTP, JSP, and AJAX.pdfArumugam90
 
Building Applications Using Ajax
Building Applications Using AjaxBuilding Applications Using Ajax
Building Applications Using Ajaxs_pradeep
 
Servletand sessiontracking
Servletand sessiontrackingServletand sessiontracking
Servletand sessiontrackingvamsi 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.5Martin 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 2010Arun 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 jsFrancois Zaninotto
 
Struts Java I I Lecture 8
Struts  Java  I I  Lecture 8Struts  Java  I I  Lecture 8
Struts Java I I Lecture 8patinijava
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface pptTaha Malampatti
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug 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
 
MeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentMeetJS Summit 2016: React.js enlightenment
MeetJS Summit 2016: React.js enlightenmentArtur Szott
 

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

Dernier

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxOnBoard
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphNeo4j
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 

Dernier (20)

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Maximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptxMaximizing Board Effectiveness 2024 Webinar.pptx
Maximizing Board Effectiveness 2024 Webinar.pptx
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
#StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge GraphSIEMENS: RAPUNZEL – A Tale About Knowledge Graph
SIEMENS: RAPUNZEL – A Tale About Knowledge Graph
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
Neo4j - How KGs are shaping the future of Generative AI at AWS Summit London ...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 

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>