@InitBinder を設定して、Spring MVC コントローラーのバリデーターを設定しています。ただし、実行時にバリデーターが実際に起動されるようには見えません。
コントローラーは次のようになります。
@Controller
@RequestMapping("/login")
public class LoginController {
final private static String USER_COOKIE_NAME = "ADVPROT_CHAT_USER";
final private static String CURRENT_VIEW = "login";
final private static String SUCCESS_VIEW = "redirect:welcome.htm";
@Autowired
private UserManagerService userManagerService;
@Autowired
private LoginValidator loginValidator;
@InitBinder("login")
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new LoginValidator());
}
@RequestMapping(method = RequestMethod.POST)
protected String processSubmit(@Valid @ModelAttribute("login") Login login, BindingResult result, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
if(result.hasErrors()) {
return CURRENT_VIEW;
} else {
model.addAttribute("login", login);
String loginResultMessage = "Login successful via LDAP";
User user = getUser(login.getUsername());
model.addAttribute("userLoggedIn", user);
model.addAttribute("loginResultMessage", loginResultMessage);
request.getSession().setAttribute("userLoggedIn", login.getUserLoggingIn());
if (login.getUserLoggingIn() != null) {
response.addCookie(new Cookie(USER_COOKIE_NAME, login.getUserLoggingIn().getId()));
}
return SUCCESS_VIEW;
}
}
private User getUser(String username) throws Exception {
return userManagerService.getUserById(username);
}
@RequestMapping(method = RequestMethod.GET)
protected String initForm(ModelMap model, HttpServletRequest request) {
Login login = new Login();
Cookie[] cookies = request.getCookies();
if (cookies != null && cookies.length > 0) {
for (Cookie nextCookie: cookies ) {
if (nextCookie.getName().equals(USER_COOKIE_NAME)) {
login.setUsername(nextCookie.getValue());
break;
}
}
}
model.addAttribute("login", login);
return CURRENT_VIEW;
}
}
実行時に、バリデーターがチェックを行っているようには見えません。
モデル属性を指定せずに @InitBinder を使用すると
@InitBinder
protected void initBinder(WebDataBinder binder) {
binder.setValidator(new LoginValidator());
}
バリデーターが他のオブジェクトで起動されたようで、例外が発生します。したがって、 @InitBinder のモデルを指定する方法は何らかの形で間違っていると思いますが、確かではありません。