【问题标题】:unable to display spring mvc validation errors无法显示 spring mvc 验证错误
【发布时间】:2017-07-07 18:37:31
【问题描述】:

我正在学习 spring mvc 并且卡在 spring mvc 的文本字段下显示验证错误消息。
这里是控制器。在 updateUser() 方法中,我想对验证错误进行编码。

@Controller
public class ReportsController {

@Autowired
private ReportsDAO reportsDAO;

@Autowired
MyValidationUtils myValidationUtils;

public void setReportsDAO(ReportsDAO reportsDAO) {
    this.reportsDAO = reportsDAO;
}

@RequestMapping(value="/reports",method=RequestMethod.GET)
public ModelAndView report(){
    List<User> userList=reportsDAO.showAll();
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("Reports");
    modelAndView.addObject("userList", userList);
    modelAndView.addObject("User", new User());
    return modelAndView;
}

@RequestMapping(value="/update/{id}", method=RequestMethod.GET)
public ModelAndView reportUpdate(@PathVariable("id") String id){
    User user=reportsDAO.showByUCode(id);
    List<User> userList=reportsDAO.showAll();
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("Reports");
    modelAndView.addObject("userList", userList);
    modelAndView.addObject("User", user);
    if(user!=null){
        modelAndView.addObject("editUser", user);
    }
    return modelAndView;
}
@RequestMapping(value="/delete/{id}", method=RequestMethod.GET)
public ModelAndView reportDelete(@PathVariable("id") String id){
    int result=reportsDAO.deleteByID(id);
    ModelAndView modelAndView=new ModelAndView();
    modelAndView.setViewName("redirect:/reports");
    return modelAndView;
}

@InitBinder
protected void initBinder(WebDataBinder binder) {
    binder.setValidator(myValidationUtils);
}


@RequestMapping(value="/reportUpdate",method=RequestMethod.POST)
public ModelAndView updateUser(@ModelAttribute @Validated User user,BindingResult results,RedirectAttributes redirectAttributes){

    ModelAndView modelAndView=new ModelAndView();
    if(results.hasErrors()){
        modelAndView.setViewName("Reports");
        modelAndView.addObject("User", user);
        results.rejectValue("name", "Name cannot be empty.");
        return modelAndView;
    }
    if(user!=null){
        int result=reportsDAO.updateByCode(user);
        if(result!=-1){
            modelAndView.setViewName("redirect:/reports");
        }else{
            modelAndView.setViewName("Reports");
            modelAndView.addObject("message", "Unable to edit, Please try again.");
        }
    }else{
        modelAndView.setViewName("Reports");
        modelAndView.addObject("message", "Unable to edit, Please try again.");
    }

    return modelAndView;
}
}  

这里是jsp表单。

<form:form action="/ORMWebApp/reportUpdate" modelAttribute="User"
            method="post" class="form-style-9">
            <ul>
                <li><%-- <form:label path="ucode">UCODE</form:label> --%> <form:input type="hidden" path="ucode"
                         class="field-style field-full align-none"
                        placeholder="UCode" value="${editUser.ucode}" /> <form:errors
                        path="ucode" class="field-style field-full align-none"></form:errors></li>

                <li>
                <spring:bind path="name">
                <form:label path="name">NAME</form:label> <form:input type="text" path="name"
                         class="field-style field-full align-none"
                        placeholder="Name" value="${editUser.name}" /> <form:errors
                        path="name" class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="email">
                <form:label path="email">EMAIL</form:label> <form:input type="email" path="email"
                         class="field-style field-full align-none"
                        placeholder="Email" value="${editUser.email}" /> <form:errors
                        path="email" class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="address">
                <form:label path="address">ADDRESS</form:label> <form:input type="text"
                        path="address" 
                        class="field-style field-full align-none" placeholder="Address"
                        value="${editUser.address}" /> <form:errors path="address"
                        class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="password">
                <form:label path="password">PASSWORD</form:label> <form:input type="password"
                        path="password" 
                        class="field-style field-full align-none" placeholder="Password"
                        value="${editUser.password}" /> <form:errors path="password"
                        class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li>
                <spring:bind path="about">
                <form:label path="about">ABOUT</form:label> <form:textarea path="about"
                         class="field-style" placeholder="About" ></form:textarea>
                        <form:errors path="about"
                        class="field-style field-full align-none"></form:errors></spring:bind></li>
                <li><input type="submit" value="UPDATE" /></li>
            </ul>
        </form:form>  

这里是验证工具类。

public class MyValidationUtils implements Validator{

@Override
public boolean supports(Class<?> arg0) {

    return User.class.equals(arg0);
}

@Override
public void validate(Object target, Errors errors) {

    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotNull.user.name", "Name cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotNull.user.address", "Address cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotNull.user.email", "email cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotNull.user.password", "password cannot be blank.");
    ValidationUtils.rejectIfEmptyOrWhitespace(errors, "about", "NotNull.user.about", "About cannot be blank.");

}
}    

这是我在表单中返回验证错误所缺少的东西。提前致谢。

【问题讨论】:

    标签: java spring-mvc bean-validation


    【解决方案1】:

    问题是我没有正确绑定模型属性,也没有返回结果。这对我有用。

    @RequestMapping(value="/reportUpdate",method=RequestMethod.POST)
    public ModelAndView updateUser(@ModelAttribute("User") @Validated User user,BindingResult results,RedirectAttributes redirectAttributes){
    
        ModelAndView modelAndView=new ModelAndView();
        //myValidationUtils.validate(user, results);
        if(results.hasErrors()){
            return new ModelAndView("Reports", "User", user);
        }
        if(user!=null){
            int result=reportsDAO.updateByCode(user);
            if(result!=-1){
                modelAndView.setViewName("redirect:/reports");
            }else{
                modelAndView.setViewName("Reports");
                modelAndView.addObject("message", "Unable to edit, Please try again.");
            }
        }else{
            modelAndView.setViewName("Reports");
            modelAndView.addObject("message", "Unable to edit, Please try again.");
        }
    
        return modelAndView;
    }
    

    并且必须在 MyValidationUtils 中编写。

    @Override
    public void validate(Object target, Errors errors) {
        User user=(User)target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "name", "NotNull.user.name", "Name cannot be blank.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "address", "NotNull.user.address", "Address cannot be blank.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "email", "NotNull.user.email", "email cannot be blank.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "password", "NotNull.user.password", "password cannot be blank.");
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "about", "NotNull.user.about", "About cannot be blank.");
    
    }
    

    并在资源文件夹中放置一个messages.properties。

    NotNull.user.name=Please fill name.
    NotNull.user.address=Please fill address.
    NotNull.user.email=Please fill email.
    NotNull.user.password=Please fill password.
    NotNull.user.about=Please fill about.
    

    并在 dispatcher-servlet 中创建一个 bean。

    <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
        <property name="basename">
            <value>messages</value>
        </property>
    </bean>
    <bean id="myValidationUtils" class="org.apedusoft.validator.MyValidationUtils"></bean>
    

    它会在 messages.properties 文件中返回值。但是由于我身边的一些jsp表单错误。验证错误消息仅针对名称返回两次,但对于电子邮件等工作正常。

    【讨论】:

      【解决方案2】:

      基于 Spring 文档,默认模型属性名称是从声明的属性类型(即方法参数类型或方法返回类型)中推断出来的。

      所以,回到你原来的代码@ModelAttribute @Validated User user,这个属性将被命名为user。问题是在你的jsp中你有&lt;form modelAttribute="User"(大写U)。

      在您的回答中,您已经提交了将模型名称明确设置为“用户”的代码,这就是它起作用的原因: @ModelAttribute("User") @Validated User user

      【讨论】:

        猜你喜欢
        • 2014-09-23
        • 2012-04-08
        • 2011-07-21
        • 2011-11-25
        • 2014-10-17
        • 2017-01-25
        • 2011-01-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多