好吧,我找到了一种方法使用Hibernate的验证器注解@Email & NOTNULL等验证表单字段:
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.Email;
import org.hibernate.validator.constraints.NotBlank;
public class LoginForm
{
@Email
@Size(min = 4, max = 128)
private String username;
@NotBlank
@Size(min = 4, max = 128)
private String password;
...
}
安全部分有点棘手,因为我必须手动对authenticationManager进行身份验证,并且安全上下文不想更新当前会话:
@Autowired
@Qualifier("authenticationManager")
private AuthenticationManager authenticationManager;
@RequestMapping(method = RequestMethod.POST)
public String processForm(@Valid LoginForm loginForm, BindingResult result, HttpServletRequest request, Model model)
{
// Display errors in loginForm if not valid
if (result.hasErrors())
return "login";
try
{
UsernamePasswordAuthenticationToken token = new UsernamePasswordAuthenticationToken(loginForm.getUsername(), loginForm.getPassword());
Authentication auth = authenticationManager.authenticate(token);
SecurityContextHolder.getContext().setAuthentication(auth);
// for some reason, security context is NOT setting the auth key in session
// so I had to put it here myself!
HttpSession session = request.getSession();
session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY, SecurityContextHolder.getContext());
return "redirect:/index";
}
catch (AuthenticationException e)
{
SecurityContextHolder.getContext().setAuthentication(null);
String errorMessage = e.getLocalizedMessage();
model.addAttribute("errorMessage", errorMessage);
return "loginerror";
}
}
请务必将别名认证管理器,以便能够自动装配它<security:authentication-manager alias="authenticationManager">
希望帮助别人:)
其实我在谈论验证,确保用户名是有效的电子邮件格式,或确保密码至少8个字符等等。 当然,我需要在服务器端进行验证,而不必考虑它也可以在客户端完成。 (问题已更新) – 2011-04-12 14:22:47
更新了我的回复。我看到你的答案,这绝对是可行的 - 但它绕过了标准的Spring Security流程。 – sourcedelica 2011-04-12 16:53:17