当前位置:网站首页>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 .
边栏推荐
- Datasimba launched wechat applet, and datanuza accepted the test of the whole scene| StartDT Hackathon
- Afghan interim government security forces launched military operations against a hideout of the extremist organization "Islamic state"
- 『HarmonyOS』DevEco的下载安装与开发环境搭建
- 备份阿里云实例-oss-browser
- DataSimba推出微信小程序,DataNuza接受全场景考验? | StartDT Hackathon
- 【塔望方法论】塔望3W消费战略 - U&A研究法
- socket编程之常用api介绍与socket、select、poll、epoll高并发服务器模型代码实现
- 万字保姆级长文——Linkedin元数据管理平台Datahub离线安装指南
- [Tawang methodology] Tawang 3W consumption strategy - U & a research method
- Improve application security through nonce field of play integrity API
猜你喜欢
[PaddleSeg源码阅读] PaddleSeg Validation 中添加 Boundary IoU的计算(1)——val.py文件细节提示
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
行业案例|数字化经营底座助力寿险行业转型
Yearning-SQL审核平台
Wireshark analyzes packet capture data * cap
Antisamy: a solution against XSS attack tutorial
GSAP animation library
Using stored procedures, timers, triggers to solve data analysis problems
二叉树的基本概念和性质
链式二叉树的基本操作(C语言实现)
随机推荐
Five network IO models
String type, constant type and container type of go language
NAT地址转换
Static routing configuration
pip相关命令
磁盘存储链式的B树与B+树
sqlite sql 异常 near “with“: syntax error
Differences between rip and OSPF and configuration commands
[principle and technology of network attack and Defense] Chapter 1: Introduction
Charles+drony的APP抓包
nest. Database for getting started with JS
Debian10 compile and install MySQL
【软件测试】从企业版BOSS直聘,看求职简历,你没被面上是有原因的
万字保姆级长文——Linkedin元数据管理平台Datahub离线安装指南
“解密”华为机器视觉军团:华为向上,产业向前
[software test] from the direct employment of the boss of the enterprise version, looking at the resume, there is a reason why you are not covered
[paper sharing] where's crypto?
Reject policy of thread pool
coming! Gaussdb (for Cassandra) new features appear
idea彻底卸载安装及配置笔记