Spring MVC Data Validation--validate encoding method

Source: Internet
Author: User

1. Import Jar Package
    • Validation-api-1.0.0.ga.jar This is a more critical jar package that is primarily used to parse annotation @valid.
    • Hibernate-validator-4.3.2.final.jar can download the latest, this package is particularly important in the annotation encoding.
    • The other is some log packages (not necessarily all need): Jboss-logging-3.1.3.ga.jar, Slf4j-log4j12-1.6.1.jar
2. Structure diagram of Web project
    • The main structure of the project, not clear the environment of the Web project can learn for yourself, recommend to MU class online looking for video to see

    • LIB Library jar package, paste out for easy control, there are 3 main classes: Spring Core library, validate need to load libraries, other libraries (there are several JSP tag libraries, not the focus)

3. Project configuration
    • Web. XML configuration
      Minimum configuration for Spring MVC project
<?xml version="1.0"encoding="UTF-8"? ><web-app xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://xmlns.jcp.org/xml/ns/javaee"xsi:schemalocation="Http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"version="3.1"> <display-name>SpringMVC</display-name> <welcome-file-list> <welcome-file>jsp/ hello.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>hello</    Servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> & Lt;url-pattern>/</url-pattern> </servlet-mapping></web-app>
    • Hello-servlet.xml Configuration
      by automatically loading
<?xml version="1.0"encoding="UTF-8"? ><beans xmlns="Http://www.springframework.org/schema/beans"xmlns:p="http://www.springframework.org/schema/p"Xmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"Xmlns:mvc="Http://www.springframework.org/schema/mvc"xmlns:aop="HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP"xmlns:context="Http://www.springframework.org/schema/context"xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-4.0.xsd Http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/ Spring-mvc-4.0.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-4.0.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context.xsd "> <context:component-scan base- Package="Controller"> </context:component-scan> <bean class="Org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"/> <bean class="Org.springframework.web.servlet.view.InternalResourceViewResolver"p:prefix="/web-inf/jsp/"p:suffix=". JSP"> <!--<property name="Viewclass"Value="Org.springframework.web.servlet.view.JstlView"></property>-</bean> <!--data authentication encoding configuration--<mvc:annotation-driven validator="Accountvalidator"/> <bean id="Accountvalidator"class="DAO. Accountvalidator "></bean></beans>
4. Add source code under SRC
    • Controller Package
      The Registercontroller class has two main methods, one for get and the other for post. Where data validation is placed in the Registerif () method. The validation is through the first two parameters, the first parameter is a javabean holds the information of the registered user, and the second parameter is used for data validation submitted by the JavaBean object.
Package Controller;Import Javax. Validation. Valid;import org. Springframework. Stereotype. Controller;import org. Springframework. UI. Model;import org. Springframework. Validation. Bindingresult;import org. Springframework. Validation. DataBinder;import org. Springframework. Web. Bind. Annotation. Initbinder;import org. Springframework. Web. Bind. Annotation. Modelattribute;import org. Springframework. Web. Bind. Annotation. Requestmapping;import org. Springframework. Web. Bind. Annotation. Requestmethod;Import DAO. Account;Import DAO. Accountvalidator;@Controller @requestmapping ("/register") public class Registercontroller {@RequestMapping (method=requestmethod. GET) Public String Register (model model) {if (!model. Containsattribute("Account") {model. AddAttribute("Account", new account ());} return"Register";} @InitBinder public void Initbinder (DataBinder binder) {Binder. Setvalidator(New Accountvalidator ());} @RequestMapping (Method=requestmethod. POST) Public String Registerif (@Valid @ModelAttribute ("Account") account Account,bindingresult Result,model Model) {System. out. println("User name:"+account. GetUserName());if (Result. HasErrors()) {System. out. println("Register faliure.");Model. AddAttribute("Message","Registration Failed");}else {model. AddAttribute("Message","Registered successfully");} return"Register";}}
    • DAO Package
      (1), JavaBean type account, for storing registered user information
 PackageDaoImportJavax.validation.constraints.Pattern;ImportJavax.validation.constraints.Size; Public  class  account {    PrivateString username;PrivateString password; Public  Account() {//TODO auto-generated constructor stub} Public  Account(string username, string password) {Super(); This. Username = Username; This. Password = password; } PublicStringGetUserName() {returnUsername } Public void Setusername(String username) { This. Username = Username; } PublicStringGetPassword() {returnPassword } Public void SetPassword(String password) { This. Password = password; }}

(2), Accountvalidator for checking account input user information
This is the main class of encoding validation data, by loading the class in Hello-servlet.xml, the introduction point is at the @valid annotation.

 PackageBA);ImportOrg.springframework.validation.Errors;ImportOrg.springframework.validation.ValidationUtils;ImportOrg.springframework.validation.Validator; Public  class accountvalidator implements Validator {    @Override     Public Boolean supports(class<?> arg0) {//TODO auto-generated method stub        returnAccount.class.equals (arg0); }@Override    //This method is used to verify the data     Public void Validate(Object obj, Errors erros) {//TODO auto-generated method stubValidationutils.rejectifempty (Erros,"username",NULL,"User name cannot be empty."); Validationutils.rejectifempty (Erros,"Password",NULL,"The password cannot be empty."); Account Account = (account) obj;if(Account.getusername (). Length () <3|| Account.getusername (). Length () > -) {Erros.rejectvalue ("username","Length","User name length between 3-20 strings"); }if(Account.getpassword (). Length () <6|| Account.getpassword (). Length () > -) {Erros.rejectvalue ("Password","Size","Password length is between 6-20 characters"); }    }}
5. Join JSP

Create a new JSP directory in Web-inf, and then create a new register.jsp file, adding the following code:

<%@ page language="java" contenttype="text/html; Charset=utf-8 "pageencoding="UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "Http://www.w3.org/TR/html4/loose.dtd" ><%@ taglib prefix="form" uri="Http://www.springframework.org/tags/form" %><html><head><meta http-equiv="Content-type" Content="text/html; Charset=utf-8 "><title>Registration interface</title></head><body>    <form:form Method="POST"modelattribute="Account">          <label for ="username">User name:</label>        <form:input type="text" path="username"/>         <form:errors path="username"/><br><br>       <label for ="pwd">Password:</label>&nbsp;<form:input type="password" path="password"/>         <form:errors path="password"/>        <br><br>        <input type="Submit" value="register" name=  "Login"/>&nbsp;&nbsp;</form:form><br><hr>${message}</body></html>
6. Effect Demonstration

Run the program and enter the address in the browser: http://localhost:8080/annotation_springmvc/register

Spring MVC Data Validation--validate encoding method

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.