@ModelAttribute and @ SessionAttributes and @ SessionAttribute and @ RequestAttribute

Posted by everurssantosh on Thu, 24 Feb 2022 18:59:42 +0100

1, @ ModelAttribute

  1. usage
  1. Bind request parameters to command object (input parameter object): when placed on the input parameter of the controller method, it is used to bind multiple request parameters to a command object, so as to simplify the binding process, and is automatically exposed as model data for use in view page display; When the parameter type is a bean, it can be injected one by one according to the attributes of the bean@ ModelAttribute("LoginUser") User user
  2. Expose the form reference object as model data: when placed on the general method of the processor (non functional processing method, that is, the method without @ RequestMapping annotation), it is to prepare the form reference data object to be displayed for the form: such as the static information such as the city to be selected during registration. Before executing the function processing method (@ RequestMapping annotation method), it is automatically added to the model object for use in view page display; This method basically includes this method in a parent Controller, and then the subclass inherits it, so that all subclass controllers can automatically directly access dicts in the corresponding view without repeating each
  3. @When the ModelAttribute and @ RequestMapping annotations are applied to methods at the same time, they have the following functions:
  • The return value of the method will be stored in the Model object, and the key is the value attribute value of ModelAttribute.
  • The return value of the method is no longer the access path of the method, and the access path will become the value of @ RequestMapping. For example, @ RequestMapping(value = "/index") will jump to the page of index JSP page.
  1. Code example
abstract public class CommonController {
    @ModelAttribute
    public void  MyModelAttribute(Model model){
        model.addAttribute("model", "MyModel");
    }
    @ModelAttribute
    public void newUser(Model model){
        User user = new User();
        user.setName("myUser");
        user.setId(1);
        model.addAttribute("myUser", user);
    }
}
@Controller
public class MyController  {  
    @RequestMapping("init")
    @ResponseBody
    public String init(){
        return "init";
    }
    @RequestMapping("user")
    @ResponseBody
    public void getUser(@ModelAttribute("myUser")User user){
        System.out.println(user.toString());
    }
    @ModelAttribute("modelAndMapping")
    @RequestMapping("yes")
    public String modelAttributeAndRequestMapping(){
        return "yes1";
    }
}
  • yes.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>yes.jsp</title>
</head>
<body>
${modelAndMapping}
</body>
</html>

2, @ SessionAttributes and @ SessionAttributes

  1. Function: the function is to add the key value pair in the specified Model to the session, so that it can be used in the next request. This annotation can only be used on the class.

  2. @The parameters set by the SessionAttributes annotation can be used in three ways:

  1. In the view (such as jsp page, etc.) through request Getattribute () or session Getattribute get
  2. In the view returned by the later request, the session Getattribute or get it from model (this is also commonly used)
  3. Automatically set the parameter to the Model type parameter of the processor corresponding to the subsequent request or the parameter with @ ModelAttribute annotation (it should be our focus to use it together with @ ModelAttribute). Note that you can't get the attribute by using @ ModelAttribute in other controllers. You can get the attribute only by using @ ModelAttribute in this controller, In other controllers, you can use @ SessionAttribute to get
//Add the values with attrName "user","id","name" in the Model to the session through the @ SessionAttributes annotation
@SessionAttributes(value = {"user","id","name"})
@Controller
public class UserController {
    @ModelAttribute("user")
    public User login(){
        User user = new User();
        user.setName("loginYES");
        user.setId(2);
        return user;
    }
    @RequestMapping("newUser")
    public String testHandler(Model model){
        model.addAttribute("id",23);
        model.addAttribute("name","kk");
        return "result";
    }
    @ResponseBody
    @RequestMapping("iisLogin")
    //If you get it through @ SessionAttribute, you can get it normally
    public String isLogin(@ModelAttribute("user") User user) {
        if (user.getName() != null) {
            return "isLogin!";
        } else return "isLogin??";
    }
}
@Controller
public class MyController {
    @ResponseBody
    @RequestMapping("isLogin")
    public String isLogin(@ModelAttribute("user") User user,HttpSession httpSession){
        if(user.getName()!=null){
            return "isLogin!";
        }
        else return "isLogin??";
    }
}
  • result.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>result</title>
</head>
<body>
${sessionScope.user.id}
${sessionScope.user.name}
<br/>
${sessionScope.id}
${sessionScope.name}
</body>
</html>


@SessionAttributes is to set the model to the session.
@SessionAttribute is the data set in the session before being obtained from the session.

4, @ RequestAttribute

  1. Function: it is used for method input parameters to get the corresponding value from the request. As for how the attribute exists in the request, there are various ways. It is pre stored in the interceptor, pre stored in the ModelAttribute annotation, and brought by request forwarding.

When trying to access a value that does not exist in the request, @ RequestAttribute threw an exception:

@RequestMapping("/demo1")
    public String demo1(@RequestAttribute String name){
        System.out.println(name);
        return "test";
    }
  1. How to request the pre stored attribute in the request:
  • Mode 1 ModelAttribute annotation
@ModelAttribute
public void storeEarly(HttpServletRequest request){
    request.setAttribute("name","lvbinbin");
}
  • Mode II Request in interceptor setAttribute()
public class SimpleInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println(" Simple Interceptor preHandle");
        request.setAttribute("name",24);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println(" Simple Interceptor postHandle");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println(" Simple Interceptor afterCompletion");
    }
}
  • Mode III Request forwarding, which exists in the forwarded request attribute;
  1. @RequestAttribute attribute required

@The RequestAttribute attribute required defaults to true, request If getattribute cannot get the parameter, it will throw an exception ServletRequestBindingException; When required is set to false, skip is ignored even if it is not obtained from the request, and the assignment is null;

  1. @RequestAttribute and @ RequestParam and @ RequestBody
  • @The parameters of the RequestAttribute annotation are parsed by the project itself, not passed by the front end. Specifically, in the interceptor of the project, the Token information will be parsed, and the parsed parameters will be put back in the request (httpServletRequest.setAttribute(name,value)). This annotation will be used when the subsequent interface receives the parameters.
  • @The RequestParam annotation indicates that this parameter is passed through the front end. If there is no such parameter in the request, an error of 400 Bad Request will be reported. The parameter in the request path or post request is used to parse the parameter in the request form;
  • @The RequestBody annotation is used to receive the parameters in the POST request BODY in JSON format.

Reference articles

Topics: Java Front-end Spring Spring Boot mvc