aku*_*ma8 2 java forms spring spring-mvc
是否可以使用Spring注释@ModelAttribute而不使用Spring标签来处理表单<form:form...>。我看到了这种方法,但是使用Thymeleaf似乎很复杂(我对此一无所知)。
Spring应该是一个非侵入性框架,所以我的问题是否有替代解决方案?
如果使用Spring标记构建表单,它将被转换为HTML。运行您的项目,并检查JSP站点的源代码。Spring标签只是使编码人员的工作变得容易一些。例如
<form:form modelAttribute="newUser" action="/addUser" method="post">
<form:input path="firstName" />
<form:input path="lastName" />
<button type="submit">Add</button>
</form:form>
Run Code Online (Sandbox Code Playgroud)
将转换为HTML
<form id="newUser" action="/addUser" method="post">
<input id="firstName" name="firstName" type="text" value="" />
<input id="lastName" name="lastName" type="text" value="" />
<button type="submit">Add</button>
</form>
Run Code Online (Sandbox Code Playgroud)
例如,在Controller中,将数据传输对象(DTO)添加到Model中
@RequestMapping(value = "/index", method = RequestMethod.GET)
public ModelAndView homePage() {
ModelAndView model = new ModelAndView();
model.addObject("newUser", new User());
model.setViewName("index");
return model;
}
Run Code Online (Sandbox Code Playgroud)
并接收表格数据
@RequestMapping(value = "/addUser", method = RequestMethod.POST)
public ModelAndView addUser(
@ModelAttribute("newUser") User user) { ... }
Run Code Online (Sandbox Code Playgroud)
只要表单字段的命名与bean对象(此处为User类)和模型中的命名完全相同,使用Spring标记是完全可选的。
| 归档时间: |
|
| 查看次数: |
7133 次 |
| 最近记录: |