You might not want to use the entity as a form backing object which could have security implications. For example an malicious request could be forged to set some unwanted properties.
Therefor it's better in general to create a explicit form backing object for each form to process. It will require you to write more code but it also negates some common problems (like the one you're having).
When using a form backing object your handler looks more like:
Note that I altered the BPost
argument to BPostForm
.
@RequestMapping(value = "/edit/{id}", method = RequestMethod.POST)
public String editProcessPost(Model model, @PathVariable Integer id, @ModelAttribute BPostForm editPost) {
// fetch the original post
BPost post = bPostService.findById(editPost.getId());
// set the properties
post.setTitle(editPost.getTitle());
post.setDescription(editPost.getDescription());
post.setText(editPost.getText());
// update
bPostService.updatePost(post);
model.addAttribute("posts", bPostService.getPosts());
return "redirect:/";
}
P.s. Using bPostService.getPosts()
to add posts to the model and immediately return a redirect seems rather pointless ;)
[EDIT] Validation
Your form backing object can be validated using declarative validation using the Hibernate annotations or settings a custom validator in the WebdataBinder
.
Hibernate annotations
When using the Hibernate annotations you can place any annotation on a field or getter. For these validations to kick in you'll need to do two things.
- Register a validator bean
org.springframework.validation.beanvalidation.LocalValidatorFactoryBean
. - Annotate the form backing object's argument in your handler with
@valid
.
Example: public String editProcessPost(Model model, @PathVariable Integer id, @ModelAttribute @Valid BPostForm editPost, BindingResult result)
Note that using validation needs a BindingResult
to be present in the argument list and it needs to be directly after the backing object. This BindingResult
will be a container for all validation errors.
Custom validator
A custom validator is a bit more work. You will need to write your own first.
MyPostValidator extends org.springframework.validation.Validator
After writing the validator you can add it to the WebDataBinder
.
@InitBinder
public void initBinder(WebDataBinder binder) {
binder.setValidator(new MyPostValidator());
}