[英]Should l make Spring Model class with one field?
I don't know should i make class with only one field which l will use as @ModelAttribute to get data from jsp?我不知道我是否应该只使用一个字段来创建类,我将使用该字段作为 @ModelAttribute 从 jsp 获取数据? for example:
例如:
public class Age {
private int number;
public int getNumber() {
return number;
}
public void setNumber(int number) {
this.number = number;
}}
And then using spring mvc form tag to fill this ModuleAttribute然后使用 spring mvc 表单标签来填充这个 ModuleAttribute
<form:form action="processForm" modelAttribute="age">
<form:input path="number"/>
</form:form>
First of all, you need to create a controller :首先,您需要创建一个控制器:
@Controller
public class AgeController {
// this is to create an instance of Age and set in the model.
@RequestMapping("showForm")
public String showForm(Model model) {
model.addAttribute("age", new Age());
return "form"; // return form page.
}
// this is to print the age in the display page.
@RequestMapping("processForm")
public String processForm(@ModelAttribute("age") Age age) {
return "display"; // return display page where you will display the data populated in the form page.
}
}
Now, form page should look like :现在,表单页面应该如下所示:
<%@taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html>
<html>
<!-- When you enter the data here, Spring will set the data in the Age bean by calling respective setter of the data members -->
<body>
<form:form action="processForm" modelAttribute="age">
Enter an age : <form:input path="number" />
<input type="submit" value="Submit" />
</form:form>
</body>
</html>
Now, display page should look like :现在,显示页面应如下所示:
<%@taglib prefix="core" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<body>
The age is : ${age.number} <!-- Here getter is called internally -->
</body>
</html>
On clicking the submit, the display page will show the data.单击提交后,显示页面将显示数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.