Spring 4 mvc RedirectView,带有BindingResult错误以及RedirectAttributes和ModelAttribute

时间:2016-04-27 07:01:47

标签: spring jsp spring-mvc modelattribute

我有控制器(POST | GET)和jsp视图表单(添加人)

如果我有错误,如何进行重定向 - 在INPUT字段中查看页面上的错误? bindingResult.hasErrors()== true?

如果确定,我看到成功 FlashAttribute

如果我有错误,我会看到FlashAttribute 错误,但我没有看到错误字段INPUT

   <form:form id="data" action="/addUserProfile" method="POST" modelAttribute="userProfile" commandName="userProfile">
       <p><pre><code>${errorMessage}</code></pre></p>
       <p><pre><code>${id}</code></pre></p>
       <p><pre><code>${successMessage}</code></pre></p>
        <table>
            <tr>
                <td><form:label path="phone">phone</form:label></td>
                <td><form:input path="phone"/></td>
                <td><form:errors path="phone" cssClass="error"/></td>
            </tr>
            <tr>
                <td><form:label path="firstname">firstname</form:label></td>
                <td><form:input path="firstname"/></td>
                <td><form:errors path="firstname" cssClass="error"/></td>
            </tr>
            <!--submit -->
            <tr>
            <td><input type="submit" value="submit"/></td>
          </tr>
       </table>
     </form:form>

并查看addUserProfile.jsp

 @RequestMapping(
            value = "/addUserProfile",
            method = RequestMethod.POST
    )
    public RedirectView addUserProfile(HttpServletRequest request,
            @Valid @ModelAttribute("userProfile") UserProfile userProfile,
            BindingResult bindingResult,
            RedirectAttributes redirectAttrs) {

        RedirectView redirectView = new RedirectView(request.getRequestURI());

        if (bindingResult.hasErrors()) {
            redirectAttrs.addFlashAttribute("errorMessage","error");
            redirectView.setContextRelative(true);
        } else {
             redirectAttrs.addFlashAttribute("successMessage","success");

            long id = userService.add(userProfile);
            redirectAttrs.addFlashAttribute("id",id);
        }



        return redirectView;
    }

如何重定向到

public class UserProfile {
    @NotEmpty
    @Size(min = 9, max = 20)
    private String phone;
    @NotEmpty
    @Size(min = 3, max = 20)
    private String firstname;
}

验证对象表单

{{1}}

0 个答案:

没有答案