springboot 验证信息国际化

1.准备entity 属性用@NotBlank( message="{error.name}")
2.controller 入参 @Valid User
3.项目中加入 GlobalExceptionHandler
4.在resources目录下增加 ValidationMessages.properties ValidationMessages_en_US.properties ValidationMessages_zh_CN.properties

若要自定义文件位置或名称则需要重写WebMvcConfigurerAdapter 的 getValidator 方法
代码见 MyConfigureation

@Configuration
public class MyConfigureation extends WebMvcConfigurerAdapter {

public ResourceBundleMessageSource getMessageSource() throws Exception {
ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
rbms.setDefaultEncoding("UTF-8");
rbms.setBasenames(" i18n/error/ValidationMessages"); // 此为文件目录 ValidationMessages是文件名
rbms.setCacheSeconds(10);
return rbms;
}

@Bean
@Override
public Validator getValidator() {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
try {
validator.setValidationMessageSource(getMessageSource());
} catch (Exception e) {
e.printStackTrace();
}
return validator;
}
}

@ControllerAdvice
@RestController
public class GlobalExceptionHandler implements ErrorController {
private Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);

@ExceptionHandler(value = Exception.class)
@RequestMapping("/error")
public Result defaultErrorHandler(HttpServletRequest req, Exception ex) throws Exception {
logger.error("", ex);
String result = "";
if (ex instanceof BindException) {
BindException bindException = (BindException) ex;
for (FieldError fieldErro : bindException.getBindingResult().getFieldErrors()) {
result += "【" + fieldErro.getField() + ":" + fieldErro.getDefaultMessage() + "】";
}
} else if (ex instanceof MethodArgumentNotValidException) {
MethodArgumentNotValidException methodArgumentNotValidException = (MethodArgumentNotValidException) ex;
for (FieldError fieldErro : methodArgumentNotValidException.getBindingResult().getFieldErrors()) {
result += "【" + fieldErro.getField() + ":" + fieldErro.getDefaultMessage() + "】";
}
} else if (ex instanceof HttpRequestMethodNotSupportedException) {
HttpRequestMethodNotSupportedException httpRequestMethodNotSupportedException = (HttpRequestMethodNotSupportedException) ex;
result = httpRequestMethodNotSupportedException.getMessage();
} else if (ex instanceof NoHandlerFoundException) {
result = "无效的请求地址";
} else if (ex instanceof MissingServletRequestParameterException) {
MissingServletRequestParameterException missingServletRequestParameterException = (MissingServletRequestParameterException) ex;
result = "缺少必要的参数[" + missingServletRequestParameterException.getMessage() + "]";
} else {
result = "Error handling OR Service unavaliable at client01";
}

return new Result(1, result);
}

public String getErrorPath() {
return "/error";
}
}

public class User {
private int id;
@NotBlank(message="{error.name}")
private String name;
@NotEmpty(message="密码不能为空")
private String pwd;
............
}

@Controller
public class HelloController {
@ResponseBody
@RequestMapping("/user")
public User test(@Valid User user){
System.out.println(user);
return user;
}
}

你可能感兴趣的:(技术)