Commit 74ab33da by zhanghj

V1.0.0--提交hibernate-validator校验

git-svn-id: svn://192.168.3.233/frms/code/car-service/trunk/car-service@16300 aeb6102e-e053-11e5-9fec-f9ebc45caf4b
1 parent 55ec349c
...@@ -30,6 +30,12 @@ ...@@ -30,6 +30,12 @@
<artifactId>car-service-common</artifactId> <artifactId>car-service-common</artifactId>
<version>1.0.0</version> <version>1.0.0</version>
</dependency> </dependency>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>test</scope>
</dependency>
<!-- springboot使用Shiro框架 --> <!-- springboot使用Shiro框架 -->
<dependency> <dependency>
<groupId>org.apache.shiro</groupId> <groupId>org.apache.shiro</groupId>
...@@ -42,6 +48,12 @@ ...@@ -42,6 +48,12 @@
<artifactId>shiro-ehcache</artifactId> <artifactId>shiro-ehcache</artifactId>
<version>${shiro.version}</version> <version>${shiro.version}</version>
</dependency> </dependency>
<!-- hibernate.validator -->
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
<version>6.0.13.Final</version>
</dependency>
</dependencies> </dependencies>
<build> <build>
......
package com.glsx.manager.config;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.validation.beanvalidation.MethodValidationPostProcessor;
/**
*
* @Title ValidatorConfig.java
* @Package com.glsx.manager.config
* @Description TODO hibernate-validator验证配置
* @author zhanghj
* @date 2019年1月3日 下午5:01:02
* @version 1.0.0
*/
@Configuration
public class ValidatorConfig {
final static Logger logger = LoggerFactory.getLogger(ValidatorConfig.class);
@Bean
public MethodValidationPostProcessor methodValidationPostProcessor() {
return new MethodValidationPostProcessor();
}
/*public ResourceBundleMessageSource getMessageSource() throws Exception {
ResourceBundleMessageSource rbms = new ResourceBundleMessageSource();
rbms.setDefaultEncoding("UTF-8");
rbms.setBasenames("i18n/validation/ValidationMessages");
return rbms;
}
@Bean
public Validator getValidator() throws Exception {
LocalValidatorFactoryBean validator = new LocalValidatorFactoryBean();
validator.setValidationMessageSource(getMessageSource());
return validator;
} */
}
package com.glsx.manager.controller;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.Validator;
import javax.validation.ValidatorFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
/**
*
* @Title BaseController.java
* @Package com.glsx.manager.controller
* @Description TODO
* @author zhanghj
* @date 2019年1月3日 下午4:51:03
* @version 1.0.0
*/
public class BaseController {
public Logger logger = LoggerFactory.getLogger(getClass());
/**
* hibernate-validator参数校验返回错误方法
* @param result
* @return
*/
public Map<String, String> getErrors(BindingResult result) {
Map<String, String> map = new HashMap<String, String>();
List<FieldError> list = result.getFieldErrors();
for (FieldError error : list) {
map.put(error.getField(), error.getDefaultMessage());
}
return map;
}
/**
* hibernate-validator对于特殊参数格式的校验方式
* @param object
* @return
*/
public Map<String, String> getErrors(Object object) {
Map<String, String> map = new HashMap<String, String>();
ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
Validator validator = factory.getValidator();
Set<ConstraintViolation<Object>> constraintViolations = validator.validate(object);
for (ConstraintViolation<Object> constraintViolation : constraintViolations) {
String key = constraintViolation.getPropertyPath().toString();
String value = constraintViolation.getMessage();
map.put(key, value);
}
return map;
}
}
...@@ -4,7 +4,10 @@ import java.util.HashMap; ...@@ -4,7 +4,10 @@ import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
...@@ -19,18 +22,18 @@ import com.glsx.manager.utils.PropertiesUtil; ...@@ -19,18 +22,18 @@ import com.glsx.manager.utils.PropertiesUtil;
@RestController @RestController
@RequestMapping(value="/test") @RequestMapping(value="/test")
public class TestController { public class TestController extends BaseController{
@Autowired @Autowired
private TestService testService; private TestService testService;
@RequestMapping(value="/get", method={RequestMethod.GET, RequestMethod.POST}) @RequestMapping(value="/get", method={RequestMethod.GET, RequestMethod.POST})
public ResultObject index(Test test){ public ResultObject index(@Valid Test test, BindingResult bindingResult){
try{ if (bindingResult.hasErrors()) {
test = testService.get(test); Map<String, String> errorMap = getErrors(bindingResult);
}catch(Exception e){ return new ResultObject(ResultCodeEnum.PARAM_ERROR.getCode(), ResultCodeEnum.PARAM_ERROR.getMsg(), errorMap);
} }
test = testService.get(test);
return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), test); return new ResultObject(ResultCodeEnum.SUCCESS.getCode(), ResultCodeEnum.SUCCESS.getMsg(), test);
} }
......
...@@ -9,16 +9,29 @@ import java.util.Date; ...@@ -9,16 +9,29 @@ import java.util.Date;
*/ */
public class BaseModel { public class BaseModel {
/**
* 主键id
*/
private Integer id; private Integer id;
/**
* 创建人
*/
private String createBy; private String createBy;
/**
* 创建时间
*/
private Date createTime; private Date createTime;
/**
* 更新人
*/
private String updateBy; private String updateBy;
/**
* 更新时间
*/
private Date updateTime; private Date updateTime;
/**
* 备注
*/
private String remark; private String remark;
public Integer getId() { public Integer getId() {
......
package com.glsx.manager.pojo; package com.glsx.manager.pojo;
import javax.validation.constraints.NotNull;
/**
*
* @Title Test.java
* @Package com.glsx.manager.pojo
* @Description TODO
* @author zhanghj
* @date 2019年1月3日 下午4:44:21
* @version 1.0.0
*/
/**
* Bean Validation 中内置的 constraint
* @Null 被注释的元素必须为 null
* @NotNull 被注释的元素必须不为 null
* @AssertTrue 被注释的元素必须为 true
* @AssertFalse 被注释的元素必须为 false
* @Min(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @Max(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @DecimalMin(value) 被注释的元素必须是一个数字,其值必须大于等于指定的最小值
* @DecimalMax(value) 被注释的元素必须是一个数字,其值必须小于等于指定的最大值
* @Size(max=, min=) 被注释的元素的大小必须在指定的范围内
* @Digits (integer, fraction) 被注释的元素必须是一个数字,其值必须在可接受的范围内
* @Past 被注释的元素必须是一个过去的日期
* @Future 被注释的元素必须是一个将来的日期
* @Pattern(regex=,flag=) 被注释的元素必须符合指定的正则表达式
* Hibernate Validator 附加的 constraint
* @NotBlank(message =) 验证字符串非null,且长度必须大于0
* @Email 被注释的元素必须是电子邮箱地址
* @Length(min=,max=) 被注释的字符串的大小必须在指定的范围内
* @NotEmpty 被注释的字符串的必须非空
* @Range(min=,max=,message=) 被注释的元素必须在合适的范围内
*/
public class Test { public class Test {
@NotNull(message="{param.not.null}")
private Integer id; private Integer id;
private String username; private String username;
......
param.not.null=\u53c2\u6570\u4e0d\u80fd\u4e3a\u7a7a
\ No newline at end of file \ No newline at end of file
...@@ -87,7 +87,7 @@ spring.freemarker.template-loader-path=classpath:/templates ...@@ -87,7 +87,7 @@ spring.freemarker.template-loader-path=classpath:/templates
#\u9759\u6001\u8d44\u6e90\u8def\u5f84 #\u9759\u6001\u8d44\u6e90\u8def\u5f84
spring.mvc.static-path-pattern=/** spring.mvc.static-path-pattern=/**
##shiro\u914d\u7f6e ##shiro\u914d\u7f6e
# \u767b\u5f55\u5730\u5740 # \u767b\u5f55\u5730\u5740
shiro.user.loginUrl=/login shiro.user.loginUrl=/login
......
...@@ -60,12 +60,6 @@ ...@@ -60,12 +60,6 @@
<artifactId>spring-boot-starter-test</artifactId> <artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope> <scope>test</scope>
</dependency> </dependency>
<!-- spring-boot-devtools -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-devtools</artifactId>
<scope>test</scope>
</dependency>
<dependency> <dependency>
<groupId>org.mybatis.spring.boot</groupId> <groupId>org.mybatis.spring.boot</groupId>
<artifactId>mybatis-spring-boot-starter</artifactId> <artifactId>mybatis-spring-boot-starter</artifactId>
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!