以登录为例:
1.controller的登录方法:
@RequestMapping("/SSOAuth/login")
@ResponseBody
public ResponseValue login(@Valid @RequestBody LoginParam param, BindingResult result) {
//验证数据合法性
if (result.hasErrors()) {
ResponseValue responseValue = ResponseValue.newInstance(HeadCode.BAD_REQUEST);
responseValue.getHead().setMsg(result.getFieldError().getDefaultMessage());
return responseValue;
}
String loginName = param.getLoginName();
String pwd = param.getPassword();
if (loginValidation.exist(loginName) == false) {
ResponseValue value = ResponseValue.newInstance(HeadCode.NOT_FIND);
value.getHead().setMsg("用户信息不存在!");
return value;
}
if (loginValidation.verify(loginName, pwd) == false) {
ResponseValue value = ResponseValue.newInstance(HeadCode.BAD_REQUEST);
value.getHead().setMsg("密码不正确!");
return value;
}
return result(loginName, new Date());
}
该方法的关键是@valid注解和BindingResult结合使用验证传入的信息是否合法,LoginParam这是验证对象。
2.验证对象:
public class LoginParam implements Serializable {
private static final long serialVersionUID = 1L;
@NotBlank(message="{NotBlank.name}")
@Length(min=0, max=50, message="loginName长度超出范围")
private String loginName;
@NotBlank(message="{NotBlank.password}")
@Length(min=6, max=10, message="password长度超出范围")
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;
}
}