"Funnybear Java Tour-Spring chapter" Spring Form Validation

Source: Internet
Author: User

Tried to validate a form provided by spring

1. Create a form

Add the following form to the JSP page. Where action corresponds to the controller,commandname we have prepared to specify the object that corresponds to the form in the PageContext. Spring automatically fills the form data into the object. The path of Sf:input and Sf:error corresponds to the properties of the object.

<prefix= "SF"  uri= "Http://www.springframework.org/tags/form"  %>
<Sf:formMethod= "POST"Action= "${pagecontext.request.contextpath}/docreate"CommandName= "User">    <Tableclass= "Formtable">        <TR>            <TDclass= "Label">Name:</TD>            <TD><Sf:inputname= "Name"Path= "Name"type= "text"></Sf:input><BR/>                <sf:errorsPath= "Name"CssClass= "Error"></sf:errors></TD>        </TR>        <TR>            <TDclass= "Label">Email:</TD>            <TD><Sf:inputname= "Email"Path= "Email"type= "text"></Sf:input><BR/>                <sf:errorsPath= "Email"CssClass= "Error"></sf:errors></TD>        </TR>        <TR>            <TD></TD>            <TD><inputvalue= "Create user"type= "Submit"></input></TD>        </TR>    </Table></Sf:form>

2. Adding a Controller method

When accessing the page of the form, we need to add an object to PageContext that corresponds to the form commandname.

@RequestMapping ("/createuser") public String CreateUser (model model) {    Model.addattribute (New  User ());     return "CreateUser";}

@Valid indicates that we want to verify the user object passed in from the form, and the result will be filled into the Bindingresult object, and Sf:error will take the corresponding error message from the Bindingresult object and display it.

@RequestMapping (value= "/docreate", method=requestmethod.post) public String docreate (Model Model, @Valid User user, bindingresult result) { if(Result.haserrors ()) { return "CreateUser"; } Else { usersservice.createuser (user); return "Usercreated"; }}

3. Adding a test to the user class

The verification is mainly implemented by annotations, for which we refer to the validator of Validation-api-1.1.0.final.jar and hibernate. Add the following dependencies in the MAVEN project's Pom file

<Dependency>    <groupId>Javax.validation</groupId>    <Artifactid>Validation-api</Artifactid>    <version>1.1.0.Final</version></Dependency><Dependency>    <groupId>Commons-validator</groupId>    <Artifactid>Commons-validator</Artifactid>    <version>1.5.1</version></Dependency><Dependency>    <groupId>Org.hibernate</groupId>    <Artifactid>Hibernate</Artifactid>    <version>3.5.4-final</version>    <type>Pom</type></Dependency><Dependency>    <groupId>Org.hibernate</groupId>    <Artifactid>Hibernate-validator</Artifactid>    <version>5.0.1.Final</version></Dependency>

Add a check condition on a field

 PackageCom.funnybear.springmvc.dao;ImportJavax.validation.constraints.NotNull;Importjavax.validation.constraints.Size; Public classUser {@Size (min=5, max=100, message= "Name must be between 5 and characters.")    PrivateString name; @NotNullPrivateString Email;  PublicString GetName () {returnname; }     Public voidsetName (String name) { This. Name =name; }     PublicString Getemail () {returnemail; }     Public voidsetemail (String email) { This. email =email; }     PublicUser () {} PublicUser (string name, string email) {Super();  This. Name =name;  This. email =email; } @Override PublicString toString () {return"User [name=" + name + ", email=" + email + "]"; }}

This will make it easy to display the verification results at the time of submission.

Problem: Hibernate class library is not directly referenced in the code, but missing it, the validation results can not be displayed, need to further study.

"Funnybear Java Tour-Spring chapter" Spring Form Validation

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.