SPRINGMVC data Validation--authentication instance of registered user format

Source: Internet
Author: User

Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

Server-side data validation is very important for a Web application, While spring supports the JSR-303 specification from 3.0, it defines some standard validation constraints and also provides an extensible customization to meet different development needs, with elephants based on SSM3 and examples to illustrate how to use spring MVC implements validator validation in the form of custom constraint annotations.


VALIDATION-API is the standard interface of the JSR-303 specification, Hibernate-validator is an implementation of this interface, and Hibernate-validator implementation will use SLF4J, so you need to add the two jar package. With this, we can implement the custom annotation constraint extension on this basis.


First, create a Web project in eclipse

The entire project directory is as follows:


Importing packages

2. Create User Class

and annotate annotations

Where @length, @Email is the hibernate-validator in the data validation annotations, you can also use javax.validation annotations, such as @notnull

Package Com.mucfc.model;import Org.hibernate.validator.constraints.email;import Org.hibernate.validator.constraints.length;import org.hibernate.validator.constraints.notempty;/** * User format validation class *@ Author Linbingwen *@2015 May 17 15:45:27 */public class User {@NotEmpty (message= "User name cannot be empty") Private String username;@ Notempty (message= "Password cannot be empty") @Length (min=6,max=16,message= "password length is not correct, must be between 6-16") private String UserPassword; @NotEmpty ( Message= "Mailbox cannot be empty")        @Email (message= "mailbox format is incorrect") private string Useremail;public string GetUserName () {return userName ;} public void Setusername (String userName) {this.username = UserName;} Public String Getuserpassword () {return userpassword;} public void SetUserPassword (String userpassword) {This.userpassword = UserPassword;} Public String getUserEmail () {return useremail;} public void Setuseremail (String useremail) {this.useremail = UserEmail;}}

3. Configuring the Controller in Web. xml

<?xml version= "1.0" encoding= "UTF-8"? ><web-app xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns= "Http://java.sun.com/xml/ns/javaee" xmlns:web= "http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi: schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id= "Webapp_ ID "version=" 3.0 "><!--SPRINGMVC Front-end controller--><servlet><servlet-name>mydispatcher</ Servlet-name><servlet-class>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!--load configuration file path--><init-param><param-name>contextconfiglocation</param-name>< param-value>/web-inf/spring-servlet.xml</param-value></init-param><!--when to start A value greater than 0 indicates that the servlet is initialized when the container starts, the lower the value the higher the priority--><load-on-startup>1</load-on-startup></servlet><!-- Spring MVC configuration file End--><!--springmvc intercept Settings--><servlet-mapping><servlet-name>mydispatcher</ servlet-name><!--intercept all requests by SPRINGMVC--><url-pattern>/</url-pattern></servlet-mapping><!--Springmvc Intercept set end--><!-- Solve Chinese garbled problem--><filter><filter-name>characterencodingfilter</filter-name><filter-class> Org.springframework.web.filter.characterencodingfilter</filter-class><init-param><param-name >encoding</param-name><param-value>UTF-8</param-value></init-param></filter> <filter-mapping><filter-name>characterencodingfilter</filter-name><url-pattern>/*</ Url-pattern></filter-mapping> </web-app>

4. Controller configuration file

Add the configuration in the Spring MVC configuration file:

Add the following MVC note-driven configuration, and everything becomes "automated"

<Mvc:annotation-driven />

<beans xmlns= "Http://www.springframework.org/schema/beans" xmlns:context= "http://www.springframework.org/ Schema/context "xmlns:util=" Http://www.springframework.org/schema/util "xmlns:xsi=" http://www.w3.org/2001/ Xmlschema-instance "xmlns:p=" http://www.springframework.org/schema/p "xmlns:mvc=" http://www.springframework.org/ Schema/mvc "xsi:schemalocation=" Http://www.springframework.org/schema/util Http://www.springframework.org/schema /util/spring-util-3.2.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ Spring-mvc-3.2.xsd Http://www.springframework.org/schema/beans http://www.springframework.org/schema/ Beans/spring-beans-3.2.xsd Http://www.springframework.org/schema/context http://www.springframework.org /schema/context/spring-context-3.2.xsd "> <mvc:annotation-driven/> <!--Convert a class labeled @controller annotation to a bean-- ><context:component-scan base-package= "COM.MUCFC"/><!--The resolution of the name of the model view,That is, add the prefix--><beanclass= "org.springframework.web.servlet.view.InternalResourceViewResolver" p:prefix= "in the Model view name /web-inf/views/"p:suffix=". JSP "/></beans>

5. The class of the note controller

First, add the @valid annotation to the bean that needs to be validated, and tell the SPRINGMVC framework that the bean needs to be validated, and also add @modelattribute annotations to the bean that needs validation, exposing the bean to the view, and specify the name, this has two functions, the first is to display a checksum error needs to use this name, the second is to return the original page, the previous input of all the values to be displayed;

Next, each bean that needs to be validated is immediately followed by a BINDINGRESULT,SPRINGMVC framework that officer the results in it, and the HasErrors method can determine if there is a checksum error;

Finally, when returning to the original page, the SPRINGMVC framework also saves all the checksum error information in the context for a validation error on the page, and Spring provides a set of JSP custom tags.


Package Com.mucfc.controller;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import Javax.validation.valid;import Org.springframework.stereotype.controller;import Org.springframework.ui.model;import Org.springframework.validation.bindingresult;import Org.springframework.web.bind.annotation.ModelAttribute; Import Org.springframework.web.bind.annotation.requestmapping;import Org.springframework.web.bind.annotation.requestmethod;import Com.mucfc.model.User; @Controllerpublic class usercontrollers {@RequestMapping (value = "/register", method = {requestmethod.post}) public String Registercheck (Model Model, @Valid @ModelAttribute ("user") user User,bindingresult result) {if (Result.haserrors ()) return "register"; else{    Model.addattribute ("UserName", User.getusername ()); return "Forward:/success";}} @ModelAttribute ("user") public user GetUser () {User user=new user (); return user;} @RequestMapping (value = "/register", method = {Requestmethod.get}) public StringRegister () {return "register";} @RequestMapping (value = "/success") Public String Success (HttpServletRequest request,httpservletresponse response) { String str= (String) request.getattribute ("UserName"); if (str==null| | Str.equals ("")) {return "Redirect:/register";} Return "Success";}}

6. Web-inf New Folder

(1) The first is user data input register.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" Utf-8 "%><%@ taglib prefix=" form "uri=" Http://www.springframework.org/tags/form " %><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%&GT;&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >This uses the form of the Springmvc form, automatically associate the input and user annotation format class, when you enter the correct format, will not jump to other pages, otherwise this page will be reported errors

Display the checksum error message on the JSP page:

The page header needs to be imported into spring's Custom tag library:

<%@ taglib prefix="form" uri="Http://www.springframework.org/tags/form"%> 

You need to show all checksum errors at once:

(the value of CommandName is the value specified in the @modelattribute annotation)

<form:formcommandName="Userdetail">    <form:errors  Path="*"cssstyle="color:red"></form:errors>  </form:form>

you need to display a single checksum error after the corresponding input box:

(specifying the specific checksum error by path Specifies that the Userdetail is the value specified in the @modelattribute annotation, followed by a checksum error specifying which property in the display bean is displayed)

<input type="text" name= "userName" value="${ Userdetail.username} " ><form:errors path="Userdetail.username" cssstyle="COLOR: Red "></form:errors><input type="text" name="Email" value= "${userdetail.email}"><form:errors path="Userdetail.email" cssstyle="color:red" ></form:errors>

(2) After the user registration information is correctly submitted success.jsp

<%@ page language= "java" contenttype= "text/html; Charset=utf-8 "pageencoding=" UTF-8 "%><%@ taglib prefix=" form "uri=" Http://www.springframework.org/tags/form " %><%string path = Request.getcontextpath (); String basepath = request.getscheme () + "://" + request.getservername () + ":" + request.getserverport () + path + "/";%>&L t;! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" >

7. Look at the results after running

In the browser, enter: Http://localhost:8080/SpringMVCLearningChapter3/register

Go to registration page

If you do not write a direct submission, the following error will be reported


Error in Password and mailbox format

If the data format is correct, the following is just what happens

Second, note description

Finally, add some explanatory notes

@AssertFalseValidated data type: Boolean,boolean Description: Verify that the element value of the annotation is false@AssertTrueValidated data type: Boolean,boolean Description: Verify that the element value of the annotation is true@NotNullValidated data type: Any type description: Verifies that the element value of the annotation is not null@NullValidated data type: Any type description: Verifies that the element value of the annotation is null@Min (value= value)Validated data types: Bigdecimal,biginteger, byte,short, int, long, and so on any number or charsequence (stored as a numeric) sub-type description : Verifies that the element value of the annotation is greater than or equal to the value specified by @min@Max (value= value)Validated data type: Same as @min requirements Description: Verify that the element value of the annotation is less than or equal to the value specified by @max@DecimalMin (value= value)Validated data type: Same as @min requirements Description: Verify that the element value of the annotation is greater than or equal to the value specified by the @ decimalmin@DecimalMax (value= value)Validated data type: Same as @min requirements: Verify that the element value of the annotation is less than or equal to the value specified by @ Decimalmax@Digits (integer= integer digits, fraction= decimal place)Validated data type: Same as @min requirements Description: Verify the value of the element of the annotation integer and the maximum number of decimal place@Size (min= lower limit, max= upper limit)Validated data types: string, Collection, Map, array, etc. description: Validates the element value of the annotation within a specified interval of min and max (inclusive), such as character length, collection size@PastValidated data type: Java.util.date,java.util.calendar,joda Time Class Library Date type description: Validate annotation element values (date type) earlier than current  @FutureValidated data type: Same as @past requirements: Verify that the element value of the annotation (date type) is later than the current time@NotBlankValidated data type: Charsequence subtype Description: Verifies that the element value of the annotation is not null (NOT NULL, the first space is removed after the length is 0), differs from @notempty, that the @NotBlank is applied only to strings and that the first space of the string is stripped when compared@Length (min= lower limit, max= upper limit)Validated data type: Charsequence subtype Description: Validates element value length of annotations within min and Max intervals@NotEmptyValidated data types: Charsequence subtype, Collection, Map, array Description: Validates that the element value of the annotation is not null and is not NULL (string length is not 0, collection size is not 0)@Range (min= min, max= max)Validated data types: Bigdecimal,biginteger,charsequence, Byte, short, int, long, etc. atomic types and Packing type description: Validates the element value of the annotation between the minimum and maximum values@Email (regexp= regular expression, flag= flag pattern)Validated data type: Charsequence subtype (String) Description: Verify that the element value of the annotation is email, or you can specify a custom email format via REGEXP and flag@Pattern (regexp= regular expression, flag= flag pattern)Validated data type: String, subtype of any charsequence description: Validates that the element value of the annotation matches the specified regular expression@ValidValidated data type: Any non-atomic type description: Specifies the object that is associated with recursive validation, such as an Address object property in a User object, if you want to validate the address object together when validating the user object, add @valid annotations on the Address object to cascade validationNote:Only the most validation constraint annotations provided by Hibernate Validator are listed here, please refer to Hibernate Validator Official documentation for additional validation constraint annotations and custom validation constraint annotation definitions Lin Bingwen Evankaka original works. Reprint please specify the source Http://blog.csdn.net/evankaka

SPRINGMVC data Validation--authentication instance of registered user format

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.