Spring mvc annotation @valid, @JsonSerialize, @JsonView, etc. __js

Source: Internet
Author: User


@Valid

Spring MVC is a hibernate-validate, the first step must be the guide package, it ignores

Validation annotations that can be used

@NotNull  value cannot be empty
@Null     value must be empty
@Pattern (regex=) string must match regular expression
@Size (min=,max=)  The number of elements in the collection must be between Min and Max
@CreditNumber (ignorenondigitcharacters=) string must be a credit card number (verified by US standards)
@Email    The string must be an email address
@Length (min=,max=) Check the length of the string
@NotBlank   string must have a character
@Range (min=,max=) number must be greater than min, Less than
or equal to Max @SafeHtml   string is secure HTML
@URL   string is a valid URL
@AssertFalse   value must be false
@    the Asserttrue value must be true
@DecimalMax (value,inclusive=) value must be less than or equal to (inclusive=true)/less than (Inclusive=false) Value that can be annotated on a property of a string type
@DecimalMin (value,inclusive=) value must be greater than or equal to (inclusive=true)/greater Than (Inclusive=false) Value that can be annotated on a property of a string type
@Digits (integer=,fraction=)  number format Check, integer to specify the maximum length of the integer part, Fraction Specify the maximum length of a fractional part @Future value must be a  future log
@Past value must be  a past date
@Max (value=) value must be less than or equal to the value specified. Cannot gaze @Min (value=) value on a property of a string type
must be greater than or equal to the value specified, and cannot be watched on a property of a string type

a simple checksum

Use, first define the entity

public class User {

    private String ID;

    Private String username;

    @NotBlank (message = "Password cannot be null")
    private String password;

    @Past (message = "Birthday must be Past time")
    private Date birthday;

  Getter and Setter
}

Control Layer Implementation:
@PutMapping ("/{id:\\d+}") Public
User Update (@Valid @RequestBody user user, Bindingresult errors) {

    if ( Errors.haserrors ()) {
        //errors.getallerrors (). Stream (). ForEach (Error-> System.out.println ( Error.getdefaultmessage ()));
        Errors.getallerrors (). Stream (). ForEach (Error->{
            fielderror fielderror = (fielderror) error;
            System.out.println (Fielderror.getfield () + ":" +fielderror.getdefaultmessage ());
        });

    System.out.println (User.getid ());
    System.out.println (User.getusername ());
    System.out.println (User.getpassword ());
    System.out.println (User.getbirthday ());

    User.setid ("1");
    return user;
}

OK, the error message will print out and you can do your own logical processing
Custom Validator Checksum
/**
 * Custom Validator
 * Created by Xingyuchao on 2017/12/2.
 */
@Target ({elementtype.method, Elementtype.field})
@Retention (retentionpolicy.runtime)
@Constraint (Validatedby = myconstraintvalidator.class)
Public @interface Myconstraint {
	
	String message ();

	Class<?>[] Groups () default {};

	class<? Extends payload>[] Payload () default {};
	
	String field () Default "";
}
The above three attributes are required.
To complete the validation logic, it is necessary to note that the class that implements the Constraintvalidator is already in the spring container, so you can use the injection other class
public class Myconstraintvalidator implements Constraintvalidator<myconstraint, object> {

	@Autowired
	Private HelloService HelloService;
	
	@Override public
	Void Initialize (Myconstraint constraintannotation) {
		System.out.println (' My validator init ') );
	}

	@Override Public
	Boolean isValid (Object value, Constraintvalidatorcontext context) {
		helloservice.greeting (" Tom ");
		System.out.println (value);
		return false;  Returns True checksum passes, false checksum does not pass
	}

}

Use
Private String ID;

@MyConstraint (message = "This is a validation test")
 Private String username;

@NotBlank (message = "Password cannot be null")
private String password;

@Past (message = "Birthday must be Past time")
private Date birthday;

@JsonView

@JsonView can filter the field properties of the serialized object, allowing you to have the selected serialized object.
Use steps:

Using interfaces to declare multiple views specify views on a Get method of a Value object specify a view on the Controller method

public class User {public

    interface Usersimpleview {};
    Public interface Userdetailview extends Usersimpleview {};

    Private String username;

    private String password;

    @JsonView (usersimpleview.class) public
    String GetUserName () {return  username;}

    public void Setusername (String username) {this.username = username;}

    @JsonView (userdetailview.class) public
    String GetPassword () {return password;}

    public void SetPassword (String password) {this.password = password;}
}


@RestController @RequestMapping ("/user") public class Usercontroller {@GetMapping @JsonView (user.usersimpleview.  Class) Public list<user> query (userquerycondition condition, @PageableDefault (page = 2, size =, sort = "username", direction= Sort.Direction.DESC) pageable pageable) {System.out.println (reflectio   Ntostringbuilder.tostring (condition, tostringstyle.multi_line_style));
        Print ToString System.out.println (pageable.getpagesize ());
        System.out.println (Pageable.getpagenumber ());


        System.out.println (Pageable.getsort ());
        list<user> userlist = new arraylist<> ();
        Userlist.add (New User ());
        Userlist.add (New User ());
        Userlist.add (New User ());
    return userlist; //{id:\\d+} represents only a digital @GetMapping ("/{id:\\d+}") @JsonView (User.UserDetailView.class) public User Getinf O (@PathVariable String ID) {//throw new RuntimeException ("User not ExisT ");
        SYSTEM.OUT.PRINTLN ("Access to GetInfo service");
        User user = new user ();
        User.setusername ("Tom");
    return user; }
}


@JsonSerialize
This annotation is used on property or getter methods to embed our custom code when serializing, such as by limiting the two-bit decimal point to the back of a double.

Because the timestamp in the Java date period is MS, I now need to convert MS to S, which is divided by 1k
public class Date2longserializer extends jsonserializer<date> {

    @Override public
    void Serialize (Date Date, Jsongenerator jsongenerator, Serializerprovider serializerprovider) throws IOException, Jsonprocessingexception {
        Jsongenerator.writenumber (Date.gettime ()/1000);
    }
}


Use:
Private String ID;

@MyConstraint (message = "This is a checksum test")
private String username;

@NotBlank (message = "Password cannot be null")
private String password;

@JsonSerialize (using = Date2longserializer.class)
@Past (message = "Birthday must be Past time")
private Date birthday;

This completes the time stamp 13-bit to 10-bit conversion
@JsonIgnore, @JsonIgnoreProperties@JsonIgnoreProperties: This annotation is a class annotation that ignores some of the properties in the Java bean when the JSON is serialized, and is affected by serialization and deserialization. @JsonIgnore: This annotation is used on properties or methods (preferably on attributes), as in the @jsonignoreproperties above.
are used for JSON conversions that ignore empty fields, or other ways to control
The first kind of local control:
The second type: Global control, I use the Springboot
There are other JSON related annotations, do not enumerate, you can refer to: https://www.cnblogs.com/guijl/p/3855329.html



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.