Home  >  Spring MVC

Spring MVC RedirectView Example

By Arvind Rai, June 28, 2019
Here will walk through the Spring MVC RedirectView example to add/fetch flash attributes using RedirectAttributes, Model and RequestContextUtils. Flash Attributes are attributes which lives in session for short time. It is used to propagate values from one request to another request and then automatically removed. Handling flash attributes are achieved using FlashMap and FlashMapManager. But in annotated spring MVC controller, it can be achieved with RedirectAttributes. Flash attributes are added using addFlashAttribute("key", "value") method of the RedirectAttributes in controller method annotated with @RequestMapping. In flash attributes, there are the concurrency issues. So to reduce it, we should use flash attributes with RedirectView. To fetch flash attributes we can use Model and RequestContextUtils. Model contains the flash attributes of just previous request.

How to Use Spring MVC RedirectView

org.springframework.web.servlet.view.RedirectView redirects URL that can be absolute or relative to context. It can also be used as URI template and the values of template will automatically be replaced by the same key in the Model or attributes in RedirectAttributes. In RedirectView , there is a method setContextRelative(). By default its value is false, it means the relative URL will start from web server root. When we set it to true, then the relative URL will start from application context. To use RedirectView, we need to write the code as below.
RedirectView redirectView = new RedirectView();
redirectView.setContextRelative(true);
redirectView.setUrl("/hello");
return redirectView; 
In spring MVC application, we can redirect our URL, even without using RedirectView. Just use redirect keyword as below.
return "redirect:/success.jsp";
 

Add Flash Attributes using RedirectAttributes.addFlashAttribute()

To add flash attributes with RedirectAttributes , create RedirectAttributes as an argument in @RequestMapping method inside spring MVC controller. In RedirectAttributes there is a method addFlashAttribute, using which we add key value pair.
redirectAttrs.addFlashAttribute("key", "value"); 
In this way, more than one flash attributes can be added and it will be propagated till the next request.

Fetch Flash Attributes using Model and RequestContextUtils

To fetch flash attributes we have two approaches. The first one is by using Model as an argument in the @RequestMapping method and fetch the flash attribute as below.
model.asMap().get("key");
 
Another approach is by using RequestContextUtils . The static method getInputFlashMap() accepts HttpServletRequest as an argument and it returns a Map. Now using keys we can fetch flash attributes.
Map>String, ?< flashMap = RequestContextUtils.getInputFlashMap(request);
flashMap.get("key"); 

Example

To understand the flash attribute with RedirectView, we are providing complete example. We are creating two controllers. The first controller will have a method that will run on HTTP form post. The values of HTTP form, will be fetched and added to RedirectAttributes, and this method will return RedirectView to go to the next controller method
ControllerOne.java
@Controller
public class ControllerOne {
	@RequestMapping(value="mybook", method = RequestMethod.GET)
	public ModelAndView book(){
		return new ModelAndView("book","book",new Book());
	}
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	public RedirectView  save(@ModelAttribute("book") Book book, RedirectAttributes redirectAttrs) {
		redirectAttrs.addAttribute("msg", "Hello World!");
		redirectAttrs.addFlashAttribute("book", book.getBookName());
		redirectAttrs.addFlashAttribute("writer", book.getWriter());
		
		RedirectView redirectView = new RedirectView();
		redirectView.setContextRelative(true);
		redirectView.setUrl("/hello/{msg}");
	        return redirectView;
	}
} 
Here we have used URI template for RedirectView. The value of msg will be taken by attributes from Model . Now in the next controller method, we will fetch flash attribute using Model and RequestContextUtils.
ControllerTwo.java
@Controller
public class ControllerTwo {
	@RequestMapping(value="/hello/{msg}", method = RequestMethod.GET)
	public String hello(Model model, RedirectAttributes redirectAttrs,@PathVariable("msg") String msg,
			                                   HttpServletRequest request){
		System.out.println("Message:"+msg);
		
		System.out.println("Fetch Flash Attributes By using Model");
		System.out.println("Book Name:"+model.asMap().get("book"));
		System.out.println("Writer:"+model.asMap().get("writer"));
		
		System.out.println("Fetch Flash Attributes By using RequestContextUtils");
		Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
		if (flashMap != null) {
		    System.out.println("Book Name:"+flashMap.get("book"));
		    System.out.println("Writer: "+flashMap.get("writer"));
		}
		return "redirect:/success.jsp";
	}
} 
Now find the application configuration class. Here we are using InternalResourceViewResolver that will be used to run input form page.
AppConfig.java
@Configuration 
@ComponentScan("com.concretepage") 
@EnableWebMvc
public class AppConfig {  
    @Bean  
    public InternalResourceViewResolver viewResolver() {  
	InternalResourceViewResolver resolver = new InternalResourceViewResolver();  
        resolver.setPrefix("/WEB-INF/views/");  
        resolver.setSuffix(".jsp");
        resolver.setViewClass(JstlView.class);  
        return resolver;  
    }
} 
It is required to use @EnableWebMvc to run RedirectView. Now find the JSP to create form.
book.jsp
  <form:form action="save" method="post" commandName="book">
	<tr>  <td>Book Name:</td> <td><form:input  path="bookName"/> </td> </tr> 
	<tr> <td> Writer :</td> <td><form:input path="writer"/> </td> </tr> 
	<tr> <td colspan=2>   <input type="submit" value="Save"> </td>
  </form:form> 

Output

To test the output, run the URL http://localhost:8080/concretepage-1/mybook . We will get a form.
Spring MVC RedirectView Example to  Add/Fetch Flash Attributes using  RedirectAttributes,  Model  and RequestContextUtils
The output in console will be
Message:Hello World!
Fetch Flash Attributes By using Model
Book Name:Panchtantra
Writer:Premchand
Fetch Flash Attributes By using RequestContextUtils
Book Name:Panchtantra
Writer: Premchand 

Download Complete Source Code

POSTED BY
ARVIND RAI
ARVIND RAI
FIND MORE TUTORILAS






©2019 concretepage.com | Privacy Policy | Contact Us