Spring @RequestAttribute annotation – Spring MVC

Spring 4.3 provides a new @RequestAttribute annotation that helps us access to pre-existing global request attributes (outside the controller). Today we’re gonna look at how to get a HttpServletRequest attribute which is created in an Interceptor using Spring @RequestAttribute annotation.

Related Articles:
How to use SpringMVC HandlerInterceptor with Spring Boot
Spring @SessionAttribute annotation – Spring MVC


Instead of using HttpServletRequest object, we can bind attribute from a javax.servlet.http.HttpServletRequest to a handler method parameter by using @RequestAttribute annotation on that parameter:

In the example, to have a pre-existing request attribute which are managed globally, we create an Interceptor and focus on preHandle() method:

For more details, please take a look at this article: How to use SpringMVC HandlerInterceptor with Spring Boot

So, we’re gonna look at the next part of this tutorial to know how to get Counter attribute from HttpServletRequest with attribute created in preHandle() method.


– Java 1.8
– Maven 3.3.9
– Spring Tool Suite – Version 3.8.1.RELEASE
– Spring Boot: 1.5.1.RELEASE

Project Structure:

Now follow step by step:

1. Create Spring Boot project and add Dependency

– Open Spring Tool Suite, on Menu, choose File -> New -> Spring Starter Project, then fill each fields.
– Click Next, then Finish. Spring Boot project will be created successfully.
– Add dependency to pom.xml:

2. Create Data Model class

Under package model, create Counter class, this class will be used for request attribute:

3. Create and add Interceptor class

Under package config, create CounterInterceptor class that implements HandlerInterceptor. For simplifying the example, we only focus on writing code for preHandle() method:

We set Attribute Counter for HttpServletRequest with value START_COUNT. This value will be kept when Counter attribute is bound to handle() method of Web Controller.

Next, create a @Configuration component to add the Interceptor above:

4. Create a WebController

Under package controller, create WebController class:

Everytime we send a request, @RequestAttribute named “counter” will be bound.

5. Run Spring Boot Application & Enjoy Result

– Config maven build:
clean install
– Run project with mode Spring Boot App
– Check results:

Send request: http://localhost:8080/
System shows:

Web Browser:

It means we got request attribute counter with value 9 successfully and increased it.



Related Posts

Got Something To Say:

Your email address will not be published. Required fields are marked *