Springmvc learning notes (14)-springmvc Verification

Source: Internet
Author: User

Springmvc learning notes (14)-springmvc Verification
Springmvc learning notes (14)-springmvc Verification

This article describes springmvc verification, including environment preparation, validator configuration, pojo sheets, verification rules, capture and display inspection error information, and simple group verification examples.

Verification Comprehension

Projects usually use front-end verification, such as js verification on pages. We recommend that you verify the security requirements on the server.

Server Verification:

Control Layer conroller: verifies the validity of the parameters of the page request. In the conroller check on the server control layer, there is no distinction between client types (browsers, mobile clients, remote calls) service layer (more used): Mainly checks key business parameters, only parameters used in the service interface are allowed. Persistent layer dao: Generally, it is not verified. Springmvc verification requirements

Springmvc uses the validation framework of hibernate (which has nothing to do with hibernate ).

Verification ideas:

The request parameters are submitted on the page. The request is sent to the controller method and verified using validation. If an error occurs during verification, the error message is displayed on the page.

Specific requirements:

Modify the product and add verification (check the product name length and non-empty verification on the production date). If an error occurs during verification, the product modification page displays the error message.

Environment preparation

We need three jar packages:

Hibernate-validator.jar jboss-logging.jar validation-api.jar

Here we add maven dependency


  
      
   
    
Org. hibernate
   Hibernate-validator    
   
    
5.2.4.Final
   
  

View maven dependency tree

[INFO] \- org.hibernate:hibernate-validator:jar:5.2.4.Final:compile[INFO]    +- javax.validation:validation-api:jar:1.1.0.Final:compile[INFO]    +- org.jboss.logging:jboss-logging:jar:3.2.1.Final:compile[INFO]    \- com.fasterxml:classmate:jar:1.1.0:compile

We can see that the other two jar packageshibernate-validatorTherefore, you do not need to add any more.

Configure the validator to add it to springmvc. xml

  
      
       
       
        
    
   
  
  
      
       
           
                
     
      
Classpath: CustomValidationMessages
             
        
       
       
       
        
    
   
  
The validator is injected into the processor adapter.

  
In CustomValidationMessages. properties, configure the verification error message:
# Add verification error message items. name. length. error = enter the product name from 1 to 30 characters items. createtime. isNUll = enter the product production date
Add validation rules in pojo

Add verification rules in ItemsCustom. java:

Public class Items {private Integer id; // check that the name is between 1 and 30 characters. // message indicates the information displayed when an error occurs during verification. // groups: the group to which the verification belongs, groups can define multiple groups @ Size (min = 1, max = 30, message = "{items. name. length. error} ") private String name; private Float price; private String pic; // non-null check @ NotNull (message =" {items. createtime. isNUll} ") private Date createtime;
Capture and display verification error messages
@RequestMapping("/editItemsSubmit")public String editItemsSubmit(        Model model,        HttpServletRequest request,        Integer id,        @Validated ItemsCustom itemsCustom,        BindingResult bindingResult)throws Exception {
Upload the error message to the page in the controller.
// Obtain the verification error message if (bindingResult. hasErrors () {// output error message List
  
   
AllErrors = bindingResult. getAllErrors (); for (ObjectError objectError: allErrors) {// output error message System. out. println (objectError. getdefamessage message ();} // upload the error message to the model on the page. addAttribute ("allErrors", allErrors); // you can directly use the model to display the submitted pojo back to the page model. addattrim ("items", itemsCustom); // return "items/editItems ";}
  
Error message displayed on the page:

  
      
   
    
$ {Error. defaultMessage}
   
  
Group verification requirements:
The validation rules are defined in pojo, and pojo is shared by multiple controllers. When different controller methods verify the same pojo, each controller method requires a different verification solution:
Defines Multiple Validation groups (in fact, a java Interface), and defines the rules in the group. Each controller method uses different validation groups.

1. Check group

Public interface ValidGroup1 {// you do not need to define any method in the interface, but only group different validation rules. // This group only verifies the length of product names}

2. Add a group to the validation rule.

// Check that the name is between 1 and 30 characters. // message indicates the information displayed when an error occurs. // groups: the group to which the verification belongs, groups can define multiple groups @ Size (min = 1, max = 30, message = "{items. name. length. error} ", groups = {ValidGroup1.class}) private String name;

3. Use the verification of the specified group in the controller Method

// Value = {ValidGroup1.class} specifies the verification @ RequestMapping ("/editItemsSubmit") public String editItemsSubmit (Model model, HttpServletRequest request, Integer id, @ Validated (value = ValidGroup1.class) ItemsCustom itemsCustom, BindingResult bindingResult) throws Exception {

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.