Is there any model/entity form abstraction library available i can use in Spring projects ?
I'm looking something like "Django forms framework" or "Symfony Forms" in the Java/Spring world.
The basic idea is to simplify JPA开发者_如何学编程 entities form creation and the easier creation of multiform handling controllers.
If i've understood you correctly you're after a way to bind an entity to a form (and allow a user to add/edit entities)? In which case theres no need for another framework Spring already does this really well. A quick example:
Our controller would look like this:
@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";
}
}
Then we can use spring form macros in our JSP to create the form:
<%@ 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>
I think spring roo does what you want to do.
精彩评论