Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How to check validator and JSR-303 with Spring

2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

This article will explain in detail how to check validator and JSR-303 in Spring. The editor thinks it is very practical, so I share it with you as a reference. I hope you can get something after reading this article.

Spring check (validator,JSR-303) implementation what is the JSR-303 specification

JSR 303 is a subspecification of Java EE 6, called Bean Validation, and the official reference implementation is hibernate Validator, which has nothing to do with Hibernate ORM. JSR 303 is used to validate the values of fields in Java Bean.

Combine with Spring MVC

Spring-mvc.xml configuration:

Add validation comments to entity classes

Post some of the code here and know how to annotate it:

Import com.lemontree.common.utils.AjaxResult;import com.lemontree.common.utils.StringUtil;import com.lemontree.common.utils.email.EmailUtils;import org.hibernate.validator.constraints.NotEmpty;import java.util.Date;public class User {/ * * This field was generated by MyBatis Generator. * This field corresponds to the database column user.id * @ mbg.generated Thu Mar 16 13:27:38 CST 2017 * / private Integer id; / * This field was generated by MyBatis Generator * This field corresponds to the database column user.user_name * * @ mbg.generated Thu Mar 16 13:27:38 CST 2017 * / @ NotEmpty (message = "user name cannot be empty") private String userName; / * This field was generated by MyBatis Generator. * This field corresponds to the database column user.password * * @ mbg.generated Thu Mar 16 13:27:38 CST 2017 * / @ NotEmpty (message = "password cannot be empty") private String password;} Controller Verification Note added

Follow the @ Validated annotation in front of the entity class, followed by BindingResult:

RequestMapping (value = "/ login.htm", method = RequestMethod.POST) public @ ResponseBody AjaxResult login (@ Validated User user, BindingResult bindingResult, HttpServletRequest request, HttpServletResponse response) {if (bindingResult.hasErrors ()) {List errorses = bindingResult.getFieldErrors () If (CollectionUtils.isNotEmpty (errorses)) {errorses.forEach (item- > {System.out.println (item.getDefaultMessage ());});} Java Hibernate Validator JSR-303 verification

JSR-303 is a subspecification of JAVA EE 6, called Bean Validation,Hibernate Validator, which is a reference implementation of Bean Validation.

The actual use is to add constraints to the field through annotations, and then verify whether the field conforms to the specification, and if not, an exception will be thrown, so as to reduce the code for verifying data, and ensure that the data obtained are in accordance with the specification. It can also be used in conjunction with the Spring framework.

Integration

Official document

Https://mvnrepository.com/artifact/org.hibernate/hibernate-validator

Https://mvnrepository.com/artifact/javax.validation/validation-api

Org.hibernate hibernate-validator 6.0.10.Final org.glassfish javax.el 3.0.1-b09 javax.validation validation-api 2.0.1.Final usage

Check object

Public class JsrTest {@ NotNull (message = "id cannot be empty!") @ Min (value = 1, message = "Id can only be greater than or equal to 1") Integer id; @ NotNull (message = "name cannot be empty!") String name; public void validateParams () {Validator validator = Validation.buildDefaultValidatorFactory () .getValidator (); / / get a validator Set violationSet = validator.validate (this); / / verify the data and get the error set Iterator iterator = violationSet.iterator (); if (iterator.hasNext ()) {String errorMessage = iterator.next (). GetMessage () / / get error message throw new ValidationException (errorMessage);}} public static void main (String args []) {JsrTest req = new JsrTest (); req.id = 1; req.validateParams ();}}

As above, you will add comments to the attribute to declare the constraint

Check attribute

The above is to verify the entire object, or you can verify a field separately:

Validator.validateProperty (object, "name")

Packet check

Public class JsrTest {@ NotNull (message = "id cannot be empty!", groups = {ValidationGroup.class}) @ Min (value = 1, message = "Id can only be 1 or more") Integer id; @ NotNull (message = "name cannot be empty!", groups = {ValidationGroup.class}) String name; @ DecimalMin (value = "1.1") double price; int date Public static void validateParams (JsrTest jsrTest) {Validator validator = Validation.buildDefaultValidatorFactory () .getValidator (); Set violationSet = validator.validate (jsrTest, ValidationGroup.class); Iterator iterator = violationSet.iterator (); if (iterator.hasNext ()) {String errorMessage = iterator.next () .getMessage (); throw new ValidationException (errorMessage) }} public static void main (String args []) {JsrTest req = new JsrTest (); validateParams (req);} public interface ValidationGroup {}}

The calss specified by the packet check must be an interface, and multiple can be specified.

Custom constraint

In general, the annotations provided by the framework can meet the normal verification requirements, but we can also customize annotations to meet our needs.

Our example here is that the annotated string cannot contain the specified character.

@ Target (FIELD) / / meta-annotation, which defines that the annotation uses @ Retention (RUNTIME) / / defines the life cycle of the annotation on the field @ Constraint (validatedBy = CustomValidator.class) / / indicates that the validator @ Documented / / indicates that the annotation will be added to JavaDoc public @ interface CustomConstraints {String message () default "default exception message"; Class [] groups () default {}; Class

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report