开发者社区> 问答> 正文

配置commons validator验证框架:报错

在SpringMV中怎么配置commons validator验证框架,完全不会求详细代码 在线等 啊 谢谢

展开
收起
kun坤 2020-06-14 07:19:09 535 0
1 条回答
写回答
取消 提交回答
  • 参考:
    http://my.oschina.net/u/241255/blog/297726
    1.准备工作(依赖jar)

    2.配置要求
    <mvc:annotation-driven validator="validator"  />
    <bean id="validator" class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean"> 
            <property name="providerClass" value="org.hibernate.validator.HibernateValidator"/> 
            <!-- 如果不加默认到 使用classpath下的 ValidationMessages.properties --> 
            <property name="validationMessageSource" ref="messageSource"/> 
        </bean> 
          
        <!-- 国际化的消息资源文件(本系统中主要用于显示/错误消息定制) --> 
        <bean id="messageSource" class="org.springframework.context.support.ReloadableResourceBundleMessageSource"> 
            <property name="basenames"> 
                <list> 
                    <!-- 在web环境中一定要定位到classpath 否则默认到当前web应用下找  --> 
                    <value>classpath:resources/error</value> 
                </list> 
            </property> 
            <property name="useCodeAsDefaultMessage" value="false"/> 
            <property name="defaultEncoding" value="UTF-8"/> 
            <property name="cacheSeconds" value="60"/> 
        </bean>

    ===================error.properties===================================

    3.实体类


    4.页面
    1.加入tag <%@ taglib prefix="sf" uri="http://www.springframework.org/tags/form" %>
    <sf:form modelAttribute="user"  id="menuForm" name="menuForm" action="tt/addUser">
            <table class="l-table-edit page-table">
                 <tr>
                      <td></td>
                 </tr>
            </table>
                   <table class="l-table-edit page-table">
                        <tr>
                             <td><sf:label path="username">UserName:</sf:label> 
                        </td> 
                        <td><sf:input path="username" /> 
                        </td> 
                        <td><sf:errors path="username" class="errors" />
                        </td>
                             </td>
                             <td></td>
                        </tr>

    4.JAVA类处理
     @RequestMapping(value="/addUser")
       public String addUser( @Validated({First.class,Second.class})  @ModelAttribute("user") TbSysUser user ,BindingResult bindreResult,String ctype,HttpServletRequest request,Errors errors) throws Exception{
           try {
                if(!bindreResult.hasErrors()){
                     user.setPassword(StringUtil.string2MD5(user.getPassword()));     
                      userService.Add(user);
                      return "ok";
                }
                return  "sys/user_add";
         } catch (Exception e) {
              throw e;
         }
          
       }
      
       @ModelAttribute("user")
       private TbSysUser getTbSysUser(){
            return new TbSysUser();
       }















    5.AJAX处理

    @RequestMapping(value="/addUser")
       public String addUser(@Validated({First.class,Second.class})  @ModelAttribute("user") TbSysUser user ,BindingResult bindreResult,Errors errors,String ctype,HttpServletRequest request,HttpServletResponse response) throws Exception{
           try {
                if(!bindreResult.hasErrors()){
                     user.setPassword(StringUtil.string2MD5(user.getPassword()));
                      userService.Add(user);
                      response.getWriter().print("ok");
                } else {
                     Map<String, Object> map = new HashMap<String, Object>();
                     List<FieldError> fieldErrors = errors.getFieldErrors();
                     for (int i = 0; i < fieldErrors.size(); i++) {
                          map.put(fieldErrors.get(i).getField(), fieldErrors.get(i).getDefaultMessage());
                      }
                   response.getWriter().print("validateError!@#$"+JSONArray.fromObject(map));
                   throw new VerifyException("verror","message");
                }
                return null;
         } catch (Exception e) {
              throw new VerifyException("verror","message");
         }

    JS处理
    case(500):
                                   var errorStr = jqXHR.responseText.toString();
                                   if(errorStr.indexOf("validateError") != -1 ){//validateError
                                        var errorMessage = errorStr.split("!@#$")[1];//验证错误信息详情
                                        var errorJson = eval(errorMessage);//转json
                                        var inputName,errorDetail,top,left;
                                        for(var i=0; i<errorJson.length; i++)  {  //遍历
                                             for( var key in errorJson[i]){
                                                  inputName = key;
                                                  errorDetail = errorJson[i][key];
                                                  if($(":input[name='"+inputName+"']").length != 0){
                                                       var parentDiv = $(":input[name='"+inputName+"']").parent();
                                                       top = $(parentDiv).offset().top;
                                                       left = $(parentDiv).width()+$(parentDiv).offset().left+15;
                                                       $(":input[name='"+inputName+"']").parent().after("<span style='position:absolute; top:"+top+"px;left:"+left+"px '>"+errorDetail+"</span>");
                                                  }
                                             }
                                              }
                                   }
                                   $.ligerDialog.error("服务器系统内部错误");
                                  break;  
    ######

    ######或者你去参考
    http://my.oschina.net/u/241255/blog/297726
    2020-06-14 07:19:24
    赞同 展开评论 打赏
问答地址:
问答排行榜
最热
最新

相关电子书

更多
introduction to Apache Bean 立即下载
Java Spring Boot开发实战系列课程【第15讲】:Spring Boot 2.0 API与Spring REST Docs实战 立即下载
低代码开发师(初级)实战教程 立即下载