Spring MVC: How to redirect to a page with error?

后端 未结 2 562
我在风中等你
我在风中等你 2021-01-15 10:32

I am trying to make my Controller to redirect to a page with a custom error message:

    @RequestMapping(method=RequestMethod.POST)
    public String process         


        
相关标签:
2条回答
  • 2021-01-15 10:59

    There's something wrong in your controller method. It would be better way to call getAllErrors() method from result than the getFieldErrors(). Of course if the result is BindingResult type . Like this:

    model.addAttribute("errors", result.getAllErrors());

    0 讨论(0)
  • 2021-01-15 11:16

    You can add the following section in your jsp--

    <c:choose>
    <c:when test="${not empty  errors}">
        <div class="error">
        <c:forEach items="${errors}" var="err">
            ${err.defaultMessage}
            <br/>
        </c:forEach>
        </div>
    </c:when>
    </c:choose>
    

    Here c is nothing but this--

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
    

    Also you need to pass the errors into the model and view like this inside the if block in your controller method--

    model.addAttribute("errors",result.getFieldErrors());
    

    error class in the DIV is nothing but my custom css to display as a red block--

    .error{
        color: red;
        border:2px solid red;
        padding:10px;
    
    }
    

    You can also have a look at this
    Hope my answer has helped you..

    0 讨论(0)
提交回复
热议问题