How to show error message on same page in spring MVC

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

    
        ...
        
        
        ...
    
    

    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.

提交回复
热议问题