Fill Form and Echo the post by Spring Web MVC


I created Hello World App in the last article Hello World App by Spring Web MVC.
In this article, I would like to add form and show the post result.


🐮 Update index.jsp

You should add a link to webapp/WEB-INF/index.jsp like this:

<html>
<body>
<h1>Hello World!h1>
<ul>
<li><a href="">Go to echo page!a>li>
ul>
body>
html>

😼 Create EchoForm

You should create a EchoForm class to have user input to
src/main/java/example/app/EchoForm.java:

package example.app;

import org.hibernate.validator.constraints.NotEmpty;

import javax.validation.constraints.Size;
import java.io.Serializable;

public class EchoForm implements Serializable {

private static final long serialVersionUID = 1L;

@NotEmpty
@Size(max = 100)
private String text;

public String getText() {
return text;
}

public void setText(String text) {
this.text = text;
}
}

🗻 Create EchoController

You should crate a EchoController to handle input request from user
in src/main/java/example/app/EchoController.java, like this:

package example.app;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

@Controller
@RequestMapping("echo")
public class EchoController {

@RequestMapping(method = RequestMethod.GET)
public String viewInput(Model model) {
EchoForm form = new EchoForm();
model.addAttribute(form);
return "echo/input";
}

@RequestMapping(method = RequestMethod.POST)
public String echo(@Valid EchoForm form, BindingResult result) {
if(result.hasErrors()) {
return "echo/input";
}
return "echo/output";
}
}

🐯 Add echo/input.jsp

You can add new view webapp/WEB-INF/echo/input.jsp for user input:

<html>
<head>
<title>Input Pagetitle>
head>
<body>
<h2>Input Pageh2>
<form:form modelAttribute="echoForm">
<div>Please fill text :div>
<div>
<form:input path="text" />
<form:errors path="text" />
div>
<div>
<form:button>Sendform:button>
div>
form:form>
body>
html>

😎 Add echo/output.jsp

You can add new view webapp/WEB-INF/echo/input.jsp for showing user output:

<html>
<head>
<title>Output Pagetitle>
head>
<body>
<h2>Output Pageh2>
<div>
The filled text is : <span>"<c:out value="${echoForm.text}" />"span>
div>
<div><a href="">Go to Topa>div>
body>
html>

🏀 The result

Input Page

spring-mvc-input-page

Output Page

spring-mvc-output-page

Input Error Page

spring-mvc-input-error-page

🍮 Sample source

morizyun/spring_web_mvc_sample_codes: Sample Codes by Spring Web MVC

🖥 Recommended VPS Service

VULTR provides high performance cloud compute environment for you. Vultr has 15 data-centers strategically placed around the globe, you can use a VPS with 512 MB memory for just $ 2.5 / month ($ 0.004 / hour). In addition, Vultr is up to 4 times faster than the competition, so please check it => Check Benchmark Results!!