跳转至

域对象共享数据

使用ServletAPI向request域对象共享数据

@RequestMapping("/test/rest/{username}/{id}")  
public String testRest(@PathVariable("id") Integer id, @PathVariable("username") String username){  
    System.out.println("username:"+username + "id:"+id);  
    return "success";  
}

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

  • ModelAndView包含了
    • Model:向请求域中共享数据
    • View:设置视图,实现页面跳转
      @RequestMapping("/test/mav")  
      public ModelAndView testmav(){
          ModelAndView mav = new ModelAndView();  
          mav.addObject("mav", "hello mav");  
          mav.setViewName("success");  
          return mav;  
      }
      

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

@RequestMapping("/test/model")  
public String testModel(Model model){  
    model.addAttribute("test", "hello model");  
    return "success";  
}

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

@RequestMapping("test/map")  
public String testMap(Map<String , String> map){  
    map.put("test", "hello map");  
    return "success";  
}

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 {}
    

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

@RequestMapping("test/modelMap")  
public String testModelMap(ModelMap modelMap){  
    modelMap.addAttribute("test", "hello model map");  
    return "success";  
}

向session域共享数据

建议直接使用ServletAPI

  • 与浏览器有关
    @RequestMapping("test/session")  
    public String testSession(HttpSession session){  
        session.setAttribute("test1", "hello session");  
        return "success";  
    }
    

向application域共享数据

sessionrequest都可以获取ServletContext

  • 与服务器有关
    @RequestMapping("test/application")  
    public String testApplication(HttpSession session){  
        ServletContext application = session.getServletContext();  
        application.setAttribute("test2", "hello application");  
        return "success";  
    }