Spring MVC – Redirecting model attributes from one controller to other controller

In the real world applications, we are required to redirect the request from one controller to other controller.

In other words we are required to redirect the request without user interaction again.

Example : Registration controller accepts the registration request and saves the user data.
Then it has to redirect to home page after successful registration.

So here , we will have one controller for registration and another controller for getting the home page.

After registration , we are required to redirect the request to home page controller with user details.

So how do we pass the user information to other controller ?

Spring MVC 3.1 has come up with the solution called Flash Attributes.
We will see how request can be redirected and how flash attributes can be added.

Spring MVC redirect can be achived in 2 ways
1)org.springframework.web.servlet.view.RedirectView : This class redirects the URL(absolute or Relative)
It has a method called setContextRelative(boolean b)
By default . it is false and which means it takes absolute url.

If we set it to true,it takes relative url(starts from the application context)

So below code is representing the RedirectView example

  1. RedirectView redirectView = new RedirectView();
  2. redirectView.setContextRelative(true);
  3. redirectView.setUrl("/home");
  4. return redirectView;
RedirectView redirectView = new RedirectView();
redirectView.setContextRelative(true);
redirectView.setUrl("/home");
return redirectView;

2)We can use redirect keyword rather than using RedirectView class as below

  1. return  “redirect:/home”
return  “redirect:/home”

Now , when we do Redirect, How are we adding Flash attributes to pass to other redirected controller ?

RedirectAttributes should be added as a parameter in the @RequestMapping method in the controller
Then we can use addFlashAttribute(“key”,”value”);

addFlashAttribute add the given parameter to the output flash map and pass it to the subsequent request.

How can we access the Flash Attribute in the redirected controller ?

3 ways to access Flash attributes

1)Using Model attribute argument in the @RequestMapping method and access the value as below
Model.asMap().get(“key”);

2)Using RequestContextUtils, the static method getInputFlashMap() accepts HttpServeltRequest as an argument and it returns a Map.

We can access the flash attribute by passing key to the map.

  1. Map<String, ?> flashInputMap = RequestContextUtils.getInputFlashMap(request);
  2. flashInputMap.get("key");
Map<String, ?> flashInputMap = RequestContextUtils.getInputFlashMap(request);
flashInputMap.get("key");

3)Access directly using model parameter from the @RequestMapping method in the jsp page.

Problem with Flash Attributes is, they are accessible only in the first redirection.

Once redirection is done, the flash attributes are getting removed.

So after redirection, if user Refreshes the page these flash attributes will not be available .
So it is better if we do null check for the flashMap and take to the appropriate view.

Ex:

  1. If(flashInputMap !=null)
  2. return “home”;
  3. else
  4. return “someOtherView”;
If(flashInputMap !=null)
return “home”;
else
return “someOtherView”;

Lets see the real world example for the same

Project structure

Create the model class as below

  1. package com.kb.model;
  2.  
  3. public class Customer {
  4.    
  5.    
  6.     private String emailId;
  7.    
  8.     private String password;
  9.    
  10.    
  11.     private String confPassword;
  12.    
  13.     private int age;
  14.  
  15.     public String getEmailId() {
  16.         return emailId;
  17.     }
  18.  
  19.     public void setEmailId(String emailId) {
  20.         this.emailId = emailId;
  21.     }
  22.  
  23.     public String getPassword() {
  24.         return password;
  25.     }
  26.  
  27.     public void setPassword(String password) {
  28.         this.password = password;
  29.     }
  30.  
  31.     public String getConfPassword() {
  32.         return confPassword;
  33.     }
  34.  
  35.     public void setConfPassword(String confPassword) {
  36.         this.confPassword = confPassword;
  37.     }
  38.  
  39.     public int getAge() {
  40.         return age;
  41.     }
  42.  
  43.     public void setAge(int age) {
  44.         this.age = age;
  45.     }
  46.  
  47. }
package com.kb.model;

public class Customer {
	
	
	private String emailId;
	
	private String password;
	
	
	private String confPassword;
	
	private int age;

	public String getEmailId() {
		return emailId;
	}

	public void setEmailId(String emailId) {
		this.emailId = emailId;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getConfPassword() {
		return confPassword;
	}

	public void setConfPassword(String confPassword) {
		this.confPassword = confPassword;
	}

	public int getAge() {
		return age;
	}

	public void setAge(int age) {
		this.age = age;
	}

}

Create the Registration controller

  1. package com.kb.controller;
  2.  
  3. import javax.validation.Valid;
  4.  
  5. import org.springframework.stereotype.Controller;
  6. import org.springframework.ui.Model;
  7. import org.springframework.validation.BindingResult;
  8. import org.springframework.web.bind.annotation.RequestMapping;
  9. import org.springframework.web.bind.annotation.RequestMethod;
  10. import org.springframework.web.servlet.mvc.support.RedirectAttributes;
  11.  
  12. import com.kb.model.Customer;
  13.  
  14. @Controller
  15. public class RegistrationController {
  16.    
  17.      @RequestMapping(value = "/register", method = RequestMethod.GET)
  18.         public String viewRegistrationPage(Model model) {
  19.           Customer customer = new Customer();
  20.             model.addAttribute("customer", customer);
  21.             return "register";
  22.         }
  23.    
  24.      @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
  25.         public String doLogin(@Valid Customer customer, BindingResult result,Model model,RedirectAttributes redirectAttributes) {
  26.          model.addAttribute("customer",customer);
  27.           //Do the Registration logic and then redirect to home page without using action for home page
  28.          
  29.          redirectAttributes.addFlashAttribute("customerEmail", customer.getEmailId());
  30.           return "redirect:/home";
  31.         }
  32.  
  33. }
package com.kb.controller;

import javax.validation.Valid;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.kb.model.Customer;

@Controller
public class RegistrationController {
	
	 @RequestMapping(value = "/register", method = RequestMethod.GET)
	    public String viewRegistrationPage(Model model) {
	      Customer customer = new Customer();
	        model.addAttribute("customer", customer);
	        return "register";
	    }
	
	 @RequestMapping(value = "/doRegister", method = RequestMethod.POST)
	    public String doLogin(@Valid Customer customer, BindingResult result,Model model,RedirectAttributes redirectAttributes) {
		 model.addAttribute("customer",customer);
	      //Do the Registration logic and then redirect to home page without using action for home page
		 
		 redirectAttributes.addFlashAttribute("customerEmail", customer.getEmailId());
	      return "redirect:/home";
	    }

}

Create the Home controller

  1. package com.kb.controller;
  2.  
  3. import java.util.Map;
  4.  
  5. import javax.servlet.http.HttpServletRequest;
  6.  
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.ui.Model;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.servlet.support.RequestContextUtils;
  12.  
  13. @Controller
  14. public class HomeController {
  15.    
  16.      @RequestMapping(value = "/home", method = RequestMethod.GET)
  17.         public String doLogin(HttpServletRequest request,Model model) {
  18.          String emailId1 = (String)model.asMap().get("customerEmail");
  19.           System.out.println(emailId1);
  20.           Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
  21.           String emailId2 =  (String) flashMap.get("customerEmail");
  22.           System.out.println(emailId2);
  23.           return "home";
  24.         }
  25.  
  26. }
package com.kb.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContextUtils;

@Controller
public class HomeController {
	
	 @RequestMapping(value = "/home", method = RequestMethod.GET)
	    public String doLogin(HttpServletRequest request,Model model) {
		 String emailId1 = (String)model.asMap().get("customerEmail");
	      System.out.println(emailId1);
	      Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
	      String emailId2 =  (String) flashMap.get("customerEmail"); 
	      System.out.println(emailId2);
	      return "home";
	    }

}

In the above controller, I have shown the different way of accessing flash attribute

Create the registration page

  1. <%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
  2. <html>
  3. <head>
  4. <title>Spring MVC form Validation</title>
  5. </head>
  6.  
  7. <body>
  8.     <h2>Enter below details to Register</h2>
  9.  
  10.     <form:form method="POST" modelAttribute="customer" action="doRegister">
  11.         <table>
  12.            
  13.             <tr>
  14.                 <td>Enter your E-mail:</td>
  15.                 <td><form:input path="emailId" /></td>
  16.                 <td><form:errors path="emailId" cssStyle="color: #ff0000;" /></td>
  17.             </tr>
  18.            
  19.             <tr>
  20.                 <td>Enter your Age:</td>
  21.                 <td><form:input path="age"/></td>
  22.                 <td><form:errors path="age" cssStyle="color: #ff0000;"/></td>
  23.             </tr>
  24.            
  25.             <tr>
  26.                 <td>Enter your password:</td>
  27.                 <td><form:password path="password"  showPassword="true"/></td>
  28.                 <td><form:errors path="password" cssStyle="color: #ff0000;"/></td>
  29.             </tr>
  30.            
  31.                 <tr>
  32.                 <td>Confirm your password:</td>
  33.                 <td><form:password path="confPassword"  showPassword="true"/></td>
  34.                 <td><form:errors path="confPassword" cssStyle="color: #ff0000;"/></td>
  35.             </tr>
  36.            
  37.             <tr>
  38.                 <td><input type="submit" name="submit" value="Click here to Register"></td>
  39.             </tr>
  40.         </table>
  41.     </form:form>
  42.  
  43. </body>
  44. </html>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<html>
<head>
<title>Spring MVC form Validation</title>
</head>

<body>
	<h2>Enter below details to Register</h2>

	<form:form method="POST" modelAttribute="customer" action="doRegister">
		<table>
			
			<tr>
				<td>Enter your E-mail:</td>
				<td><form:input path="emailId" /></td>
				<td><form:errors path="emailId" cssStyle="color: #ff0000;" /></td>
			</tr>
			
			<tr>
				<td>Enter your Age:</td>
				<td><form:input path="age"/></td>
				<td><form:errors path="age" cssStyle="color: #ff0000;"/></td>
			</tr>
			
			<tr>
				<td>Enter your password:</td>
				<td><form:password path="password"  showPassword="true"/></td>
				<td><form:errors path="password" cssStyle="color: #ff0000;"/></td>
			</tr>
			
				<tr>
				<td>Confirm your password:</td>
				<td><form:password path="confPassword"  showPassword="true"/></td>
				<td><form:errors path="confPassword" cssStyle="color: #ff0000;"/></td>
			</tr>
			
			<tr>
				<td><input type="submit" name="submit" value="Click here to Register"></td>
			</tr>
		</table>
	</form:form>

</body>
</html>

Create the home page

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
  4. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  5. <html>
  6. <head>
  7. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  8. <title>Registration Success</title>
  9. </head>
  10. <body>
  11.  <div align="center">
  12.         <h2>Welcome ${customerEmail}! Here is your Home Page.</h2>
  13.   </div>
  14. </body>
  15. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Success</title>
</head>
<body>
 <div align="center">
        <h2>Welcome ${customerEmail}! Here is your Home Page.</h2>
  </div>
</body>
</html>

Create the spring mvc configuration file

  1. <?xml version="1.0" encoding="UTF-8"?>
  2. <beans xmlns="http://www.springframework.org/schema/beans"
  3.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:p="http://www.springframework.org/schema/p"
  4.     xmlns:context="http://www.springframework.org/schema/context"
  5.     xmlns:mvc="http://www.springframework.org/schema/mvc"
  6.     xsi:schemaLocation="http://www.springframework.org/schema/beans
  7.        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
  8.        http://www.springframework.org/schema/context
  9.        http://www.springframework.org/schema/context/spring-context-3.2.xsd
  10.        http://www.springframework.org/schema/mvc
  11.        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">
  12.  
  13.     <context:component-scan base-package="com.kb.*" />
  14.     <mvc:annotation-driven />
  15.  
  16.     <bean id="viewResolver"
  17.         class="org.springframework.web.servlet.view.InternalResourceViewResolver">
  18.         <property name="prefix" value="/WEB-INF/pages/" />
  19.         <property name="suffix" value=".jsp" />
  20.     </bean>
  21.  
  22. </beans>
<?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"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc"
	xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd">

	<context:component-scan base-package="com.kb.*" />
	<mvc:annotation-driven />

	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="prefix" value="/WEB-INF/pages/" />
		<property name="suffix" value=".jsp" />
	</bean>

</beans>

Create the web.xml

  1. <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.     xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
  3.     version="3.1">
  4.  
  5.     <display-name>Spring MVC Flash Attribute</display-name>
  6.  
  7.     <!-- Spring MVC dispatcher servlet -->
  8.     <servlet>
  9.         <servlet-name>mvc-dispatcher</servlet-name>
  10.         <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  11.         <init-param>
  12.             <param-name>contextConfigLocation</param-name>
  13.             <param-value>
  14.             /WEB-INF/spring-mvc.xml,
  15.         </param-value>
  16.         </init-param>
  17.         <load-on-startup>1</load-on-startup>
  18.     </servlet>
  19.     <servlet-mapping>
  20.         <servlet-name>mvc-dispatcher</servlet-name>
  21.         <url-pattern>/</url-pattern>
  22.     </servlet-mapping>
  23.  
  24.     <listener>
  25.         <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  26.     </listener>
  27.  
  28. </web-app>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
	version="3.1">

	<display-name>Spring MVC Flash Attribute</display-name>

	<!-- Spring MVC dispatcher servlet -->
	<servlet>
		<servlet-name>mvc-dispatcher</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<param-value>
			/WEB-INF/spring-mvc.xml,
		</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<servlet-mapping>
		<servlet-name>mvc-dispatcher</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>

	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>

</web-app>

Create the pom.xml

  1. <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  2.   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  3.   <modelVersion>4.0.0</modelVersion>
  4.   <groupId>Spring</groupId>
  5.   <artifactId>SpringMVCFlashAttributes</artifactId>
  6.   <packaging>war</packaging>
  7.   <version>0.0.1-SNAPSHOT</version>
  8.   <name>SpringMVCFlashAttributes Maven Webapp</name>
  9.   <url>http://maven.apache.org</url>
  10.    <properties>
  11.         <org.springframework.version>4.2.0.RELEASE</org.springframework.version>
  12.     </properties>
  13.   <dependencies>
  14.     <dependency>
  15.       <groupId>junit</groupId>
  16.       <artifactId>junit</artifactId>
  17.       <version>3.8.1</version>
  18.       <scope>test</scope>
  19.     </dependency>
  20.     <dependency>
  21.             <groupId>org.springframework</groupId>
  22.             <artifactId>spring-web</artifactId>
  23.             <version>${org.springframework.version}</version>
  24.         </dependency>
  25.  
  26.         <dependency>
  27.             <groupId>org.springframework</groupId>
  28.             <artifactId>spring-webmvc</artifactId>
  29.             <version>${org.springframework.version}</version>
  30.         </dependency>
  31.         <dependency>
  32.             <groupId>javax.servlet</groupId>
  33.             <artifactId>servlet-api</artifactId>
  34.             <version>2.5</version>
  35.             <scope>provided</scope>
  36.         </dependency>
  37.         <dependency>
  38.     <groupId>javax.servlet.jsp.jstl</groupId>
  39.     <artifactId>javax.servlet.jsp.jstl-api</artifactId>
  40.     <version>1.2.1</version>
  41. </dependency>
  42. <dependency>
  43.     <groupId>taglibs</groupId>
  44.     <artifactId>standard</artifactId>
  45.     <version>1.1.2</version>
  46. </dependency>
  47. <dependency>
  48.     <groupId>javax.validation</groupId>
  49.     <artifactId>validation-api</artifactId>
  50.     <version>1.1.0.Final</version>
  51. </dependency>
  52. <dependency>
  53.     <groupId>org.hibernate</groupId>
  54.     <artifactId>hibernate-validator</artifactId>
  55.     <version>5.0.1.Final</version>
  56.  </dependency>
  57.   </dependencies>
  58.   <build>
  59.     <finalName>SpringMVCFlashAttributes</finalName>
  60.     <plugins>
  61.             <plugin>
  62.                 <groupId>org.apache.maven.plugins</groupId>
  63.                 <artifactId>maven-compiler-plugin</artifactId>
  64.                 <version>2.5.1</version>
  65.                 <configuration>
  66.                     <source>1.8</source>
  67.                     <target>1.8</target>
  68.                 </configuration>
  69.             </plugin>
  70.         </plugins>
  71.   </build>
  72. </project>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Spring</groupId>
  <artifactId>SpringMVCFlashAttributes</artifactId>
  <packaging>war</packaging>
  <version>0.0.1-SNAPSHOT</version>
  <name>SpringMVCFlashAttributes Maven Webapp</name>
  <url>http://maven.apache.org</url>
   <properties>
		<org.springframework.version>4.2.0.RELEASE</org.springframework.version>
	</properties>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>
    <dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${org.springframework.version}</version>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
	<groupId>javax.servlet.jsp.jstl</groupId>
	<artifactId>javax.servlet.jsp.jstl-api</artifactId>
	<version>1.2.1</version>
</dependency>
<dependency>
	<groupId>taglibs</groupId>
	<artifactId>standard</artifactId>
	<version>1.1.2</version>
</dependency>
<dependency>
    <groupId>javax.validation</groupId>
    <artifactId>validation-api</artifactId>
    <version>1.1.0.Final</version>
</dependency>
<dependency>
    <groupId>org.hibernate</groupId>
    <artifactId>hibernate-validator</artifactId>
    <version>5.0.1.Final</version>
 </dependency>
  </dependencies>
  <build>
    <finalName>SpringMVCFlashAttributes</finalName>
    <plugins>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>2.5.1</version>
				<configuration>
					<source>1.8</source>
					<target>1.8</target>
				</configuration>
			</plugin>
		</plugins>
  </build>
</project>

Build and deploy the project and access the below url

http://localhost:8080/SpringMVCFlashAttributes/register

Enter below details

Click on Register

Observe that flash attribute is accessed inside the jsp using model attribute.

One problem with Flash attribute is the Refresh(F5)

Now Refresh the above page and see the output, email id is not displayed as its null now

So To avoid this situation, its better to add null check on the flash attribute and handle it as below

I am going to display one more jsp if flash map is null by modifying the Home controller as below

  1. package com.kb.controller;
  2.  
  3. import java.util.Map;
  4.  
  5. import javax.servlet.http.HttpServletRequest;
  6.  
  7. import org.springframework.stereotype.Controller;
  8. import org.springframework.ui.Model;
  9. import org.springframework.web.bind.annotation.RequestMapping;
  10. import org.springframework.web.bind.annotation.RequestMethod;
  11. import org.springframework.web.servlet.support.RequestContextUtils;
  12.  
  13. @Controller
  14. public class HomeController {
  15.    
  16.      @RequestMapping(value = "/home", method = RequestMethod.GET)
  17.         public String doLogin(HttpServletRequest request,Model model) {
  18.          Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
  19.          if(flashMap != null){
  20.              String emailId =  (String) flashMap.get("customerEmail");
  21.              System.out.println(emailId);
  22.              return "home";
  23.          }
  24.          else{
  25.              return "refreshNotAllowed";
  26.          }
  27.          
  28.         }
  29.  
  30. }
package com.kb.controller;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.support.RequestContextUtils;

@Controller
public class HomeController {
	
	 @RequestMapping(value = "/home", method = RequestMethod.GET)
	    public String doLogin(HttpServletRequest request,Model model) {
		 Map<String, ?> flashMap = RequestContextUtils.getInputFlashMap(request);
		 if(flashMap != null){
			 String emailId =  (String) flashMap.get("customerEmail");
			 System.out.println(emailId);
			 return "home";
		 }
		 else{
			 return "refreshNotAllowed";
		 }
	      
	    }

}

Create the refreshNotAllowed jsp as below

  1. <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
  2.     pageEncoding="ISO-8859-1"%>
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
  4. <html>
  5. <head>
  6. <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
  7. <title>Insert title here</title>
  8. </head>
  9. <body>
  10. <h2>Sorry ,Refresh on this page is not allowed</h2>
  11. </body>
  12. </html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h2>Sorry ,Refresh on this page is not allowed</h2>
</body>
</html>

Build the project and deploy it and run it by accessing below url

http://localhost:8080/SpringMVCFlashAttributes/register

Click on Register by entering the details

Now Refresh the above page

So this is one way we can handle refresh on flash attribute.

Download this project SpringMVCFlashAttributes

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on