当前位置:网站首页>Reuse of data validation framework Apache bval
Reuse of data validation framework Apache bval
2022-07-07 18:54:00 【sp42a】
About Apache BVal, I N Used a long time ago , He also wrote even the only Jianzhong tutorial in the whole network 《 Data validation framework Apache BVal brief introduction 》, I still hold that view :
Apache BVal ( Source code ) Is entity data validation Java Bean Validation Reference implementation of .Apache BVal Provides JSR 303 All built-in... In the specification constraint The implementation of the , Used to deal with Bean The value of the field in the constraint definition 、 Describe and verify . If only JSR The specification of large slag may not be clear , But I did POJO Of Hibernate Validator Annotated friends know what it is ,—— Then why not use mainstream Hibernate Validator Well ? Because the goods are all compressed packages 13mb 了 ( Although there can be documentation 、 The source code includes others ),BVal Only 400 many kb, And I just need the server to verify ,—— Innocent children can't afford to be hurt . My ORM It's also Mybatis Of , Try to be as lightweight as possible .
usage
Maven quote
Add the following two Maven rely on :
<dependency>
<groupId>org.apache.bval</groupId>
<artifactId>bval-jsr</artifactId>
<version>2.0.6</version>
</dependency>
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
<version>2.0.1.Final</version>
</dependency>
2.0 requirement Java 8,Apache CommonUtils Not strong dependence , meanwhile JSR The validation specification is also upgraded to 2.x.
Integrate Spring
Spring Injected inside Provider.
/** * Data validation framework * * @return */
@Bean
LocalValidatorFactoryBean localValidatorFactoryBean() {
LocalValidatorFactoryBean v = new LocalValidatorFactoryBean();
v.setProviderClass(ApacheValidationProvider.class);
return v;
}
Call verification
Manual verification method , Try it first
@Autowired
LocalValidatorFactoryBean v;
public List<DataDict> getDataDict(Long parentId) {
List<DataDict> list = DataDictDao.DataDictDAO.setWhereQuery("parentId", parentId).findList();
Validator validator = v.getValidator();
Set<ConstraintViolation<DataDict>> violations = validator.validate(list.get(0));
System.out.println(violations.size()); // Verification results
System.out.println(list.get(0).getParentId());
if (CollectionUtils.isEmpty(list))
list = new ArrayList<>();
return list;
}
The above code is for a Java Bean:DataDict check ,Bean The fields of can be configured with the following constraints .
public class DataDict implements CommonEntity {
/** * Primary key id, Self increasing */
private Long id;
/** * Father id */
@NotNull
private Long parentId;
/** * type id */
@NotNull
private Long type;
……
}
For more verification notes, see Old language .
Spring MVC Automatic verification
It's simple , adding annotations @Valid
stay Bean Parameter .
/** * newly build * @return */
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid T news, Model model) {
System.out.println(" newly build ");
if (result.hasErrors()) {
LOGGER.info("create error!");
}else{
LOGGER.info("create ok!");
}
news.setService(getService());
try {
getService().create(news);
model.addAttribute("newlyId", news.getId());
} catch (ServiceException e) {
model.addAttribute("errMsg", e.toString());
}
return "common/entity/json_cud";
}
Then talk about how to deal with errors , Or do not handle the default handover Servlet Processing can also . The following is the handler of the custom exception , Turn into JSON return .
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import com.ajaxjs.util.WebHelper;
/** * Back end form 、 Exception capture of data verification * * @author Frank Cheung<[email protected]> * */
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
static final String TPL = " Input field [%s] Failed verification , reason [%s], The input value is [%s], Please check before submitting .";
@ExceptionHandler(value = BindException.class)
public void exceptionHandler(HttpServletRequest req, HttpServletResponse resp, BindException e) {
String msg = "";
List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
for (FieldError err : fieldErrors) {
msg += String.format(TPL, err.getField(), err.getDefaultMessage(), err.getRejectedValue());
// msg += "\\\\n";
}
ResponseResult result = new ResponseResult();
result.setErrorCode("400");
result.setMessage(msg);
WebHelper.outputJson(resp, result.toString());
}
}
This RestResponseEntityExceptionHandler Inject according to normal Spring Component mode is ok , Here's a way :
@Bean
RestResponseEntityExceptionHandler initRestResponseEntityExceptionHandler() {
return new RestResponseEntityExceptionHandler();
}
JSR 303 You can customize the reason for the constraint , This will not output the default English , But it is troublesome to explain one by one .
There's another one getAllErrors, This is not for fields , Estimation is for Verification method .
List<ObjectError> allErrors = e.getAllErrors();
for (ObjectError err : allErrors) {
msg += err.getDefaultMessage();
msg += StringUtils.arrayToDelimitedString(err.getCodes(), ",");
}
Advanced usage
Apache BVal The function of is far more than that , You can refer to foreigners article Learn more advanced usage .
边栏推荐
- 持续测试(CT)实战经验分享
- What is the general yield of financial products in 2022?
- [unity shader] insert pass to realize the X-ray perspective effect of model occlusion
- Performance test process and plan
- String type, constant type and container type of go language
- Will domestic software testing be biased
- Nunjuks template engine
- idea彻底卸载安装及配置笔记
- Improve application security through nonce field of play integrity API
- pip相关命令
猜你喜欢
DataSimba推出微信小程序,DataNuza接受全场景考验? | StartDT Hackathon
如何选择合适的自动化测试工具?
The highest level of anonymity in C language
行业案例|数字化经营底座助力寿险行业转型
Debian10 compile and install MySQL
Discuss | frankly, why is it difficult to implement industrial AR applications?
回归问题的评价指标和重要知识点总结
我感觉被骗了,微信内测 “大小号” 功能,同一手机号可注册两个微信
万字保姆级长文——Linkedin元数据管理平台Datahub离线安装指南
The report of the state of world food security and nutrition was released: the number of hungry people in the world increased to 828million in 2021
随机推荐
[Tawang methodology] Tawang 3W consumption strategy - U & a research method
Tear the Nacos source code by hand (tear the client source code first)
国内的软件测试会受到偏见吗
通过 Play Integrity API 的 nonce 字段提高应用安全性
五种网络IO模型
万字保姆级长文——Linkedin元数据管理平台Datahub离线安装指南
Backup Alibaba cloud instance OSS browser
云景网络科技面试题【杭州多测师】【杭州多测师_王sir】
小程序中实现付款功能
Classification of regression tests
Redis publishing and subscription
AI defeated mankind and designed a better economic mechanism
链式二叉树的基本操作(C语言实现)
Redis集群与扩展
2022年理财产品的一般收益率是多少?
[unity shader] insert pass to realize the X-ray perspective effect of model occlusion
Differences between rip and OSPF and configuration commands
Thread factory in thread pool
我感觉被骗了,微信内测 “大小号” 功能,同一手机号可注册两个微信
DeSci:去中心化科学是Web3.0的新趋势?