当前位置:网站首页>Cadre de validation des données Apache bval réutilisé
Cadre de validation des données Apache bval réutilisé
2022-07-07 18:54:00 【Sp42a】
À propos de Apache BVal,- moi. N Utilisé il y a longtemps,J'ai même écrit le seul tutoriel en ligne《Cadre de validation des données Apache BVal Introduction》,Je suis toujours d'accord:
Apache BVal (Code source)Est la validation des données de l'entité Java Bean Validation Mise en œuvre de référence pour.Apache BVal Offre JSR 303 Toutes les spécifications intégrées constraint Réalisation,Pour Bean La valeur du champ dans la définition de contrainte、Description et vérification.Si seulement JSR La spécification Big Slag n'est peut - être pas claire,Mais oui. POJO De Hibernate Validator Un ami annoté sait ce que c'est,——Alors pourquoi ne pas utiliser le courant dominant Hibernate Validator Et alors??Parce que cette cargaison est un paquet compact qui a été 13mb C'est(Bien qu'il puisse y avoir de la documentation、Code source autre),BVal C'est tout. 400 Beaucoup. kb,Et j'ai juste besoin de l'authentification côté serveur,——Un enfant naïf ne peut pas se permettre de se blesser.À moi. ORM C'est aussi Mybatis De,Pour être aussi léger que possible.

Utilisation
Maven Références
Ajouter les deux éléments suivants Maven Dépendance:
<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 Exigences Java 8,Apache CommonUtils Ce n'est pas une forte dépendance ,En même temps JSR Les spécifications de validation ont également été mises à jour pour 2.x.
Intégration Spring
Spring Injection à l’intérieur Provider.
/** * Cadre de validation des données * * @return */
@Bean
LocalValidatorFactoryBean localValidatorFactoryBean() {
LocalValidatorFactoryBean v = new LocalValidatorFactoryBean();
v.setProviderClass(ApacheValidationProvider.class);
return v;
}
Vérification des appels
Méthode de vérification manuelle ,Essaie d'abord.
@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()); // Résultats de la vérification
System.out.println(list.get(0).getParentId());
if (CollectionUtils.isEmpty(list))
list = new ArrayList<>();
return list;
}
Le code ci - dessus est pour un Java Bean:DataDict Effectuer la vérification,Bean Les champs pour peuvent être configurés avec les contraintes suivantes .
public class DataDict implements CommonEntity {
/** * Clé primaire id,Auto - augmentation */
private Long id;
/** * Père id */
@NotNull
private Long parentId;
/** * Type id */
@NotNull
private Long type;
……
}
Pour plus de commentaires sur la vérification, voir Ancien article.
Spring MVC Vérification automatique
C'est simple.,Ajouter un commentaire @Valid In Bean Paramètre.
/** * Nouveau * @return */
@RequestMapping(method = RequestMethod.POST)
public String create(@Valid T news, Model model) {
System.out.println("Nouveau");
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";
}
Ensuite, comment gérer les erreurs , Ou ne pas traiter la livraison par défaut Servlet Le traitement peut aussi. Voici le processeur d'exception personnalisé ,Convertir en JSON Retour.
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;
/** * Formulaire d'arrière - plan 、 Saisie d'exception pour la vérification des données * * @author Frank Cheung<[email protected]> * */
@ControllerAdvice
public class RestResponseEntityExceptionHandler {
static final String TPL = "Champ d'entrée [%s] Échec de la vérification,Raisons [%s],La valeur saisie est [%s], Veuillez vérifier avant de soumettre .";
@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());
}
}
C'est RestResponseEntityExceptionHandler Injection normale Spring Le mode composant est suffisant , Voici une façon de :
@Bean
RestResponseEntityExceptionHandler initRestResponseEntityExceptionHandler() {
return new RestResponseEntityExceptionHandler();
}
JSR 303 Pourquoi les contraintes peuvent - elles être personnalisées , De cette façon, l'anglais par défaut ne sera pas imprimé , Mais c'est plus compliqué de le dire un par un .
Il y a un autre getAllErrors, Ce n'est pas pour le champ ,Ça doit être for Méthode d'étalonnage .
List<ObjectError> allErrors = e.getAllErrors();
for (ObjectError err : allErrors) {
msg += err.getDefaultMessage();
msg += StringUtils.arrayToDelimitedString(err.getCodes(), ",");
}
Utilisation avancée
Apache BVal Il y a plus que ça , Vous pouvez vous référer à Article (s) En savoir plus sur l'utilisation avancée .
边栏推荐
- Five network IO models
- 低代码助力企业数字化转型会让程序员失业?
- DeSci:去中心化科学是Web3.0的新趋势?
- Summary of evaluation indicators and important knowledge points of regression problems
- Charles+Postern的APP抓包
- Interview vipshop internship testing post, Tiktok internship testing post [true submission]
- Learn to make dynamic line chart in 3 minutes!
- PIP related commands
- 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%
- Yearning-SQL审核平台
猜你喜欢
随机推荐
嵌入式C语言程序调试和宏使用的技巧
Is it safe to open an online futures account now? How many regular futures companies are there in China?
你真的理解粘包与半包吗?3分钟搞懂它
Datasimba launched wechat applet, and datanuza accepted the test of the whole scene| StartDT Hackathon
idea彻底卸载安装及配置笔记
线程池和单例模式以及文件操作
[principle and technology of network attack and Defense] Chapter 1: Introduction
Some key points in the analysis of spot Silver
[论文分享] Where’s Crypto?
回归问题的评价指标和重要知识点总结
socket编程之常用api介绍与socket、select、poll、epoll高并发服务器模型代码实现
体总:安全有序恢复线下体育赛事,力争做到国内赛事应办尽办
PHP面试题 foreach($arr as &$value)与foreach($arr as $value)的用法
持续测试(CT)实战经验分享
[principle and technology of network attack and Defense] Chapter 7: password attack technology Chapter 8: network monitoring technology
Tear the Nacos source code by hand (tear the client source code first)
CVPR 2022丨学习用于小样本语义分割的非目标知识
直播预约通道开启!解锁音视频应用快速上线的秘诀
[PaddleSeg源码阅读] PaddleSeg Validation 中添加 Boundary IoU的计算(1)——val.py文件细节提示
Yearning-SQL审核平台









