开发者

Automatically return to input form on @Valid failure

I have the following method in my controller:

@RequestMapping(value = "/status", method = RequestMethod.POST)
public String update(@Valid StatusForm statusForm, BindingResult result) {    
    if(result.hasErrors()) {
        return "statusForm";
    }
    //do stuff when there are no errors        
        return "dashboard";
}

It seems like in a lot of these methods there is a repeating code block:

if(result.hasErrors()) {
    return "statusForm";
}

Is there a way to avoid having开发者_如何学C to insert this block and automatically redirect back to where the POST request came from in an event of Validation errors?


The same action can be accessed from multiple pages, so you would have to configure the error view somehow. In struts for example, you have an xml file describing the input jsp for each action. It would probably be possible to create an annotation containing the view id and implement a AnnotationMethodHandlerAdapter to handle this logic.

The current way of doiing this in code has one advantage. It allows you to to additional validations in your action method, maybe checking some values in a database or some more complicated business rules, and handling this errors in a uniform way.


In your controller handler method, make sure that the BindingResult argument is immediately after the command argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜