简体   繁体   English

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

[英]form validation error message doesn't show spring mvc thymeleaf

I have add user form doesn't display the error message with thymeleaf. 我已添加用户表单,但不与thymeleaf显示错误消息。 I try to read other solutions and apply other solutions in this forum but still doesn't work. 我尝试在该论坛上阅读其他解决方案并应用其他解决方案,但仍然无法正常工作。

**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>

My spring MVC controller 我的Spring MVC控制器

UserformController.java 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; 
        } 

    } 

Did you define any constraints in the User class? 您是否在User类中定义了任何约束? Please show the User class. 请显示用户类别。

The errors would be based on the constraints in the properties of the User class, so there should be something like this 错误将基于User类的属性中的约束,因此应该有类似这样的内容

public class User {

    @NotNull
    private String first_name;

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM