有没有我可以在 Spring 项目中使用的模型/实体形式抽象库?
我在 Java/Spring 世界中寻找类似于“Django forms framework”或“Symfony Forms”的东西。
基本思想是简化 JPA 实体表单创建并更轻松地创建多表单处理 Controller 。
最佳答案
如果我没理解错的话,您是在寻求一种将实体绑定(bind)到表单(并允许用户添加/编辑实体)的方法吗?在这种情况下,不需要另一个框架,Spring 已经很好地做到了这一点。一个简单的例子:
我们的 Controller 看起来像这样:
@Controller
@RequestMapping(value = "/addUser.html")
public class UserController {
@Autowired
private UserAccountService service;
@Autowired
@Qualifier("userValidator")
private Validator userValidator;
@ModelAttribute("user")
public User getBackingObject() {
//This gets the object we're letting the user edit.
//This can be any POJO so a JPA entity should be fine.
//Note that we're creating an object here but we could
//just as easily fetch one we already have from a database/service etc
return new User();
}
@RequestMapping(method = RequestMethod.GET)
public String showForm() {
//The form to present to the user
return "/addUser";
}
@RequestMapping(method = RequestMethod.POST)
//note: here Spring has automatically bound the entries that have been input into the webform into the User param supplied here
protected String onSubmit(User user, Errors errors, HttpServletRequest request) {
userValidator.validate(user, errors);
if (errors.hasErrors()) {
//The validator showed up some errors so send the object back to let the user correct it
return "/addUser";
}
//save our new user
service.saveUser(user);
//best practice is to redirect to another view to make sure the backing object is cleared
return "redirect:/success.html";
}
}
然后我们可以在 JSP 中使用 spring 表单宏来创建表单:
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<html>
<head>
<title>Add a user</title>
</head>
<body>
<form:form commandName="user">
<label for="firstname">first name</label>
<form:input path="firstname" /> <form:errors cssClass="errorText" path="firstname" />
<label for="lastname">last name</label>
<form:input path="lastname" /> <form:errors cssClass="errorText" path="lastname" />
<input type="submit" value="Save" />
</form:form>
</body>
</html>
关于Java/Spring模型表单框架,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5186279/