# 5.SpringMVC-共享域对象

# 1.使用servletAPi向request域对象共享数据

    @RequestMapping("/testScopeByServletAPI")
    public String testScope(HttpServletRequest  request){
        request.setAttribute("testRequestScope","hello ServletAPI");
        return "success";
    }
1
2
3
4
5

# 2.使用ModelAndView向request域对象共享数据

@RequestMapping("/testScopeByModelAndView")
    public ModelAndView testScopeByModelAndView(){
        /*
        ModelAndview有Model和view的功能
        Model主要用于向请求域共享数据
        View主要用于设置视图,实现页面跳转
         */
        ModelAndView mav = new ModelAndView();

        //向请求域共享数据
        mav.addObject("testRequestScope","hello ModelAndView");
        //设置逻辑视图名
        mav.setViewName("success");
        return mav;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 3.使用Model向request域对象共享数据

@RequestMapping("/testScopeByModel")
    public String testScopeByModel(Model model){
        //向请求域共享数据
        model.addAttribute("testRequestScope","hello Model");
        return "success";
    }
1
2
3
4
5
6

# 4.使用map向request域对象共享数据

    @RequestMapping("/testScopeByMap")
    public String testScopeByMap(Map<String,Object>  map){
        map.put("testRequestScope","hello Map");
        return "success";
    }
1
2
3
4
5

# 5.使用ModelMap向request域对象共享数据

    @RequestMapping("/testScopeByModelMap")
    public String testScopeByModelMap(ModelMap map){
        map.put("testRequestScope","hello ModelMap");
        return "success";
    }
1
2
3
4
5

# 6.Model、ModelMap、Map的关系

Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的

public interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}
1
2
3
4

# 7.向session域中共享数据

    @RequestMapping("/testScopeBySession")
    public String testScopeBySession(HttpSession session){
        session.setAttribute("testRequestScope","hello Session");
        return "success";
    }
1
2
3
4
5

# 8.向application域中共享数据

    @RequestMapping("/testScopeByApplication")
    public String testScopeByServletContext(HttpSession session){
        session.getServletContext().setAttribute("testRequestScope","hello Application");
        return "success";
    }
1
2
3
4
5

最近更新: 9/19/2026, 1:27:08 PM
编程NOTE   |