弹簧形式验证:无法在jsp中打印错误

时间:2014-11-19 12:59:01

标签: hibernate jsp spring-mvc

我正在使用spring mvc应用程序,这里我有一个用户可以更改密码的表单,这里我通过使用弹簧形式验证来验证表单,该表单验证实现了这个" org.springframework.validation.Validator&# 34;类。

please look at this code snippets.

<%@ taglib uri="http://www.springframework.strong textorg/tags/form" prefix="spring"%>
        <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
        <%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

        <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
        <!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=ISO-8859-1">
        <title> Change password </title>
        </head>
        <body>
        <%@include file="index.jsp" %>
        <div class="row">
            <div class="container" style=" background-color: #F9FFED; ">
                <div>
                    <h4><label>Change password:</label></h4> 
                </div>

                <div class="col-md-12" >
                <spring:form commandName="ChangePassword" action="ChangePassword.do" method="post">
                <table>
                    <tr>
                        <td><label for="current_pwd"  >Current Password</label></td>
                        <td><spring:input path="current_pwd" type="text" class="form-control"  placeholder="Name"/></td>
                        <td><spring:errors path="current_pwd" type="text" cssStyle="color: red;"></spring:errors></td>
                    </tr>
                    <tr>
                        <td>&nbsp</td>
                    </tr>
                    <tr>
                        <td><label for="newpassword"  >New Password</label></td>
                        <td><spring:input path="newpassword" type="text" class="form-control"  placeholder="Password"/></td>
                        <td><spring:errors path="newpassword" type="text" cssStyle="color: red;"></spring:errors></td>
                    </tr>
                    <tr>
                        <td>&nbsp</td>
                    </tr>
                    <tr>
                        <td><label for="confirmPassword"  >Confirm Password</label></td>
                        <td><spring:input path="confirmPassword" type="text" class="form-control"  placeholder="Password"/></td>
                        <td><spring:errors path="confirmPassword" type="text" cssStyle="color: red;"></spring:errors></td>
                    </tr>
                    <tr>
                        <td>&nbsp</td>
                    </tr>
                    <tr>
                        <td>
                            <button type="submit" class="btn btn-success"> SAVE </button> 
                            <a href="ListUsers.do" class="btn btn-success"> Cancel </a>
                        </td>
                      </tr>

                </table>

                </spring:form>
                </div>
            </div>
        </div>
        </body>
        </html>
  1. 控制器获取和发布方法

    @RequestMapping(值=&#34; / ChangePassword&#34;,方法= RequestMethod.GET)         public String changePassword(ChangePassword chPaswd,BindingResult result,ModelMap model){             chPaswd = new ChangePassword();             model.addAttribute(&#34; ChangePassword&#34;,chPaswd);             返回&#34; ChangePassword&#34 ;;         }

        @RequestMapping(value="/ChangePassword",method=RequestMethod.POST)
        public String changePasswordPost(ChangePassword chpwd,BindingResult result,ModelMap model,HttpSession session){
            String message="";
    
            changepwdValidator.validate(chpwd, result);
    
            chpwd=new ChangePassword();
    
            if(result.hasFieldErrors()){
                System.out.println("Has errors");
                model.addAttribute("ChangePassword",chpwd);
                return "ChangePassword";
            }else{
    
                System.out.println("chnage pwd values :"+chpwd.getNewpassword()+","+"current pwd:"+chpwd.getCurrent_pwd());
                try{
                   // some other operations
    
                    model.addAttribute("ChangePassword",chpwd);
                    }catch(Exception e){
                        message="Failed to process the request, please re-verify the values!";
                        model.addAttribute("message", message);   
                    }
                return "ChangePassword";
            }
        }
    
  2. 验证员类

    import org.springframework.validation.Errors;     import org.springframework.validation.ValidationUtils;     import org.springframework.validation.Validator;

    import com.knot.pirautomation.models.ChangePassword;
    
    public class ChangePasswordValidator implements Validator{
    
        ChangePassword chngepwd;
    
        public boolean supports(Class clazz) {
    
            return ChangePassword.class.equals(clazz);
        }
    
        public void validate(Object target, Errors errors) {
            if(target instanceof ChangePassword){
                chngepwd=(ChangePassword) target;
    
                System.out.println("----------");
                System.out.println("Old pwd:"+chngepwd.getCurrent_pwd());
                System.out.println("new pwd:"+chngepwd.getNewpassword());
                System.out.println("confirm pwd:"+chngepwd.getConfirmPassword());
                System.out.println("----------");
    
                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "newpassword", "NewPassword.required");
                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "confirmPassword", "ConfirmPassword.required");
                ValidationUtils.rejectIfEmptyOrWhitespace(errors, "current_pwd", "Oldpassword.required");
    
                if( !(chngepwd.getNewpassword().equals(chngepwd.getConfirmPassword()))){
                    errors.rejectValue("newpassword", "NewPassword.match");
                }
                if((chngepwd.getNewpassword().length()<8)){
                    errors.rejectValue("newpassword", "NewPasswordlength.match" );
                }
                if((chngepwd.getConfirmPassword().length()<8)){
                    errors.rejectValue("confirmPassword", "ConfirmPasswordlength.match" );
                }
    
                String blackListChars = "!'=();<> \"";
                char blackListArr[] = blackListChars.toCharArray();
                for(int i=0;i<blackListArr.length;i++) {
                    if(chngepwd.getNewpassword().contains("" + blackListArr[i])) {
                        errors.rejectValue("newpassword","NewPassword.invalidChars"); 
                        break;
                    }           
                }
    
                for(int i=0;i<blackListArr.length;i++) {
                    if(chngepwd.getConfirmPassword().contains("" + blackListArr[i])) {
                        errors.rejectValue("confirmPassword","ConfirmPassword.invalidChars"); 
                        break;
                    }           
                }
    
            }
    
        }
    
    }
    
  3. error.properties文件

    Oldpassword.required =需要旧密码     NewPassword.required =需要新密码     ConfirmPassword.required =需要确认密码     NewPassword.match =确认密码应匹配     NewPasswordlength.match =新密码至少应为8个字符     ConfirmPasswordlength.match =确认密码至少应为8个字符     NewPassword.invalidChars =新密码具有不允许的特殊字符     ConfirmPassword.invalidChars =确认密码具有不允许的特殊字符

  4. 你可以看到,当表单有错误时,我将控制权返回给同一个jsp。     我无法跟踪我的springform验证工作正常的错误/错误,但是当我试图显示我的属性文件中定义的错误时。

    请有人在这个问题上帮助我。

1 个答案:

答案 0 :(得分:0)

使用此...您不应该明确地调用验证器。

@Valid @ModelAttribute(“forName”)FormName formName,             BindingResult bindingResult,Model model,             RedirectAttributes redirectAttributes,HttpSession session