当前位置:网站首页>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 .
边栏推荐
- Simple configuration of single arm routing and layer 3 switching
- 直播预约通道开启!解锁音视频应用快速上线的秘诀
- [principles and technologies of network attack and Defense] Chapter 3: network reconnaissance technology
- 简单几步教你如何看k线图图解
- Redis publishing and subscription
- 2022年理财产品的一般收益率是多少?
- 来了!GaussDB(for Cassandra)新特性亮相
- Discuss | what preparations should be made before ar application is launched?
- DataSimba推出微信小程序,DataNuza接受全场景考验? | StartDT Hackathon
- 【Unity Shader】插入Pass实现模型遮挡X光透视效果
猜你喜欢

【C语言】字符串函数

CVPR 2022 - learning non target knowledge for semantic segmentation of small samples

面试唯品会实习测试岗、抖音实习测试岗【真实投稿】

Year SQL audit platform

Antisamy: a solution against XSS attack tutorial

debian10系统问题总结

Introduction de l'API commune de programmation de socket et mise en œuvre de socket, select, Poll et epoll

简单几步教你如何看k线图图解

企业展厅设计中常用的三种多媒体技术形式

Classification of regression tests
随机推荐
Simple configuration of single arm routing and layer 3 switching
PTA 1102 教超冠军卷
静态路由配置
Yunjing network technology interview question [Hangzhou multi tester] [Hangzhou multi tester _ Wang Sir]
【C语言】字符串函数
Sports Federation: resume offline sports events in a safe and orderly manner, and strive to do everything possible for domestic events
来了!GaussDB(for Cassandra)新特性亮相
现货白银分析中的一些要点
不能忽略的现货白银短线操作小技巧
PHP面试题 foreach($arr as &$value)与foreach($arr as $value)的用法
Interview vipshop internship testing post, Tiktok internship testing post [true submission]
Introduction de l'API commune de programmation de socket et mise en œuvre de socket, select, Poll et epoll
Will low code help enterprises' digital transformation make programmers unemployed?
[paper sharing] where's crypto?
Rules for filling in volunteers for college entrance examination
CVPR 2022 - learning non target knowledge for semantic segmentation of small samples
[principle and technology of network attack and Defense] Chapter 6: Trojan horse
Performance test process and plan
国内的软件测试会受到偏见吗
Nat address translation