登录页面表单
<form action="<%=request.getContextPath()%>/login.do" method="post">
用户名:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
<input type="submit" name="Login"/><br>
</form>
注册页面表单
<form action="<%=request.getContextPath()%>/register.do" method="post">
用户名:<input type="text" name="username"/><br>
密码:<input type="text" name="password"/><br>
真实姓名:<input type="text" name="realname"/><br>
年龄:<input type="text" name="age"/><br>
性别:<select>
<option value="1">男</option>
<option value="2">女</option>
</select><br>
<input type="submit" name="Login"/><br>
</form>
两个表单对应同一个User类的数据成员,要想表单数据校验必须使用分组校验才能实现,不然登录和注册不能使用同一个User类
创建两个空的接口
public interface ValidateLoginForm {
}
public interface ValidateRegisterForm {
}
User数据成员校验的注解中使用group属性
@Length(min=6,max=16,message="{UserNameErrorMessage}",groups = {ValidateLoginForm.class,ValidateRegisterForm.class})
private String username;
@Length(min=6,max=16,message="{UserPasswordErrorMessage}",groups = {ValidateLoginForm.class,ValidateRegisterForm.class})
private String password;
@NotBlank(message = "{UserRealNameErrorMessage}",groups = {ValidateRegisterForm.class})
private String realname;
@Range(min=0,max=150,message = "{UserAgeErrorMessage}",groups = {ValidateRegisterForm.class})
private Integer age;
@Pattern(regexp ="^[1-2]$",message = "{UserSexErrorMessage}",groups = {ValidateRegisterForm.class})
private String sex;
访问Controller中的方法指定使用分组
import java.util.List;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.yf.domain.User;
import com.yf.domain.ValidateLoginForm;
import com.yf.domain.ValidateRegisterForm;
@Controller
public class UserController {
/**
* 处理登录请求
* @param user
* @param bindingResult
* @return
*/
@RequestMapping("login.do")
public ModelAndView login(@Validated(value= {ValidateLoginForm.class}) User user,BindingResult bindingResult) {
System.out.println("user:"+user);
if(bindingResult.hasErrors()) {
List<ObjectError> error=bindingResult.getAllErrors();
for(ObjectError e:error) {
System.out.println(e.getDefaultMessage());
}
}
return null;
}
/**
* 处理注册请求
* @param user
* @param bindingResult
* @return
*/
@RequestMapping("register.do")
public ModelAndView register(@Validated(value= {ValidateRegisterForm.class}) User user,BindingResult bindingResult) {
System.out.println("user:"+user);
if(bindingResult.hasErrors()) {
List<ObjectError> error=bindingResult.getAllErrors();
for(ObjectError e:error) {
System.out.println(e.getDefaultMessage());
}
}
return null;
}
}