How to show error message on same page in spring MVC

前端 未结 2 1624
青春惊慌失措
青春惊慌失措 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.

    
       Error: ${error}
    
    

    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;
    
    });
    

提交回复
热议问题