Java – spring MVC sets the attribute to request / model / modelmap
I use spring MVC I need to add properties to requests or other objects It should be a message that will be displayed on the screen For example, if I use pure servlets, I might just:
request.setAttribute("message","User deleted");
Not on JSP pages
<div id="message">${message}</div>
But when I try to do this in my method:
@RequestMapping(value = "/delete",method = RequestMethod.GET) public String deleteUser(@RequestParam("login") String login,ModelMap map,HttpServletRequest request)
Model objects –
model.addAttribute("message","User deleted");
Maps –
map.put("message","User deleted");
ModelMap –
map.put("message","User deleted");
HttpServletRequest –
request.setAttribute("message","User deleted");
Not shown But in my browser, I see: http: / / localhost: 8081 / project / index? Message = user delete
How to solve this small problem? Thank you for your answer
to update:
For a clear understanding, I try to do this:
@RequestMapping(value = "/delete",Model model) { dao.delete(login); // there is NO exeptions map.addAttribute("message","User " + login + " deleted"); return "redirect:" + "index"; }
In my JSP, I also display user login in this way:
${user.login}
It requires the user to log in from the session and I see it
Solution
With your new information, the problem is redirection: When you redirect, you will send an HTTP response with 302 (or 301) response code, and the "location" title points to the new URL The browser will send a new HTTP request to the location Therefore, your request properties (and model properties) are no longer good and do not exist in the new request
Consider using the flash attribute The redirectattributes class is the way to go The javadoc has a good example.
During request processing, the model property will be added to the request property later So you won't see it directly
@RequestMapping(value = "/delete",HttpServletRequest request) map.put("message","User deleted"); String message = (String) request.getAttribute("message"); // will return null ... }
Just believe that it will eventually be in the request attribute, so it can be used in your JSP