当前位置:网站首页>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 .
边栏推荐
- 手撕Nacos源码(先撕客户端源码)
- 备份阿里云实例-oss-browser
- NAT地址转换
- Disk storage chain B-tree and b+ tree
- [principle and technology of network attack and Defense] Chapter 1: Introduction
- DeSci:去中心化科学是Web3.0的新趋势?
- go语言的字符串类型、常量类型和容器类型
- Download, installation and development environment construction of "harmonyos" deveco
- [network attack and defense principle and technology] Chapter 4: network scanning technology
- Industry case | digital operation base helps the transformation of life insurance industry
猜你喜欢
Summary of debian10 system problems
String type, constant type and container type of go language
Will low code help enterprises' digital transformation make programmers unemployed?
CVPR 2022丨学习用于小样本语义分割的非目标知识
A few simple steps to teach you how to see the K-line diagram
Download, installation and development environment construction of "harmonyos" deveco
GSAP animation library
微信网页调试8.0.19换掉X5内核,改用xweb,所以x5调试方式已经不能用了,现在有了解决方案
[paper sharing] where's crypto?
3.关于cookie
随机推荐
AntiSamy:防 XSS 攻击的一种解决方案使用教程
Unlike the relatively short-lived industrial chain of consumer Internet, the industrial chain of industrial Internet is quite long
Nat address translation
现在网上期货开户安全吗?国内有多少家正规的期货公司?
Some key points in the analysis of spot Silver
静态路由配置
标准ACL与扩展ACL
来了!GaussDB(for Cassandra)新特性亮相
[paddleseg source code reading] add boundary IOU calculation in paddleseg validation (1) -- val.py file details tips
A few simple steps to teach you how to see the K-line diagram
直播软件搭建,canvas文字加粗
[论文分享] Where’s Crypto?
How to open an account for wealth securities? Is it safe to open a stock account through the link
现货白银分析中的一些要点
Kirk Borne的本周学习资源精选【点击标题直接下载】
socket编程之常用api介绍与socket、select、poll、epoll高并发服务器模型代码实现
国内的软件测试会受到偏见吗
Tear the Nacos source code by hand (tear the client source code first)
String type, constant type and container type of go language
Live broadcast software construction, canvas Text Bold