学习java,挺好玩的呢

 

一、SpringMVC 作用域传值的几种方式

   使用原生Servlet

    1.1 在 HandlerMethod 参数中添加作用域对象

        1.1.1 ServletContext不能在方法参数中获取,只能在request中获取

@Controller
public class DemoController {
        @RequestMapping("demo")
        public String demo(HttpServletResponse resp,HttpServletRequest req,HttpSession session){
            //Request
            req.setAttribute("request", "这是HttpServletRequest");
            //Session
            session.setAttribute("session","这是HttpSession");
            HttpSession session2=req.getSession();
            session2.setAttribute("session2","这是HttpSession22");
            //application
            ServletContext context = req.getServletContext();
            context.setAttribute("servletcontext","这是ServletContext");
            return "/index.jsp";
        }
}

  2  使用Map集合

    2.1 把map中内容放在 request 作用域中

    2.2 spring 会对map集合通过  spring中的 class org.springframework.validation.support.BindingAwareModelMap 进行实例化

        @RequestMapping("demo2")
        public String demo2(Map<String,Object> map){
            System.out.println(map.getClass());
            map.put("map","天使");
            return "/index.jsp";
        }


  index.jsp中
    map:::${requestScope.map} 进行获取    (可以不使用requestScope)

  3 使用SpringMVC 中的Model接口

    3.1 本质还是 request作用域进行传值,(Model存在的意义就是替换request)

    3.2 把内容最终放入到request作用域中 

        @RequestMapping("demo3")
        public String demo3(Model model){
            model.addAttribute("model","这是Model的值");
            return "/index.jsp";
        }

  index.jsp 中
  model:::${requestScope.model} 获取

  4 使用SpringMVC中ModelAndView 类

        @RequestMapping("demo4")
        public ModelAndView demo4(){
            ModelAndView mac=new ModelAndView("/index.jsp");
            mac.addObject("mav","天使的ModelAnd view");
            return mac;
        }
index.jsp中
modelandview::${requestScope.mav}

 

posted on 2018-12-23 21:21  axu521  阅读(1643)  评论(0编辑  收藏  举报

<