How to bind form data in Spring 2.5 most efficiently?
What would be the best way how to bind a form data to model? I mean I have a simple model class:
public class LoginCommand {
private String login;
private String password;
//getters and setters
}
And what would be the best way how to bind the form data to this command in Spring 2.5? Can the @InitBinder annotation help? I couldn't understa开发者_运维百科nd how does it work.. One way how i think it might work is bellow.
@Controller
public LoginController {
@RequestMapping(value = "/login/*", method = RequestMethod.POST)
public ModelAndView loginAction(@ModelAttribute("loginCommand") LoginCommand lc, BindingResult result) {
new LoginCommandValidator().validate(lc, result);
if (result.hasErrors()){
// didn't validate
} else {
// check against db
}
}
}
Is this the best way to do it?
Well, for login actions you probably need to look into Spring security. That aside I am going to give some insight to the more general question and suggest you look into the @RequestParam annotation...
@RequestMapping(value = "/login/*", method = RequestMethod.POST)
public ModelAndView handleLogin(@RequestParam("login") String username,
@RequestParam("password") String password) {
// create constructor, remove setters to make this immutable
LoginCommand lc = new LoginCommand(username, password);
// more code here...
}
I realize there are probably multiple ways to solve this problem but I like this approach due to it's simplicity and explicitness; or more simply, it's less magic and easy to read albeit slightly verbose.
精彩评论