Springboot使用validation驗證參數之二

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);
    }

}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章