实现了Validator接口,前端页面使用
1.javaBean
2.前端登陆页面
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib uri= "http://www.springframework.org/tags/form" prefix="form" %>
登录名: | ||
密码: | ||
3.MyValidator类,实现了Validator接口
4.Controller类
package com.controller;
import javax.annotation.Resource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.validation.Errors;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import com.bean.User;
import com.validator.MyValidator;
@Controller
public class UserController {
@Autowired
@Resource
private MyValidator validator;
@RequestMapping("/{login}")
public String login(@PathVariable String login, ModelMap mm){
mm.addAttribute("user", new User());
return login;
}
@RequestMapping("/tologin")
//在需要校验的属性前面加@Validated
//BindingResult属性必须要放在@Validated注解属性的后面,否则spring会在校验不通过时直接抛出异常
public String tologin(@Validated User user, BindingResult result){
if(result.hasErrors()){
return "login";
}
return "success";
}
@InitBinder
public void initBinder(WebDataBinder binder){
binder.setValidator(validator);
}
/*@RequestMapping("/tologin")
//在需要校验的属性前面加@Validated
//Errors属性必须要放在@Validated注解属性的后面
public String tologin(@Validated User user, Errors errors){
validator.validate(user, errors);
if(errors.hasErrors()){
return "login";
}
return "success";
}*/
}
上面两种@RequestMapping("/tologin")映射的作用效果一样
5.配置文件:
xmlns:p="http://www.springframework.org/schema/p"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.3.xsd">