当前位置:网站首页>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 .
边栏推荐
猜你喜欢
Nat address translation
Wireshark分析抓包数据*.cap
[Tawang methodology] Tawang 3W consumption strategy - U & a research method
[paddleseg source code reading] add boundary IOU calculation in paddleseg validation (1) -- val.py file details tips
五种网络IO模型
Three forms of multimedia technology commonly used in enterprise exhibition hall design
How to clean when win11 C disk is full? Win11 method of cleaning C disk
The live broadcast reservation channel is open! Unlock the secret of fast launching of audio and video applications
【Unity Shader】插入Pass实现模型遮挡X光透视效果
NAT地址转换
随机推荐
go语言的字符串类型、常量类型和容器类型
[software test] from the direct employment of the boss of the enterprise version, looking at the resume, there is a reason why you are not covered
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%
debian10系统问题总结
行业案例|数字化经营底座助力寿险行业转型
Kubernetes DevOps CD工具对比选型
sqlite sql 异常 near “with“: syntax error
2022年推荐免费在线接收短信平台(国内、国外)
Yearning-SQL审核平台
Is it safe to open an online futures account now? How many regular futures companies are there in China?
线程池和单例模式以及文件操作
强化学习-学习笔记8 | Q-learning
Thread pool and singleton mode and file operation
Kirk borne's selection of learning resources this week [click the title to download directly]
RISCV64
国内的软件测试会受到偏见吗
coming! Gaussdb (for Cassandra) new features appear
小试牛刀之NunJucks模板引擎
Year SQL audit platform
[demo] circular queue and conditional lock realize the communication between goroutines