当前位置:网站首页>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 .
边栏推荐
- How to clean when win11 C disk is full? Win11 method of cleaning C disk
- GSAP animation library
- 云安全日报220707:思科Expressway系列和网真视频通信服务器发现远程攻击漏洞,需要尽快升级
- socket編程之常用api介紹與socket、select、poll、epoll高並發服務器模型代碼實現
- 不能忽略的现货白银短线操作小技巧
- More than 10000 units were offline within ten days of listing, and the strength of Auchan Z6 products was highly praised
- Yunjing network technology interview question [Hangzhou multi tester] [Hangzhou multi tester _ Wang Sir]
- 行业案例|数字化经营底座助力寿险行业转型
- Reject policy of thread pool
- Differences between rip and OSPF and configuration commands
猜你喜欢

直播预约通道开启!解锁音视频应用快速上线的秘诀

The live broadcast reservation channel is open! Unlock the secret of fast launching of audio and video applications

链式二叉树的基本操作(C语言实现)

Industry case | digital operation base helps the transformation of life insurance industry
![[Tawang methodology] Tawang 3W consumption strategy - U & a research method](/img/63/a8c08ac6ec7d654159e5fc8b4423e4.png)
[Tawang methodology] Tawang 3W consumption strategy - U & a research method

Three forms of multimedia technology commonly used in enterprise exhibition hall design

微信网页调试8.0.19换掉X5内核,改用xweb,所以x5调试方式已经不能用了,现在有了解决方案

行业案例|数字化经营底座助力寿险行业转型

Standard ACL and extended ACL

debian10系统问题总结
随机推荐
磁盘存储链式的B树与B+树
Debian10 compile and install MySQL
Classification of regression tests
企业展厅设计中常用的三种多媒体技术形式
Three forms of multimedia technology commonly used in enterprise exhibition hall design
Antisamy: a solution against XSS attack tutorial
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
gsap动画库
2022-07-04 matlab读取视频帧并保存
Kirk borne's selection of learning resources this week [click the title to download directly]
直播预约通道开启!解锁音视频应用快速上线的秘诀
Calculation of torque target value (ftorque) in servo torque control mode
Yunjing network technology interview question [Hangzhou multi tester] [Hangzhou multi tester _ Wang Sir]
Simple configuration of single arm routing and layer 3 switching
备份阿里云实例-oss-browser
Recommend free online SMS receiving platform in 2022 (domestic and foreign)
Hash, bitmap and bloom filter for mass data De duplication
【Unity Shader】插入Pass实现模型遮挡X光透视效果
CVPR 2022 - learning non target knowledge for semantic segmentation of small samples
单臂路由和三层交换的简单配置