This example shows how to apply Post-Redirect-Get pattern in Spring MVC. We will redirect the same URL from POST request to GET. We are going to use Spring Boot with Thymeleaf view.
Controller
package com.logicbig.example;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import java.util.ArrayList;
import java.util.List;
@Controller
public class VisitorController {
private List<String> visitors = new ArrayList<>();
@PostMapping("/visitor")
public String handlePostRequest(String visitorName) {
visitors.add(visitorName);
return "redirect:/visitor";
}
@GetMapping("/visitor")
public String handleGetRequest(Model model) {
model.addAttribute("visitors", visitors);
return "visitor-view";
}
}
Thymeleaf View
src/main/resources/templates/visitor-view.html<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:th="http://www.thymeleaf.org">
<body>
<h2>Visitors</h2>
<h3>Enter your name:</h3>
<form action="/visitor" method="post">
Visitor Name: <input name="visitorName"/> <br/>
<input type="submit" value="Submit">
</form>
<br>
<h3>Visitors</h3>
<p th:each="visitor : ${visitors}">
<span th:text="${visitor}"></span>
</p>
</body>
</html>
Spring Boot main class
@SpringBootApplication
public class SpringBootApplicationMain {
public static void main(String[] args) {
SpringApplication.run(SpringBootApplicationMain.class, args);
}
}
Running example
To try examples, run spring-boot maven plugin (configured in pom.xml of example project below):
mvn spring-boot:run Or run the main method class from IDE.
Output
submitting visitor name and refreshing does not double submit the form.
Example ProjectDependencies and Technologies Used: - Spring Boot 2.0.2.RELEASE
Corresponding Spring Version 5.0.6.RELEASE - spring-boot-starter-thymeleaf : Starter for building MVC web applications using Thymeleaf views.
Uses org.thymeleaf:thymeleaf-spring5 version 3.0.9.RELEASE - spring-boot-starter-web : Starter for building web, including RESTful, applications using Spring
MVC. Uses Tomcat as the default embedded container.
- JDK 1.8
- Maven 3.3.9
|