Шаги для правильной пружины mvc пример формы на основе проверки:
Создать HomeDTO
класс.
import javax.validation.constraints.NotNull;
class HomeDTO {
// on jsp page, you can't keep this field on the form empty.
@NotNull(message = "is required")
private String userName;
public HomeDTO() {
super();
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
}
Создать formpage.jsp
, чтобы показать страницу формы.
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
<h1>Result model</h1>
<form:form action="resultmodel" modelAttribute="homeDTO">
Text Input(*) : <form:input path="userName" /> <!-- Give the name of the field present in the HomeDTO --> <!-- Bu default, the type is text -->
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
Создание контроллера. Я называю это DemoController
классом.
@Controller
@RequestMapping("/home")
public class DemoController {
// first open this page at : http://localhost:8080/home/show
@RequestMapping("/show", method = RequestMethod.GET)
public String showForm(Model theModel) {
theModel.addAttribute("homeDto", new HomeDTO()); // creating the object and put in the model so that when you enter anything from formpage.jsp, this object will get populated.
return "formpage";
}
// After clicking on the submit button on the formpage.jsp, it will validate the data and send the data to the redirecting page using BindingResult.
@RequestMapping("/resultModel", method = {RequestMethod.GET, RequestMethod.POST})
public String processForm(@Valid @ModelAttribute("homeDTO") HomeDTO homeDTO, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "formpage";
}
return "showpage";
}
}
Создайте showpage.jsp
, чтобы показать результат:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
</head>
<body>
The user name is : ${homeDTO.userName}
</body>
</html>