表单验证错误消息不显示spring mvc thymeleaf

时间:2015-07-30 04:16:00

标签: java spring spring-mvc thymeleaf

我添加了用户表单,不显示百里香的错误信息。我尝试阅读其他解决方案并在此论坛中应用其他解决方案,但仍然无效。

**userform.html** 

 <form  id="adduser" role="form"  th:action="@{/adduser}" method="post" th:object="${user}">


    <div class="form-group">
                                        <label>First Name</label>
                                        <input class="form-control" th:field="*{first_name}"/>

                                          <p th:if="${#fields.hasErrors('first_name')}" th:errors="${user.first_name}">First name is mandatory</p>
                                    </div>
<button type="submit" name="action" value="adduser" class="btn btn-default" onclick="myFunction()">Submit</button>

  </form>

我的春季MVC控制器

UserformController.java

// Returns the view with model attached 
     @RequestMapping(value = "/userform", method = RequestMethod.GET) 
     public ModelAndView showuser(HttpServletRequest request, HttpServletResponse response) { 
        LOGGER.info("in get adduser"); 

        ModelAndView mav = new ModelAndView(); 

        mav.setViewName("userform"); 
        mav.addObject("user", new User()); 

        return mav; 

    } 

//Save 

    @RequestMapping(value = "/adduser", method = RequestMethod.POST) 
    public ModelAndView adduser(@Valid @ModelAttribute("userForm")  Userform user, BindingResult result, @RequestParam(value="action", required=true) String action) { 


        ModelAndView mav = new ModelAndView(); 

        if (result.hasErrors()) { 

            mav.setViewName("redirect:userform"); 
            mav.addObject("user", user); 
            return mav; 
        } 
else { 
            utilService.insert(user); 

            mav.setViewName("redirect:userlist"); 

            return mav; 
        } 

    } 

1 个答案:

答案 0 :(得分:0)

您是否在User类中定义了任何约束?请显示用户类。

错误将基于User类属性中的约束,所以应该有这样的东西

public class User {

    @NotNull
    private String first_name;

}