How to Redirect in Spring MVC

We often need to redirect our request to another controller. Its very easy to do in Spring MVC. In below code sample, I have created a controller method i.e. list which is mapper to context/users/ URL. It just displays the list of users.

There is another method i.e. save, it process the POST request and used to save data to database. I have not actually saved the data into DB because that is not our object in this post. We want to see, when save controller is called, and we have done with saving data into DB, how we can redirect our request to /users/ controller from /save/ controller method. Its very simple, below I share the code sample I have created to demonstrate the Spring MVC redirect:



package com.springpoc.controllers;

import com.springpoc.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping(value = "/users")

public class UsersController {

@RequestMapping(method = RequestMethod.GET)
public String list(Model model) {
System.out.println("Users controller called with GET method");

List users = new ArrayList();
users.add(new User(1, "Alice"));
users.add(new User(2, "Bob"));
users.add(new User(3, "Oracle"));

model.addAttribute("users", users);
return "users/Index"; // ViewResolver will serve /WEB-INF/views/users/Index.jsp
}

@RequestMapping(method = RequestMethod.POST)
public String save(@ModelAttribute User user) {
System.out.println("save called with id= " + user.getId() +
", name= " + user.getName());

// Save user object into DB here.
// and redirect to users controller i.e. list method

return "redirect:users";
}
}

The contents of Index.jsp page which is located at WEB-INF/views/users/Index.jsp location, are following. You see, in this method we have just listed the users we inserted into a collection inside our /users/ controller.

<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://www.springframework.org/tags" prefix="spring" %>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>

<html>
<head>
<title>Spring MVC Tutorials</title>
</head>
<body>
this page is located at : /users/index.jsp
<br/>

<h2>Current list of users is as follows:</h2>

<c:forEach items="${users}" var="u">
<c:out value="${u.id}"/> :
<c:out value="${u.name}"/> <br/>
</c:forEach>

</body>
</html>

Comments