@Valid作用

package com.springmvc.entity;

import org.hibernate.validator.constraints.Length;

import javax.validation.constraints.NotNull;
import java.io.Serializable;

/**
 * 用户实体类.
 */
public class User implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 用户ID
     */
    @NotNull(message = "id不能为空") //@valid就是校验这些添加注解的属性,校验从前端传入的参数是否合法,如果不合法会输出message里的值
    private String id;
    /**
     * 用户名
     */
    private String username;
    /**
     * 密码
     */
    @Length(min = 1, message = "密码最少位数是{min}") //同上
    private String password;
    /**
     * 性别
     */
    private String sex;

    public User() {
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

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

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }
}
    @RequestMapping("/find")
    @ResponseBody
    public Map<String, Object> find(@Valid User user, HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap();
        List<User> loginuser = userService.findByUsernameAndPwd(user.getUsername(), user.getPassword());
        if (loginuser != null) {
            map.put("result", "success");
        } else {
            map.put("result", "fail");
        }
        return map;
    }


密码框不输入,参数的参数是“”,不是空,所以用@notNull判断不出,需要用@Length

maven添加:(这两个maven最好都加上)

 <dependency>
          <groupId>javax.validation</groupId>
          <artifactId>validation-api</artifactId>
          <version>1.1.0.Final</version>
      </dependency>
      <dependency>
          <groupId>org.hibernate</groupId>
          <artifactId>hibernate-validator</artifactId>
          <version>5.1.0.Final</version>
      </dependency>

Spring版本:4.1.1

<mvc:annotation-driven validator="validator"/>,这句注解不添加也行


更多请见:

https://blog.csdn.net/xzmeasy/article/details/76098188

https://www.cnblogs.com/softidea/p/5839327.html


相关推荐
©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页