Spring MVC Data validation

Source: Internet
Author: User

Add a Jar Package

Bean-validator.jar

Adding validation annotation and message hints to entity classes

 PackageCom.stone.model;Importjavax.validation.constraints.Size;ImportOrg.hibernate.validator.constraints.Email;ImportOrg.hibernate.validator.constraints.NotEmpty; Public classUser {Private intID; PrivateString username; PrivateString Nickname; PrivateString password; PrivateString Email;  PublicUser (string username, string nickname, string password, string email) { This. Username =username;  This. Nickname =nickname;  This. Password =password;  This. email =email; }     PublicUser () {Super(); }     Public intgetId () {returnID; }     Public voidSetId (intID) { This. ID =ID; } @NotEmpty (Message= "User name cannot be empty")     PublicString GetUserName () {returnusername; }     Public voidSetusername (String username) { This. Username =username; }     PublicString Getnickname () {returnnickname; }     Public voidSetnickname (String nickname) { This. Nickname =nickname; } @NotEmpty (Message= "Password cannot be empty") @Size (min= 3, max = 10,message= "Password length must be greater than 3 less than 10")     PublicString GetPassword () {returnpassword; }     Public voidSetPassword (String password) { This. Password =password; } @Email (Message= "Mail format is [email protected]")     PublicString Getemail () {returnemail; }     Public voidsetemail (String email) { This. email =email; } @Override PublicString toString () {return"User [id=" + ID + ", username=" + Username + ", nickname=" + nickname + ", password=" + password + ", Emai L= "+Email+ "]"; }}

Adding @valid and Bindingresult to the controller to process the validation results

 PackageCom.stone.controller;ImportJava.util.HashMap;ImportJava.util.Map;ImportJavax.validation.Valid;ImportOrg.springframework.stereotype.Controller;ImportOrg.springframework.ui.Model;ImportOrg.springframework.validation.BindingResult;Importorg.springframework.web.bind.annotation.RequestMapping;ImportOrg.springframework.web.bind.annotation.RequestMethod;ImportOrg.springframework.web.servlet.view.InternalResourceViewResolver;ImportCom.stone.model.User, @Controller @requestmapping ("/USER") Public classUsercontroller {Private Final Staticmap<string, user> users =NewHashmap<string, user>();  PublicUsercontroller () {Users.put ("LDH",NewUser ("LDH", "Andy Lau", "123", "[email protected]")); Users.put ("Zxy",NewUser ("Zxy", "Jacky", "123", "[email protected]")); Users.put ("GFC",NewUser ("GFC", "Aaron Kwok", "123", "[email protected]")); Users.put ("LM",NewUser ("LM", "Dawn", "123", "[email protected]")); } @RequestMapping ("/users")     PublicThe String list (model model) {Model.addattribute ("Users", users); return"User/list"; } @RequestMapping (Value= "/add", method =requestmethod.get) PublicString Add (model model) {Model.addattribute (NewUser ()); return"User/add"; } @RequestMapping (Value= "/add", method =requestmethod.post) PublicString Add (@Valid user user, Bindingresult bingding) {if(Bingding.haserrors ()) {return"User/add";        } users.put (User.getusername (), user); returnInternalresourceviewresolver.redirect_url_prefix + "/user/users"; }}

Add a validation hint message to the JSP

<%@ Page Language="Java"Import="java.util.*"pageencoding="Utf-8"%><%@taglib prefix="SF"URI="Http://www.springframework.org/tags/form"%><%    StringPath=Request.getcontextpath (); StringBasePath=Request.getscheme ()+ "://"            +Request.getservername ()+ ":" +Request.getserverport ()+Path+ "/";%><!DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en"><HTML><Head><Basehref= "<%=basePath%>"><title>My JSP ' add.jsp ' starting page</title><Metahttp-equiv= "Pragma"content= "No-cache"><Metahttp-equiv= "Cache-control"content= "No-cache"><Metahttp-equiv= "Expires"content= "0"></Head><Body>    <Sf:formMethod= "POST"Modelattribute= "User">Username:<Sf:inputPath= "username" />        <sf:errorsPath= "username" />        <BR/>Password:<Sf:passwordPath= "Password" />        <sf:errorsPath= "Password" />        <BR/>Nickname:<Sf:inputPath= "nickname" />        <BR/>Email:<Sf:inputPath= "Email" />        <sf:errorsPath= "Email" />        <BR/>        <inputtype= "Submit" />    </Sf:form></Body></HTML>

Spring MVC Data 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.