当前位置:网站首页>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 .
边栏推荐
- 体总:安全有序恢复线下体育赛事,力争做到国内赛事应办尽办
- 高考填志愿规则
- Save the memory of the model! Meta & UC Berkeley proposed memvit. The modeling time support is 30 times longer than the existing model, and the calculation amount is only increased by 4.5%
- 直播预约通道开启!解锁音视频应用快速上线的秘诀
- Usage of PHP interview questions foreach ($arr as $value) and foreach ($arr as $value)
- 静态路由配置
- PTA 1102 教超冠军卷
- [unity shader] insert pass to realize the X-ray perspective effect of model occlusion
- 2022年推荐免费在线接收短信平台(国内、国外)
- 【剑指 Offer】59 - I. 滑动窗口的最大值
猜你喜欢
The highest level of anonymity in C language
A few simple steps to teach you how to see the K-line diagram
低代码助力企业数字化转型会让程序员失业?
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
Kirk borne's selection of learning resources this week [click the title to download directly]
Kirk Borne的本周学习资源精选【点击标题直接下载】
【软件测试】从企业版BOSS直聘,看求职简历,你没被面上是有原因的
[principles and technologies of network attack and Defense] Chapter 5: denial of service attack
Kubernetes DevOps CD工具对比选型
Some key points in the analysis of spot Silver
随机推荐
能同时做三个分割任务的模型,性能和效率优于MaskFormer!Meta&UIUC提出通用分割模型,性能优于任务特定模型!开源!...
Sports Federation: resume offline sports events in a safe and orderly manner, and strive to do everything possible for domestic events
DeSci:去中心化科学是Web3.0的新趋势?
Wireshark分析抓包数据*.cap
【软件测试】从企业版BOSS直聘,看求职简历,你没被面上是有原因的
AntiSamy:防 XSS 攻击的一种解决方案使用教程
A few simple steps to teach you how to see the K-line diagram
Kirk borne's selection of learning resources this week [click the title to download directly]
如何选择合适的自动化测试工具?
SQLite SQL exception near "with": syntax error
Tsinghua, Cambridge and UIC jointly launched the first Chinese fact verification data set: evidence-based, covering many fields such as medical society
【C语言】字符串函数
[principle and technology of network attack and Defense] Chapter 1: Introduction
gsap动画库
线程池和单例模式以及文件操作
Tear the Nacos source code by hand (tear the client source code first)
RIP和OSPF的区别和配置命令
unity2d的Rigidbody2D的MovePosition函数移动时人物或屏幕抖动问题解决
Classification of regression tests
强化学习-学习笔记8 | Q-learning