3

我正在设置 @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 指定模型的方式在某种程度上是不正确的,但我不确定。

4

1 回答 1

-1

您不应该在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 {

如果您需要一个工作示例,请查看此处

于 2015-06-25T16:30:56.243 回答