当前位置:网站首页>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 .
边栏推荐
- pip相关命令
- Five network IO models
- socket编程之常用api介绍与socket、select、poll、epoll高并发服务器模型代码实现
- 清华、剑桥、UIC联合推出首个中文事实核查数据集:基于证据、涵盖医疗社会等多个领域
- What are the financial products in 2022? What are suitable for beginners?
- Download, installation and development environment construction of "harmonyos" deveco
- What is the general yield of financial products in 2022?
- Differences between rip and OSPF and configuration commands
- “解密”华为机器视觉军团:华为向上,产业向前
- 企业展厅设计中常用的三种多媒体技术形式
猜你喜欢

Summary of debian10 system problems

Charles+drony的APP抓包

低代码助力企业数字化转型会让程序员失业?

【Unity Shader】插入Pass实现模型遮挡X光透视效果

String type, constant type and container type of go language

Kirk Borne的本周学习资源精选【点击标题直接下载】

Five network IO models

Redis

Disk storage chain B-tree and b+ tree

Summary of evaluation indicators and important knowledge points of regression problems
随机推荐
嵌入式C语言程序调试和宏使用的技巧
pip相关命令
Unlike the relatively short-lived industrial chain of consumer Internet, the industrial chain of industrial Internet is quite long
[principle and technology of network attack and Defense] Chapter 1: Introduction
[principle and technology of network attack and Defense] Chapter 7: password attack technology Chapter 8: network monitoring technology
nest.js入门之 database
[network attack and defense principle and technology] Chapter 4: network scanning technology
直播软件搭建,canvas文字加粗
不能忽略的现货白银短线操作小技巧
Disk storage chain B-tree and b+ tree
C语言中匿名的最高境界
Performance test process and plan
【塔望方法论】塔望3W消费战略 - U&A研究法
go语言的字符串类型、常量类型和容器类型
体总:安全有序恢复线下体育赛事,力争做到国内赛事应办尽办
海量数据去重的hash,bitmap与布隆过滤器Bloom Filter
Is it safe to open an online futures account now? How many regular futures companies are there in China?
Redis集群与扩展
Backup Alibaba cloud instance OSS browser
Continuous test (CT) practical experience sharing