Springboot使用validation验证参数之二

本文深入探讨了如何在Springboot应用中集成Bean Validation进行参数校验,详细介绍了配置步骤、注解使用以及自定义验证规则的方法,帮助开发者提升参数验证的效率和体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

package com.example.springbootvalidation.configuration;

import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
import org.springframework.web.servlet.i18n.*;

import java.util.Locale;

@Configuration
@EnableAutoConfiguration
@ComponentScan
public class LocaleResolverConfig implements WebMvcConfigurer {

    @Bean
    public LocaleResolver localeResolver() {
        /*
        //通过浏览器头部的语言信息来进行多语言选择
        AcceptHeaderLocaleResolver acceptHeaderLocaleResolver = new AcceptHeaderLocaleResolver();
        //设置固定的语言信息,这样整个系统的语言是一成不变的
        FixedLocaleResolver fixedLocaleResolver = new FixedLocaleResolver();
        //将语言信息设置到Cookie中
        CookieLocaleResolver cookieLocaleResolver = new CookieLocaleResolver();
        cookieLocaleResolver.setCookieName("localeCookie");
        cookieLocaleResolver.setCookieMaxAge(3600);
        cookieLocaleResolver.setDefaultLocale(Locale.CHINESE);//language
        cookieLocaleResolver.setDefaultLocale(Locale.CHINA);//country
        cookieLocaleResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);//zh CN
        */

        //将语言信息放到Session中
        SessionLocaleResolver sessionLocaleResolver = new SessionLocaleResolver();
        // 默认语言
        sessionLocaleResolver.setDefaultLocale(Locale.SIMPLIFIED_CHINESE);
        return sessionLocaleResolver;
    }

    @Bean
    public LocaleChangeInterceptor localeChangeInterceptor() {
        LocaleChangeInterceptor lci = new LocaleChangeInterceptor();
        // 参数名
        lci.setParamName("lang"); //?lang=zh_CN  lang=en_US
        return lci;
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(localeChangeInterceptor());
    }
}
package com.example.springbootvalidation.configuration;

import org.springframework.boot.validation.MessageInterpolatorFactory;
import org.springframework.context.MessageSource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@Configuration
public class ValidationConfiguration {

    @Bean
    public MessageSource messageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setDefaultEncoding("utf-8");//读取配置文件的编码格式
        source.setCacheMillis(-1);//缓存时间,-1表示不过期
        //source.setBasename("ValidationMessages");//配置文件前缀名,设置为Messages,那你的配置文件必须以Messages.properties/Message_en.properties...
        source.setBasename("messages");
        return source;
    }

    @Bean
    public Validator validator() {
        LocalValidatorFactoryBean factoryBean = new LocalValidatorFactoryBean();
        MessageInterpolatorFactory interpolatorFactory = new MessageInterpolatorFactory();
        factoryBean.setMessageInterpolator(interpolatorFactory.getObject());
        factoryBean.setValidationMessageSource(this.messageSource());
        return factoryBean;
    }

}
package com.example.springbootvalidation.controller;

import com.example.springbootvalidation.interfaces.UpdateAction;
import com.example.springbootvalidation.interfaces.InsertAction;
import com.example.springbootvalidation.pojo.Student;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.MessageSource;
import org.springframework.context.i18n.LocaleContextHolder;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotBlank;
import javax.validation.constraints.NotNull;
import javax.validation.groups.Default;
import java.util.Locale;

@RestController
@Validated
@RequestMapping("/student/")
public class StudentController {

    @Autowired
    private  MessageSource messageSource;

    @GetMapping("get")
    //@RequestParam(value = "id",required = true)
    public Integer getValidation(@Validated  @Min(value = 1,message = "{validation.student.id.wrong}")
            @NotNull(message = "{validation.student.id.required}") Integer id) {
        return id;
    }

    @PostMapping("add")
    public String addValidation(@Validated({InsertAction.class, Default.class})  @RequestBody Student student) {
        return "success";
    }

    @PostMapping("update")
    public String updateValidation(@Validated({UpdateAction.class, Default.class}) @RequestBody Student student) {
        return "success";
    }

    @GetMapping(value = "change")//produces = "text/plain;charset=UTF-8"
    public String changeLocale(){
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage("welcome",null,locale);
    }

}
package com.example.springbootvalidation.handler;

import com.example.springbootvalidation.pojo.ResponseResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.MissingServletRequestParameterException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolationException;
import java.util.List;

@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandler {

    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseResult validationBodyException(MethodArgumentNotValidException exception){
        StringBuffer buffer = new StringBuffer();
        BindingResult result  = exception.getBindingResult();
        if (result.hasErrors()) {
            List<ObjectError> errors = result.getAllErrors();
            errors.forEach(p ->{
                FieldError fieldError = (FieldError) p;
                buffer.append(fieldError.getDefaultMessage()).append(";");
            });
        }
        ResponseResult response = new ResponseResult("400",buffer.toString().substring(0, buffer.toString().length()-1));
        return response;
    }

    @ResponseBody
    @ExceptionHandler(MissingServletRequestParameterException.class)
    public ResponseResult validationBodyException(MissingServletRequestParameterException exception){
        ResponseResult response = new ResponseResult("400",exception.getLocalizedMessage());
        return response;
    }

    @ResponseBody
    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseResult validationBodyException(ConstraintViolationException exception){
        String msg = exception.getMessage();
        String[] msgs = msg.split(": ");

        ResponseResult response = new ResponseResult("400",msgs[msgs.length-1]);
        return response;
    }
    
}
package com.example.springbootvalidation.interfaces;

public interface InsertAction {
}



package com.example.springbootvalidation.interfaces;

public interface UpdateAction {
}
package com.example.springbootvalidation.pojo;

import lombok.Data;

@Data
public class ResponseResult {
    private String code;
    private String message;
    private Object result;

    public ResponseResult(Object result) {
        this.code = "200";
        this.message = "success";
        this.result = result;
    }

    public ResponseResult(String code, String message) {
        this.code = code;
        this.message = message;
        this.result = null;
    }

    public ResponseResult(String code, String message, Object result) {
        this.code = code;
        this.message = message;
        this.result = result;
    }
}
package com.example.springbootvalidation.pojo;

import com.example.springbootvalidation.interfaces.UpdateAction;
import com.example.springbootvalidation.interfaces.InsertAction;
import lombok.Data;

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

@Data
public class Student implements Serializable {

    private static final long serialVersionUID = 1L;

    @Null(message = "{validation.student.id.should.null}", groups = InsertAction.class)
    @NotNull(message = "{validation.student.id.should.notnull}", groups = UpdateAction.class)
    private Integer ID;

    @NotBlank(message="{validation.student.name.should.notnull}")
    private String name;

    @Email(message="{validation.student.email.format.wrong}")
    private String email;

    @Pattern(regexp="^([012])$",message="{validation.student.sex}")
    private String sex;

}
package com.example.springbootvalidation;

import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.support.SpringBootServletInitializer;

public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(SpringbootValidationApplication.class);
    }

}



package com.example.springbootvalidation;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.validation.Validator;
import org.springframework.validation.beanvalidation.LocalValidatorFactoryBean;

@SpringBootApplication
public class SpringbootValidationApplication {

    public static void main(String[] args) {
        SpringApplication.run(SpringbootValidationApplication.class, args);
    }

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值