Spring MVC Form Submission

In this guide, we will create a page to submit a form and display the form data on the other page in less than 10 minute.

Technologies

  • Gradle 5.2.1
  • Spring Boot
  • Spring MVC
  • Thymeleaf

If you are having difficulty to create a spring mvc web project, you may refer this tutorial.

Java Classes

MyController.java will contain two method, one for the GET request which display the form submission page, another POST request will process the request and display in other page.

package my.cychew;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;

@Controller
public class MyController {

	@GetMapping("/hello")
	public String helloWorld(Model model) {
		model.addAttribute("person", new Person());
		return "welcome";
	}

	@PostMapping("/greeting")
	public String greeting(@ModelAttribute Person person) {
		person.setName("Person name = " + person.getName()); 
		return "result";
	}
}

helloWorld() method will use Model object to expose our Person object to the view template, which in our case will be welcome.html

POST method greeting() will retrieve the form data via @ModelAttribute annotated Object and add in some prefix wording.

Person.java will only contain one String variable, name

package my.cychew;

public class Person {
	private String name;

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

}

Our form page, welcome.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Welcome</title>
</head>
<body>
	<h1>Hello World</h1>
	<form action="#" th:action="@{/greeting}" th:object="${person}" method="post">
    	<p>Name: <input type="text" th:field="*{name}" /></p>
        <p><input type="submit" value="Submit" /> <input type="reset" value="Reset" /></p>
    </form>
</body>
</html>

th:action will use to map back the POST mapping in our controller class, and the th:object=”${person}” will map back our model attribute.

input text field will be map to Person object name variable via th:field=”*{name}”

Result display page, result.html

<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Form submit result</title>
</head>
<body>
	<h1>Result</h1>
	<p>Name: <span th:text="${person.name}" /></p>
	<a href="/hello">Submit another form</a>
</body>
</html>

To retrieve and display controller model object, we can use ${person.name}

Project structure

Finally, we start the project with gradle bootrun command.

Access the application from browser with http://localhost:8080/hello

let’s key in some test data and submit

TA DA! you just create a form submission in Spring MVC

Spring MVC Form Submission
Tagged on:             

Leave a Reply

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