Spring MVC annotation verification springmodules common validator (annotation verification)

Source: Internet
Author: User
Tags cdata tld

First of all, spring modules, it is customized for some spring tool components, the official address in the https://springmodules.dev.java.net/, the official website is introduced as follows: Spring modules is a collection of tools, add-ons and modules to extend the Spring framework. the core goal of spring
Modules is to facilitate integration between spring and other projects without cluttering or expanding the spring core. There are many sub-projects in it. Among them, commons validator is a configurable verification framework. Its usage and working principles are the same as those of validatorplugin in struts. It can generate JS verification on the client through configuration, or implement server verification with spring controller with verification function.

I am doing a small example in my resources everybody can download http://download.csdn.net/source/3494112

The project uses eclipse to directly run all the jar packages and files.

1Download the jarpackage from https://springmodules.dev.java.net/. we will use spring-modules-validation.jar;

2The ide I'm using is eclipse creating a web project named springvaldiateanonation, copying spring, Jakarta-commons and other necessary jar files including spring-modules-validation.jar to WEB-INF/lib/, copying c-rt.tld, spring. TLD, spring-form.tld to WEB-INF/TLD/; do a good job of spring basic configuration, including web. XML, applicationcontext. XML,
Xxx-servlet.xml; configure log4j. properties;

3Create the Web. kjt package under SRC and create the domain object user under the package, which will be used as our form object;

public class User {private String userName;private String password;public String getUserName() {return userName;}public void setUserName(String userName) {this.userName = userName;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}

4Create a logincontroller under the Web. kjt package. Because the request information is configured using spring MVC annotations, no corresponding controller is inherited. The Code is as follows:

Package COM. kjt; import Java. util. arraylist; import Java. util. list; import javax. validation. valid; import Org. springframework. beans. factory. annotation. autowired; import Org. springframework. stereotype. controller; import Org. springframework. UI. modelmap; import Org. springframework. validation. bindingresult; import Org. springframework. validation. validator; import Org. springframework. web. BIND. annotation. modelattribute; import Org. springframework. web. BIND. annotation. requestmapping; @ controllerpublic class logincontroller {@ autowired (required = false) validator; // This Must Be In applicationcontext. configure bean injection in XML // client verification and background verification configuration request @ requestmapping ("/login. do ") Public String login (@ valid @ modelattribute (" user ") User user, bindingresult, modelmap) {try {system. out. println ("11"); // check whether the request can come in if (user. getUserName () = NULL) {user = new user (); modelmap. addattribute (User);} else {validator. validate (user, bindingresult); // This is to verify the data submitted by the foreground} return "login";} catch (exception e) {// todo: handle exceptionsystem. out. println ("error message" + E. getmessage (); E. printstacktrace (); Return "welcome" ;}}@ requestmapping (value = "/login1.do ") // The backend authentication configuration request public string login1 (@ valid @ modelattribute ("user") User user, bindingresult, modelmap) {try {system. out. println ("22"); If (user. getUserName () = NULL) {user = new user (); modelmap. addattribute (User);} else {validator. validate (user, bindingresult);} return "login1";} catch (exception e) {// todo: handle exceptionsystem. out. println ("error message" + E. getmessage (); E. printstacktrace (); Return "welcome ";}}}

It must be noted that the user and bindingresult objects must be adjacent to each other; otherwise, an error occurs. Their bindingresult stores the verification error information in the errors attribute.

The following describes how to configure springmvc annotation verification. In fact, it is no different from springmvc XML verification, that is, the configuration request method is different.

5Find the validator-rules.xml from the sample of the springmodules download package, verify. xml copy to the WEB-INF directory, open and look at the two files, you will find that they and Struts validatorplugin need of the two configuration files exactly
You can even copy these two files from your struts project and take them for modification.

 

The validator-rules.xml predefines some validators, such as required (mandatory), minlength (shortest length), maxlength (max length), float (decimals can be input ), INTEGER (an integer can be entered) and mask (the input value must meet the regular expression requirements). This file does not need to be changed most of the time unless we want to expand the function or find bugs;

Validation. XML defines some form verification rules. We need a form verification function to configure a verification information in this file. after these two files are copied, you can configure the validators factory and validators.

Configure validatorfactory and beanvalidator in applicationcontext. XML (why should I configure it in applicationcontext: Because the validators can be used as components common to applications and can be shared by all servlets ):

<! -- The name must be messagesource, because the jar package of springmodules needs to reference the bean named messagesource when it needs to be referenced for verification. You can try to change the name, after I tested it, wasn't the validator error messages key --> <bean id = "messagesource" class = "org. springframework. context. support. resourcebundlemessagesource "> <property name =" basename "value =" messages "/> </bean> <bean id =" validatorfactory "class =" org. springmodules. validation. commons. defaultvalidat Orfactory "> <property name =" validationconfiglocations "> <list> <value> WEB-INF/validator-rules.xml </value> <value> WEB-INF/validation. XML </value> </List> </property> </bean> <! -- In applicationcontext. configure validatorfactory and beanvalidator in XML (why should we configure it in applicationcontext: Because the validators can be used as components common to applications and can be shared by all servlets ): --> <bean id = "beanvalidator" class = "org. springmodules. validation. commons. defaultbeanvalidator "> <property name =" validatorfactory "ref =" validatorfactory "/> </bean> <bean id =" viewresolver "class =" org. springframework. web. servlet. view. internalresourceviewresolver "> <property name =" prefix "value =" WEB-INF/JSP/"/> <property name =" suffix "value = ". JSP "/> </bean>

6Open validation. xml and add a form in it,

<Form name = "user"> <field property = "username" depends = "required"> <! -- Depands field is the validators to be configured. You can configure multiple validators --> <! -- Arg0 indicates the display name of this field, when verification fails, a prompt message is displayed. The key is the key that defines the message in messageresource --> <arg0 key = "username"/> </field> <field property = "password" depends = "maxlength, required "> <arg0 key =" password "/> <arg1 name =" maxlength "Key =" $ {var: maxlength} "resource =" false "/> <var-Name> maxlength </var-Name> <var-value> 10 </var-value> </var> </field> </form>

7 configure the required message, in order to display error information when verification fails, you need to copy the validator error messages commented out at the top of the sample file validator-rules.xml to the message. properties, and put it under classpath. also in applicationcontext. configure messagesource in XML,

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"><property name="basename" value="messages" /></bean>

Add the display name of the form field to message. properties. The full text of messages. properties in this example is as follows:

#english message fileerrors.required={0} is required.errors.minlength={0} can not be less than {1} characters.errors.maxlength={0} can not be greater than {1} characters.errors.invalid={0} is invalid.errors.byte={0} must be a byte.errors.short={0} must be a short.errors.integer={0} must be an integer.errors.long={0} must be a long.errors.float={0} must be a float.errors.double={0} must be a double.errors.date={0} is not a date.errors.range={0} is not in the range {1} through {2}.errors.creditcard={0} is an invalid credit card number.errors.email={0} is an invalid e-mail address.common.messages.close=Close user.name=userNameuser.password=userPassword

8Edit the JSP form page login. jsp,

<% @ Page Language = "Java" contenttype = "text/html; charset = gb18030 "pageencoding =" gb18030 "%> <% @ taglib uri ="/WEB-INF/TLD/c-rt.tld "prefix =" C "%> <% @ taglib prefix =" Spring "uri =" http://www.springframework.org/tags "%> <% @ taglib uri ="/WEB-INF/TLD/spring-form.tld "prefix =" form "%> <%@ taglib uri =" http://www.springmodules.org/tags/commons-validator "prefix = "validator" %> <validator: javascript formname = "user" s Taticjavascript = "true" XHTML = "true" CDATA = "false"/> <! Doctype HTML public "-// W3C // dtd html 4.01 transitional // en" "http://www.w3.org/TR/html4/loose.dtd"> <HTML> 

The above configuration is verified by JavaScript and the background.

To start JavaScript verification, you must add

<Validator: javascript formname = "book" staticjavascript = "true" XHTML = "true" CDATA = "false"/>

Deploy to Tomcat and test: http: // localhost: 8080/springvaldiateanonation/login. Do

Background verification page

 

Client verification Interface

 

I am doing a small example in my resources everybody can download http://download.csdn.net/source/3494112

The project uses eclipse to directly run all the jar packages and files.

Reference: http://blog.csdn.net/sunxing007/article/details/4660262

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.