How to show error message on same page in spring MVC

前端 未结 2 1630
青春惊慌失措
青春惊慌失措 2021-02-04 13:20

I am calling a controller in spring mvc with form data.

Before saving, I check if the id is a certain range. If the id is not within the range, I need to show a message

相关标签:
2条回答
  • 2021-02-04 13:39

    A simple approach would be to add your error message as a model attribute.

    @RequestMapping(value = "/sendMessage")
    public String sendMessage(@ModelAttribute("message") Message message,
            final HttpServletRequest request, Model model) {
    
        boolean check = userLoginService.checkForRange(message.getUserLogin());
        if(!check){
            model.addAttribute("error", "The id selected is out of Range, please select another id within range");
            return "yourFormViewName";
        }
    }
    

    Then your jsp can display the "error" attribute if it exists.

    <c:if test="${not empty error}">
       Error: ${error}
    </c:if>
    

    Edit

    Here's a rough, untested implementation of validation over ajax. JQuery assumed.

    Add a request mapping for the ajax to hit:

    @RequestMapping("/validate")
    @ResponseBody
    public String validateRange(@RequestParam("id") String id) {
    
        boolean check = //[validate the id];
        if(!check){
            return "The id selected is out of Range, please select another id within range";
        }
    }
    

    Intercept the form submission on the client side and validate:

    $(".myForm").submit(function(event) {
    
        var success = true;
    
        $.ajax({
            url: "/validate",
            type: "GET",
            async: false, //block until we get a response
            data: { id : $("#idInput").val() },
            success: function(error) {
                if (error) {
                    $("#errorContainer").html(error);
                    success = false;
                }
            }
        });
    
        return success;
    
    });
    
    0 讨论(0)
  • 2021-02-04 13:44

    You can also use the existing error messages support. This way you can use the spring-mvc error tags to show the error at a global context or even at the field level. For example, if you pretend to bind the error to the field, you can use:

    @RequestMapping(value = "/sendMessage")
    public String sendMessage(@ModelAttribute("message") Message message, BindingResult bindingResult) {
        boolean check = userLoginService.checkForRange(message.getUserLogin());
        if (!check) {
            bindingResult.rejectValue("userLogin", "error.idOutOfRange", "The id selected is out of Range, please select another id within range");
            return "jspPage"; // path to the jsp filename, omit extension (considering default config) 
        }
    }
    

    At the page level, you can do:

    <form:form method="POST" commandName="message">
        ...
        <form:input path="userLogin" />
        <form:errors path="userLogin" />
        ...
    </form:form>
    

    If you just want to show a global error, omit the parameter name at bindingResult.rejectValue and form:errors tag.

    Note: you do not need to worry about recovering parameters manually. In normal conditions, spring-mvc will handle that for you.

    Hope it helps.

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