SpringMVC后台数据校验

在实际中,通常使用较多是前端的校验,比如页面中js校验,对于安全要求较高的建议在服务端也要进行校验。服务端校验可以是在控制层conroller,也可以是在业务层service,controller校验页面请求的参数的合法性,在服务端控制层conroller的校验,不区分客户端类型(浏览器、手机客户端、远程调用);service层主要校验关键业务参数,仅限于service接口中使用的参数。这里主要总结一下何如使用springmvc中后台Model和controller(控制器)的校验

一.环境准备

springmvc中我们使用hibernate的校验框架validation(注:和hibernate没有任何关系),使用这个校验框架的话,需要导入jar包,如下: 

        <dependency>
            <groupId>org.hibernate</groupId>
            <artifactId>hibernate-validator</artifactId>
            <version>4.3.1.Final</version>
        </dependency>

        <!--validation api-->
        <dependency>
            <groupId>javax.validation</groupId>
            <artifactId>validation-api</artifactId>
            <version>1.0.0.GA</version>
        </dependency>

二.配置检验器

<!--包扫描器-->
    <context:component-scan base-package="day15"></context:component-scan>

  <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>

    <!--验证器-->
    <bean id="myValidator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
        <property name="providerClass" value="org.hibernate.validator.HibernateValidator"></property>
        </bean>
        <!--注解驱动-->
<mvc:annotation-driven  validator="myValidator" ></mvc:annotation-driven>

三.在实体类中进行数据校验

/**
 * 后台数据校验
 */
public class UserInfo {
    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getPhone() {
        return phone;
    }

    public void setPhone(String phone) {
        this.phone = phone;
    }

/*    public Date getBirthday() {
        return birthday;
    }

    public void setBirthday(Date birthday) {
        this.birthday = birthday;
    }*/

    /*@NotBlank   用于String
    @NotEmpty   用于集合类型
    @NotNull    用于基本类型*/

    @NotBlank(message = "用户名不可以为空")
    @Size(min = 2,message = "用户名必须大于2个字符")
    private String username;

    @NotNull(message = "年龄不可以为空")
    @Max(value = 100,message = "年龄不能超过100!")
    @Min(value = 0,message = "年龄不能小于0岁!")
    private  Integer age;

    @NotEmpty(message = "邮箱不可以为空")
    @Pattern(regexp = "^\w+@\w+\.\w+$",message = "邮箱格式不正确")
    private String email;

    @NotEmpty(message = "电话不可以为空")
    @Pattern(regexp = "^1[3|8|5|9|7]\d{9}$",message = "电话必须是十一位")
    private String phone;

 /*   @NotEmpty(message = "出生日期不可以为空")
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date birthday;*/
}

四.捕获校验错误信息

@Controller
public class ValidatorCotroller {
    @RequestMapping("/first")
    /**
     * BindingResult和@Valid是需要一起使用的
     * 且Binding存在于@Valid之后 是用来存放校验结果的  从中获取错误信息
     *
     */
    public String doFirst(@Valid UserInfo info, BindingResult result, Model model){
        //result.getErrCount>0是代表着有错误信息
        if(result.getErrorCount()>0){
            //获取到页面上的错误信息属性值
            FieldError username = result.getFieldError("username");
            //声明一个Model  将获取到的UserINfo的属性值通过addAttribute()放入model中 方便页面上的值回显
            model.addAttribute("username",info.getUsername());
            FieldError age = result.getFieldError("age");
            model.addAttribute("age",info.getAge());
           // FieldError birthday = result.getFieldError("birthday");
            FieldError phone = result.getFieldError("phone");
            model.addAttribute("phone",info.getPhone());
            FieldError email = result.getFieldError("email");
            model.addAttribute("email",info.getEmail());
            /**
             * 如果获取到的错误信息为不等于空
             */
            if(username!=null){
                //通过上边获取到的属性的返回值变量去拿到错误信息  然后放入model  在Input文本框后边显示错误信息
                String nameMessage = username.getDefaultMessage();
                model.addAttribute("nameMessage",nameMessage);
            }
            if( age!=null){
                String  ageMessage = age.getDefaultMessage();
                model.addAttribute("ageMessage",ageMessage);
            }
            if(phone!=null){
                String phoneMessage = phone.getDefaultMessage();
                model.addAttribute("phoneMessage",phoneMessage);
            }
            if(email!=null){
                String emailMessage = email.getDefaultMessage();
                model.addAttribute("emailMessage",emailMessage);
            }
            //如果有错误  就返回本页面
            return "student";
        }
        //否则跳转到成功的页面
        return "suecssful";
    }
}

 

原文地址:https://www.cnblogs.com/1234AAA/p/8683629.html