我正在设置@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());
}
看起来验证器会被其他obejects触发,我得到异常。所以,我的猜测是我为@InitBinder指定模型的方式在某种程度上是不正确的,但我不确定。
答案 0 :(得分:0)
您不应在InitBinder
中创建验证程序的新实例。它必须看起来像:
@Autowired
private LoginValidator loginValidator;
@InitBinder
public void InitBinder(WebDataBinder binder) {
binder.setValidator(loginValidator);
}
由于您使用的是验证程序,因此您必须使用@Validated
而不是@Valid
。我的意思是:
@RequestMapping(method = RequestMethod.POST)
protected String processSubmit(@Validated @ModelAttribute("login") Login login, BindingResult result, ModelMap model, HttpServletRequest request, HttpServletResponse response) throws Exception {
如果您需要一个有效的示例,请查看here