Spring 进入Controller前参数校验

在进入Controller前完成参数的校验,针对对象参数

分为两个验证方式

(1)直接使用已定义的校验方式

1、在需要进行校验的属性上增加校验类型注解

import java.util.Date;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.NotBlank;

public class User {
    private String id;

    private String username;

    @NotBlank(message = "密码不能为空")
    private String password;

    @Past(message = "生日必须是过去的日期")
    private Date birthday;

    @JsonView(UserSimpleView.class)
    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 getId() {
        return id;
    }

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

    public Date getBirthday() {
        return birthday;
    }

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

}

2、在controller中增加注解

3、增加 BindingResult 获取错误信息

import java.util.ArrayList;
import java.util.List;
import javax.validation.Valid;
import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;
import org.springframework.data.domain.Pageable;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.fasterxml.jackson.annotation.JsonView;
import com.maple.dto.User;
import com.maple.dto.UserQueryCondition;
import com.maple.dto.User.UserDetailView;
import com.maple.dto.User.UserSimpleView;
import com.maple.exception.UserNotExitException;

/**
 * 
 * @author hzc
 *
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @PostMapping
    public User createUser(@Valid @RequestBody User user, BindingResult errors) {
        if (errors.hasErrors()) { //判断是否有错误值
            errors.getAllErrors().stream().forEach(error -> System.out.println(error.getDefaultMessage()));
        }

        System.out.println(user.getId());
        System.out.println(user.getPassword());
        System.out.println(user.getUsername());
        System.out.println(user.getBirthday());
        user.setId("1");
        return user;
    }
}

 API中已有的校验方法

(2)自定义校验方法

 1、建立自定义注解类,@Target  : 注解的范围,如方法,属性,类等 ;   @Retention  : 注解的生命周期,值为 RetentionnPolicy枚举类

package com.maple.validator;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import javax.validation.Constraint;
import javax.validation.Payload;

@Target({ ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = MyConstraintValidator.class) // 绑定下面自定义的校验方法
public @interface MyConstraint {

    // 需要定义以下三个属性
    String message();

    Class<?>[] groups() default { };

    Class<? extends Payload>[] payload() default { };
    
}

2、定义校验方法,可在方法中使用 @Autowired 实现类的注入,在isValid中实现参数的验证。

package com.maple.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import org.springframework.beans.factory.annotation.Autowired;

public class MyConstraintValidator implements ConstraintValidator<MyConstraint, Object> {
    
    @Override
    public void initialize(MyConstraint constraintAnnotation) {
        System.out.println("my validator init");
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {
        helloService.greeting("Tom");        
        System.out.println(value);        
        return false;
    }

}

3、调用自定义的校验,在属性上增加自定义的注解 @MyConstraint

    @MyConstraint(message = "这是一个测试")
    private String username;

 

 

 

 

posted @ 2019-04-27 20:43  Topze  阅读(6593)  评论(0编辑  收藏  举报