日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當(dāng)前位置: 首頁 > 编程语言 > c/c++ >内容正文

c/c++

MVC 表单验证

發(fā)布時間:2025/5/22 c/c++ 136 豆豆
生活随笔 收集整理的這篇文章主要介紹了 MVC 表单验证 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

2019獨(dú)角獸企業(yè)重金招聘Python工程師標(biāo)準(zhǔn)>>>

表單:

?

用戶注冊頁面: 名稱:user.jsp
注冊用戶包含三項信息: 用戶名,密碼,郵箱。

[html] ? view plain copy
  • < %@?page? language = "java" ? contentType = "text/html;?charset=UTF-8" % > ??
  • < %@?taglib? prefix = "sf" ? uri = "http://www.springframework.org/tags/form" % > ??
  • ??
  • <!DOCTYPE?html?PUBLIC?"-//W3C//DTD?HTML?4.01?Transitional//EN"?"http://www.w3.org/TR/html4/loose.dtd"> ??
  • < html > ??
  • < head > ??
  • < meta ? http-equiv = "Content-Type" ? content = "text/html;?charset=UTF-8" > ??
  • < title > User?Register?Page </ title > ??
  • < style ? type = "text/css" > ??
  • .error{??
  • ????color:?red;???
  • }??
  • </ style > ??
  • </ head > ??
  • ??
  • < body > ??
  • ????< %--??
  • ????????這里指定頁面綁定的對象?modelAttribute.?之前很困惑,??
  • ????????為什么< form > 上最重要的? < form ? action = "someAction.do" > 屬性沒了呢????
  • ????????后來發(fā)現(xiàn),其實(shí)在controller中的方法以及指定了地址到method的對應(yīng)關(guān)系,??
  • ????????< form > 里的action屬性就可以退休了。??
  • ????--%> ??
  • ????< sf:form ? method = "post" ? modelAttribute = "user" > ??
  • ????????< p > 用戶注冊頁面: </ p > ??
  • ????????< table ? width = "60%" ? align = "center" > ??
  • ????????????< colgroup > ??
  • ????????????????< col ? width = "10%" ? align = "right" ? /> ??
  • ????????????????< col ? /> ??
  • ????????????</ colgroup > ?????
  • ????????????< tr > ??
  • ????????????????< th > 用戶名: </ th > ??
  • ????????????????< td > ??
  • ????????????????????< sf:input ? path = "userName" ? /> ??
  • ????????????????????< small > length?of?userName?is?not?more?than?20. </ small > < br ? /> ??
  • ????????????????????< %--?顯示關(guān)于userName屬性相關(guān)的錯誤信息。?--% > ??
  • ????????????????????< sf:errors ? path = "userName" ? cssClass = "error" /> ??
  • ????????????????</ td > ??
  • ????????????</ tr > ??
  • ????????????< tr > ??
  • ????????????????< th > 密碼: </ th > ??
  • ????????????????< td > ??
  • ????????????????????< sf:password ? path = "password" ? /> ??
  • ????????????????????< small > length?of?password?is?not?less?than?6. </ small > < br ? /> ??
  • ????????????????????< sf:errors ? path = "password" ? cssClass = "error" ? /> ??
  • ????????????????</ td > ??
  • ????????????</ tr > ??
  • ????????????< tr > ??
  • ????????????????< th > 郵箱: </ th > ??
  • ????????????????< td > ??
  • ????????????????????< sf:input ? path = "email" /> ??
  • ????????????????????< small > format?should?confirm?to?general?standard. </ small > < br ? /> ??
  • ????????????????????< sf:errors ? path = "email" ? cssClass = "error" ? /> ??
  • ????????????????</ td > ??
  • ????????????</ tr > ???????????
  • ????????????< tr > ??
  • ????????????????< td ? colspan = "2" ? align = "center" > ??
  • ????????????????????< input ? type = "submit" ? value = "注冊" ? /> ??
  • ????????????????</ td > ??
  • ????????????</ tr > ??
  • ????????</ table > ??
  • ????</ sf:form > ??
  • </ body > ??
  • </ html > ??
  • ?

    校驗方式一: JSR303 Bean Validation

    在Spring3.1中增加的了對JSR303 Bean Validation規(guī)范的支持,不僅可以對Spring的 MVC進(jìn)行校驗,而且也可以對Hibernate的存儲對象進(jìn)行校驗。是一個通用的校驗框架。

    ?


    環(huán)境準(zhǔn)備:

    A) 導(dǎo)入Hibernate-Validator ?
    要使用JSR303 校驗框架, 需要加入框架的具體實(shí)現(xiàn)Hibernate-Validator, 在soureforge上下載最新的Hibernate-Validator , 當(dāng)前版本為4.2.0 Final版。
    在/WEB-INF/lib中導(dǎo)入?hibernate-validator-4.2.0.Final.jar,?hibernate-validator-annotation-processor-4.2.0.Final.jar, 導(dǎo)入它的lib/required目錄下內(nèi)容slf4j-api-1.6.1.jar,?validation-api-1.0.0.GA.jar;

    B) 配置Spring對JSR 303 的支持。?
    在你的 <servletName>-servlet.xml配置文件中,使用標(biāo)簽:

    [html] ? view plain copy
  • < mvc:annotation-driven ? /> ??
  • 配置對JSR303的支持,包括制動查找Hibernate-Validator的實(shí)現(xiàn)等工作。


    1) 可用的 JSR303注解

    ?

    空檢查

    @Null ? ? ? 驗證對象是否為null

    @NotNull ? ?驗證對象是否不為null, 無法查檢長度為0的字符串

    @NotBlank 檢查約束字符串是不是Null還有被Trim的長度是否大于0,只對字符串,且會去掉前后空格.

    @NotEmpty 檢查約束元素是否為NULL或者是EMPTY.

    ?

    Booelan檢查

    @AssertTrue ? ? 驗證 Boolean 對象是否為 true ?

    @AssertFalse ? ?驗證 Boolean 對象是否為 false ?

    ?

    長度檢查

    @Size(min=, max=) 驗證對象(Array,Collection,Map,String)長度是否在給定的范圍之內(nèi) ?

    @Length(min=, max=) Validates that the annotated string is between min and max included.

    ?

    日期檢查

    @Past ? ? ? ? ? 驗證 Date 和 Calendar 對象是否在當(dāng)前時間之前 ?

    @Future ? ? 驗證 Date 和 Calendar 對象是否在當(dāng)前時間之后 ?

    @Pattern ? ?驗證 String 對象是否符合正則表達(dá)式的規(guī)則

    ?

    數(shù)值檢查,建議使用在Stirng,Integer類型,不建議使用在int類型上,因為表單值為“”時無法轉(zhuǎn)換為int,但可以轉(zhuǎn)換為Stirng為"",Integer為null

    @Min ? ? ? ? ? ?驗證 Number 和 String 對象是否大等于指定的值 ?

    @Max ? ? ? ? ? ?驗證 Number 和 String 對象是否小等于指定的值 ?

    @DecimalMax 被標(biāo)注的值必須不大于約束中指定的最大值. 這個約束的參數(shù)是一個通過BigDecimal定義的最大值的字符串表示.小數(shù)存在精度

    @DecimalMin 被標(biāo)注的值必須不小于約束中指定的最小值. 這個約束的參數(shù)是一個通過BigDecimal定義的最小值的字符串表示.小數(shù)存在精度

    @Digits ? ? 驗證 Number 和 String 的構(gòu)成是否合法 ?

    @Digits(integer=,fraction=)?驗證字符串是否是符合指定格式的數(shù)字,interger指定整數(shù)精度,fraction指定小數(shù)精度。

    ?

    @Range(min=, max=) Checks whether the annotated value lies between (inclusive) the specified minimum and maximum.

    @Range(min=10000,max=50000,message="range.bean.wage")
    private BigDecimal wage;

    ?

    @Valid 遞歸的對關(guān)聯(lián)對象進(jìn)行校驗, 如果關(guān)聯(lián)對象是個集合或者數(shù)組,那么對其中的元素進(jìn)行遞歸校驗,如果是一個map,則對其中的值部分進(jìn)行校驗.(是否進(jìn)行遞歸驗證)

    @CreditCardNumber信用卡驗證

    @Email 驗證是否是郵件地址,如果為null,不進(jìn)行驗證,算通過驗證。

    @ScriptAssert(lang= ,script=, alias=)

    @URL(protocol=,host=, port=,regexp=, flags=)

    ?

    ?

    ?

    ?


    通過上述Constraint約束后的User對象如下:

    [java] ? view plain copy
  • package ?org.study.domain;??
  • ??
  • import ?javax.validation.constraints.Pattern;??
  • import ?javax.validation.constraints.Size;??
  • ??
  • import ?org.study.validation.annotation.NotEmpty;??
  • ??
  • public ? class ?User?{??
  • ??????
  • ????@Size ?(min= 3 ,?max= 20 ,?message= "用戶名長度只能在3-20之間" )??
  • ????private ?String?userName;??
  • ??????
  • ????@Size ?(min= 6 ,?max= 20 ,?message= "密碼長度只能在6-20之間" )??
  • ????private ?String?password;??
  • ??????
  • ????@Pattern ?(regexp= "[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}" ,?message= "郵件格式錯誤" )??
  • ????private ?String?email;??
  • ??????
  • ????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;??
  • ????}??
  • ????public ?String?getEmail()?{??
  • ????????return ?email;??
  • ????}??
  • ????public ? void ?setEmail(String?email)?{??
  • ????????this .email?=?email;??
  • ????}??
  • ??????
  • ????public ?String?toString(){??
  • ????????StringBuilder?sb?=?new ?StringBuilder();??
  • ??????????
  • ????????sb.append(getClass()).append("[" )??
  • ????????.append("userName=" ).append(userName).append( ",?" )??
  • ????????.append("password=" ).append(password).append( ",?" )??
  • ????????.append("email=" ).append(email).append( "]" );??
  • ??????????
  • ????????return ?sb.toString();??
  • ????}??
  • ??????
  • }??

  • 2) Validate的觸發(fā)
    在需要校驗的對象前增加 @Valid 注解 (該注解位于javax.validation包中)來觸發(fā)校驗。示例如下:

    [java] ? view plain copy
  • /** ?
  • ?????*?處理提交的用戶注冊信息。 ?
  • ?????*?@param?model ?
  • ?????*?@return ?
  • ?????*/ ??
  • ????@RequestMapping ?(method?=?RequestMethod.POST)??
  • ????public ?String?doRegister( @Valid ?User?user,?BindingResult?result){??
  • ????????if (logger.isDebugEnabled()){??
  • ????????????logger.debug("process?url[/user],?method[post]?in?" +getClass());??
  • ????????}??
  • ????????//校驗沒有通過 ??
  • ????????if (result.hasErrors()){??
  • ????????????return ? "user" ;??
  • ????????}??
  • ??????????
  • ????????if (user?!=? null ){??
  • ????????????userService.saveUser(user);??
  • ????????}??
  • ??????????
  • ????????return ? "user" ;??
  • ????}??

  • 這樣就可以完成針對輸入數(shù)據(jù)User對象的校驗了, 校驗結(jié)果任然保存在BindingResult對象中。

    ?

    ?

    ?

    校驗方式二: Spring Validator?

    1)Validator接口的實(shí)現(xiàn):

    Spring框架的Validator接口定義,

    [java] ? view plain copy
  • package ?org.springframework.validation;??
  • ??
  • public ? interface ?Validator?{??
  • ??????
  • ????boolean ?supports(Class<?>?clazz);??
  • ??????
  • ????void ?validate(Object?target,?Errors?errors);??
  • ??
  • }??
  • 要使用它進(jìn)行校驗必須實(shí)現(xiàn)該接口。實(shí)現(xiàn)Validator接口的代碼如下:

    [java] ? view plain copy
  • package ?org.study.validation.validator;??
  • ??
  • import ?org.springframework.validation.Errors;??
  • import ?org.springframework.validation.ValidationUtils;??
  • import ?org.springframework.validation.Validator;??
  • import ?org.study.domain.User;??
  • ??
  • public ? class ?UserValidator? implements ?Validator?{??
  • ??
  • ????@Override ??
  • ????public ? boolean ?supports(Class<?>?clazz)?{??
  • ????????return ?clazz.equals(User. class );??
  • ????}??
  • ??
  • ????@Override ??
  • ????public ? void ?validate(Object?target,?Errors?errors)?{??
  • ????????ValidationUtils.rejectIfEmpty(errors,?"userName" ,? "user.userName.required" ,? "用戶名不能為空" );??
  • ????????ValidationUtils.rejectIfEmpty(errors,?"password" ,? "user.password.required" ,? "密碼不能為空" );??
  • ????????ValidationUtils.rejectIfEmpty(errors,?"email" ,? "user.email.required" ,? "郵箱不能為空" );??
  • ????????User?user?=?(User)target;??
  • ????????int ?length?=?user.getUserName().length();??
  • ????????if (length> 20 ){??
  • ????????????errors.rejectValue("userName" ,? "user.userName.too_long" ,? "用戶名不能超過{20}個字符" );??
  • ????????}??
  • ????????length?=?user.getPassword().length();??
  • ????????if (length?< 6 ){??
  • ????????????errors.rejectValue("password" ,? "user.password.too_short" ,? "密碼太短,不能少于{6}個字符" );??
  • ????????}else ? if (length> 20 ){??
  • ????????????errors.rejectValue("password" ,? "user.password.too_long" ,? "密碼太長,不能長于{20}個字符" );??
  • ????????}??
  • ????????int ?index?=?user.getEmail().indexOf( "@" );??
  • ????????if (index?==?- 1 ){??
  • ????????????errors.rejectValue("email" ,? "user.email.invalid_email" ,? "郵箱格式錯誤" );??
  • ????????}??
  • ????}??
  • ??
  • }??

  • 2) 設(shè)置Validator,并觸發(fā)校驗。
    在我們的Controller中需要使用父類已有的方法來為DataBinder對象指定Validator, ?protected initBinder(WebDataBinder binder); 代碼如下:

    [java] ? view plain copy
  • @InitBinder ??
  • ????protected ? void ?initBinder(WebDataBinder?binder){??
  • ????????binder.setValidator(new ?UserValidator());??
  • ????}??

  • 為binder對象指定好Validator校驗對象后,下面一步的就是在需要校驗的時候觸發(fā)validate方法,該觸發(fā)步驟是通過 @Validated 注解(該注解是Spring框架定義的)實(shí)現(xiàn)的。

    [java] ? view plain copy
  • /** ?
  • ?????*?處理提交的用戶注冊信息。 ?
  • ?????*?@param?model ?
  • ?????*?@return ?
  • ?????*/ ??
  • ????@RequestMapping ?(method?=?RequestMethod.POST)??
  • ????public ?String?doRegister( @Validated ?User?user,?BindingResult?result){??
  • ????????if (logger.isDebugEnabled()){??
  • ????????????logger.debug("process?url[/user],?method[post]?in?" +getClass());??
  • ????????}??
  • ????????//校驗沒有通過 ??
  • ????????if (result.hasErrors()){??
  • ????????????return ? "user" ;??
  • ????????}??
  • ??????????
  • ????????if (user?!=? null ){??
  • ????????????userService.saveUser(user);??
  • ????????}??
  • ??????????
  • ????????return ? "user" ;??
  • ????}??

  • 至此,從頁面提交的User對象可以通過我們實(shí)現(xiàn)的UserValidator類來校驗了,校驗的結(jié)果信息存入BindingResult result對象中。在前臺頁面可以使用spring-form的標(biāo)簽<sf:errors path="*" />來顯示。

    轉(zhuǎn)載于:https://my.oschina.net/pangzhuzhu/blog/317924

    總結(jié)

    以上是生活随笔為你收集整理的MVC 表单验证的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。

    如果覺得生活随笔網(wǎng)站內(nèi)容還不錯,歡迎將生活随笔推薦給好友。