SpringMVC several model objects

The role of model objects is mainly to hold data, which can be used to bring data to the front end.

Commonly used model objects are as follows:

  1. ModelAndView (as the name implies, models and views can carry both data information and view information, the general usage is as follows)

/**
* The return value of the target method can be of type ModelAndView. 
* It can contain view and model information
* SpringMVC will put the data in the model of ModelAndView into the request domain object. 
* @return
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
String viewName = SUCCESS;
ModelAndView modelAndView = new ModelAndView(viewName); //Add model data to ModelAndView. modelAndView.addObject("time", new Date()); return modelAndView;





}

2.Map, the same as the modelAndView principle, also puts the data one by one in the requestScope, and the front-end data is also ${model data}

/**
* The target method can add parameters of type Map (actually it can also be of type Model or ModelMap). 
* @param map
* @return
*/
@RequestMapping("/testMap")
public String testMap(Map<String, Object> map){
System.out.println(map.getClass().getName()); 
map.put("names", Arrays.asList("Tom", "Jerry", "Mike"));
return SUCCESS ;
}

3. @SessionAttributes (equivalent to creating a session object and putting data into the session object, here is a perfect solution with an annotation)

The basic format is as follows:

/**
* @SessionAttributes In addition to specifying the attributes that need to be placed in the session through the attribute name (actually using the value attribute value),
* you can also specify which model attributes need to be placed in the session through the object type of the model attribute ( The type attribute value is actually used)

* Note: This annotation can only be placed above the class . It cannot be modified to place methods. 

       Think of it as storing an entity class and a String class string in the map and session.

*/

@SessionAttributes(value={"user"}, types={String.class})

@RequestMapping("/testSessionAttributes")

public String testSessionAttributes(Map<String, Object> map){
User user = new User("Tom", "123456", "[email protected]", 15);
map.put("user", user);
map.put("school", "atguigu");
return SUCCESS;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324715846&siteId=291194637