DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Trending

  • How to Format Articles for DZone
  • My LLM Journey as a Software Engineer Exploring a New Domain
  • Microsoft Azure Synapse Analytics: Scaling Hurdles and Limitations
  • AI, ML, and Data Science: Shaping the Future of Automation
  1. DZone
  2. Coding
  3. Frameworks
  4. Using Spring Interceptors in your MVC Webapp

Using Spring Interceptors in your MVC Webapp

I thought that it was time to take a look at Spring’s MVC interceptor mechanism, which has been around for a good number of years and is a really useful tool.

By 
Roger Hughes user avatar
Roger Hughes
·
Sep. 29, 11 · Tutorial
Likes (0)
Comment
Save
Tweet
Share
70.8K Views

Join the DZone community and get the full member experience.

Join For Free

I thought that it was time to take a look at Spring’s MVC interceptor mechanism, which has been around for a good number of years and is a really useful tool.

A Spring Interceptor does what it says on the tin: intercepts an incoming HTTP request before it reaches your Spring MVC controller class, or conversely, intercepts the outgoing HTTP response after it leaves your controller, but before it’s fed back to the browser.

You may ask what use is this to you? The answer is that it allows you to perform tasks that are common to every request or set of requests without the need to cut ‘n’ paste boiler plate code into every controller class. For example, you could perform user authentication of a request before it reaches your controller and, if successful, retrieve some additional user details from a database adding them to the HttpServletRequest object before your controller is called. Your controller can then simply retrieve and use these values or leave them for display by the JSP. On the other hand, if the authentication fails, you could re-direct your user to a different page.

The demonstration code shows you how to modify the incoming HttpServletRequest object before it reaches your controller. This does nothing more than add a simple string to the request, but, as I said above, you could always make a database call to grab hold of some data that’s required by every request... you could even add some kind of optimization and do some caching at this point.

public class RequestInitializeInterceptor extends HandlerInterceptorAdapter {

  // Obtain a suitable logger.
  private static Log logger = LogFactory
      .getLog(RequestInitializeInterceptor.class);

  /**
   * In this case intercept the request BEFORE it reaches the controller
   */
  @Override
  public boolean preHandle(HttpServletRequest request,
      HttpServletResponse response, Object handler) throws Exception {
    try {

      logger.info("Intercepting: " + request.getRequestURI());

      // Do some changes to the incoming request object
      updateRequest(request);

      return true;
    } catch (SystemException e) {
      logger.info("request update failed");
      return false;
    }
  }

  /**
   * The data added to the request would most likely come from a database
   */
  private void updateRequest(HttpServletRequest request) {

    logger.info("Updating request object");
    request.setAttribute("commonData",
        "This string is required in every request");
  }

  /** This could be any exception */
  private class SystemException extends RuntimeException {

    private static final long serialVersionUID = 1L;
    // Blank
  }
}


In the code above, I’ve chosen the simplest implementation method by extending the HandlerInterceptorAdaptor class, overriding preHandle(..) method. My preHandle(...) method does the error handling, deciding what to do if an error occurs and returning false if one does. In returning false the interceptor chain is broken and your controller class is not called. The actual business of messing with the request object is delegated to updateRequest(request).


The HandlerInterceptorAdaptor class has three methods, each of which are stubbed and, if desired, can be ignored. The methods are: prehandle(...), postHandle(...) and afterCompletion(...) and more information on these can be found in the Spring API documentation. Be aware that this can be somewhat confusing as the Handler Interceptor classes documentation still refer to MVC controller classes by their Spring 2 name of handlers. This point is easily demonstrated if you look at prehandle(...)’s third parameter of type Object and called handler. If you examine this in your debugger, you’ll see that it is an instance of your controller class. If you’re new to this technique, just remember that controller == handler.


The next step in implementing an interceptor is, as always, to add something to the Spring XML config file:


<!-- Configures Handler Interceptors --> 
<mvc:interceptors>  
 <!-- This bit of XML will intercept all URLs - which is what you want in a web app -->
 <bean class="marin.interceptor.RequestInitializeInterceptor" />

 <!-- This bit of XML will apply certain URLs to certain interceptors -->
 <!-- 
 <mvc:interceptor>
  <mvc:mapping path="/gb/shop/**"/>
  <bean class="marin.interceptor.RequestInitializeInterceptor" />
 </mvc:interceptor>
  -->
</mvc:interceptors>


The XML above demonstrates an either/or choice of adding an interceptor to all request URLs, or if you look at the commented out section, adding an interceptor to specific request URLs, allowing you to choose which URLs are connected to your interceptor class.


The eagle eyed readers may have noticed that the interceptor classes use inheritance and XML config as its method of implementation. In these days of convention over configuration, this pattern is beginning to look a little jaded and could probably do with a good overhaul. One suggestion would be to enhance the whole lot to use annotations, applying the same techniques that have already been added to the controller mechanism. This would add extra flexibility without the complication of using all the interfaces and abstract base classes. As a suggestion, a future interceptor class implementation could look something like this:


  @Intercept(value = "/gb/en/*", method = RequestMethod.POST)
  public boolean myAuthenticationHandler(HttpServletRequest request,
      Model model) {
    // Put some code here
  }


That concludes this look at Spring interceptors, it should be remembered that I’ve only demonstrated the most basic implementation - I may add extra examples another day...

 

From http://www.captaindebug.com/2011/09/using-spring-interceptors-in-your-mvc.html

Spring Framework

Opinions expressed by DZone contributors are their own.

Related

  • How Spring and Hibernate Simplify Web and Database Management
  • Functional Endpoints: Alternative to Controllers in WebFlux
  • Graceful Shutdown: Spring Framework vs Golang Web Services
  • Actuator Enhancements: Spring Framework 6.2 and Spring Boot 3.4

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!