Я пытаюсь добавить валидацию в мою форму, используя Hibernate Validator для моего проекта. При отправке страницы ниже отображается сообщение об ошибке. Но когда я удаляю аннотацию @ Valid из моего метода Controller ( UserController.handleLogin ), я могу предоставить сведения. Может кто-нибудь подсказать, что мне не хватает?
UserController. java
@Controller
public class UserController {
@RequestMapping(value = { "/", "/index" })
public String index(Model model) {
model.addAttribute("command", new LoginCommand());
return "index";
}
@RequestMapping(value = "/login", method = RequestMethod.GET)
public String handleLogin(Model model) {
model.addAttribute("err", null);
return "redirect:index";
}
@RequestMapping(value = "/login", method = RequestMethod.POST)
public String handleLogin(@Valid @ModelAttribute("command") LoginCommand cmd, Model model, HttpSession session, Errors error) {
if(error.hasErrors()) {
return "index";
}
try {
User loggedInUser = userService.doLogin(cmd.getLoginName(), cmd.getPassword());
if (loggedInUser == null) {
model.addAttribute("err", "Login failed, enter valid credentials");
return "index";
} else {
if (loggedInUser.getRole().equals(UserService.ROLE_ADMIN)) {
// add user to session
addUserToSession(loggedInUser, session);
return "redirect:admin/dashboard";
} else if (loggedInUser.getRole().equals(UserService.ROLE_USER)) {
// add user to session
addUserToSession(loggedInUser, session);
return "redirect:user/dashboard";
} else {
model.addAttribute("err", "Invalid User Role");
return "index";
}
}
} catch (UserBlockedException e) {
model.addAttribute("err", e.getMessage());
return "index";
}
}
}
LoginCommand. java
public class LoginCommand {
@Size(max = 20, min = 3, message = "Login Name must be between 3 and 20 characters")
private String loginName;
@Size(max = 20, min = 3, message = "Password cannot be empty")
private String password;
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
index. jsp
<s:url var="url_login" value="/login"></s:url>
<f:form action="${url_login}" modelAttribute="command" valign="middle" method="POST">
<table border="1" align="center" width="40%">
<thead>
<tr>
<td colspan="2" valign="middle" align="center">
<h2>Login here</h2></td>
</tr>
</thead>
<tbody>
<tr>
<td align="center">Username: </td>
<td align="center">
<f:input path="loginName" placeholder="Enter your username"/>
<f:errors path="loginName" />
</td>
</tr>
<tr>
<td align="center">Password: </td>
<td align="center">
<f:password path="password" placeholder="Enter your password"/>
<f:errors path="password"/>
</td>
</tr>
<tr>
<td colspan="2" align="center">
<f:button>Login</f:button>
<a href="${url_reg_form}" class="newReg">New User Registration</a>
</td>
</tr>
</tbody>
</table>
</f:form>