Java/Spring模型表单框架
是否有任何模型/实体表单抽象库可供我在Spring项目中使用 在Java/Spring世界中,我看起来有点像“”或“”Java/Spring模型表单框架,java,spring,forms,spring-mvc,webforms,Java,Spring,Forms,Spring Mvc,Webforms,是否有任何模型/实体表单抽象库可供我在Spring项目中使用 在Java/Spring世界中,我看起来有点像“”或“” 基本思想是简化JPA实体表单的创建和更容易地创建多种表单处理控制器。我认为spring roo做了您想做的事情。如果我正确理解了您的意思,您正在寻找一种将实体绑定到表单的方法(并允许用户添加/编辑实体)?在这种情况下,不需要另一个框架,Spring已经做得很好了。一个简单的例子: 我们的控制器如下所示: @Controller @RequestMapping(value = "
基本思想是简化JPA实体表单的创建和更容易地创建多种表单处理控制器。我认为spring roo做了您想做的事情。如果我正确理解了您的意思,您正在寻找一种将实体绑定到表单的方法(并允许用户添加/编辑实体)?在这种情况下,不需要另一个框架,Spring已经做得很好了。一个简单的例子: 我们的控制器如下所示:
@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>
添加用户
名字
姓
我见过这样的例子,但有并没有人可以帮助我避免为我的所有实体实现控制器逻辑,对我来说,这似乎太多样板代码了?是的,正如surajz Spring Roo所提到的,它是一个命令行工具,可以为您编写大量粘合代码。特别是当你从零开始你的项目时,它值得一看。这么说来,一旦你开始编写控制器,你就会发现,这一点额外的冗长会让你在处理代码方面有更大的能力。因此,回答我最初的问题,没有spring的forms框架可用。只是一堆用于创建样板代码的辅助工具。是的,这是我可以找到的更接近表单库的形式,()感谢您指出这一点。np。您还可以使用spring数据项目。它可能会减少您的样板jpa代码。希望这有帮助