【问题标题】:form validation error message doesn't show spring mvc thymeleaf表单验证错误消息不显示 spring mvc thymeleaf
【发布时间】:2015-07-30 04:16:00
【问题描述】:

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

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

我的 spring 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; 
        } 

    } 

【问题讨论】:

    标签: java spring spring-mvc thymeleaf


    【解决方案1】:

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

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

    public class User {
    
        @NotNull
        private String first_name;
    
    }
    

    【讨论】:

    • 是的,我有这个甚至检查大小
    • 不确定它是否会影响任何东西,但为什么 th:errors="${user.first_name}"?为什么不 th:errors="*{first_name}"?
    • @Link 是对的。正确的方法是th:errors="*{first_name}"
    • 你认为重定向刷新一切吗
    • 不使用重定向怎么样?这是我通常可以看到的唯一其他区别(除了 th:errors)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 1970-01-01
    • 2014-10-17
    • 1970-01-01
    • 2012-04-08
    • 1970-01-01
    • 2020-09-18
    相关资源
    最近更新 更多