controller中的四大作用域

request、session、application

  • 参数为HttpServletRequest 就可以拿到request
  • 通过request可以拿到session,session也是可以通过设置参数拿到的
  • 通过request可以拿到application,application不允许通过参数拿到
@RequestMapping("demo1")
	public String demo(HttpServletRequest abc){
    
    
		abc.setAttribute("a", "a的值");
		HttpSession session = abc.getSession();
		session.setAttribute("b", "b的值");
		
		ServletContext application = abc.getServletContext();
		application.setAttribute("c", "c的值");
		return "index";
	}

request的其他变形

参数设置为map,放一个键值对,实际上用的还是request.setAttribute

@RequestMapping("demo2")
	public String demo2(Map<String,Object>map){
    
    
		map.put("map", "map的值");
		return "index";
	}

底层作用域仍然是request,换汤不换药

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

依然是request,只不过加入了视图功能,返回值类型为ModelAndView,创建对象时设置跳转的jsp,addObject等效req.setAttribute

@RequestMapping("demo4")
	public ModelAndView demo4(){
    
    
		ModelAndView mav=new ModelAndView("index");
		mav.addObject("mav", "mav的值");
		return mav;
	}

复习jsp中获取作用域中的值

下边每个键值对在取出的时候,可以不加xxxScope,加上表明从哪个作用域中取出,不加的话就通过名称寻找,从最小的作用域开始找,找到一个就停止

	request:${requestScope.a}<br>
	session:${sessionScope.b}<br>
	application:${applicationScope.c}<br> 
	map:${requestScope.map}<br> 
	model:${requestScope.model }<br> 
	modelAndView:${requestScope.mav}<br> 

猜你喜欢

转载自blog.csdn.net/WA_MC/article/details/113108499