JSP 九大内置对象和四大作用域复习
JSP九大内置对象
名称 |
类型 |
含义 |
获取方式 |
request |
HttpServletRequset |
封装所有请求信息 |
方法参数 |
response |
HttpServletResponse |
封装所有相应信息 |
方法参数 |
session |
HttpSession |
封装所有会话信息 |
req.getSession() |
application |
ServletContext |
所有信息 |
getServletContext(); requset.getServletContext; |
out |
PrintWriter |
输出对象 |
response.getWriter() |
exception |
Exception |
异常对象 |
|
page |
Object |
当前页面对象 |
|
pageContext |
pageContext |
获取其他信息 |
|
config |
ServletConfig |
配置信息 |
|
四大作用域
page
在当前页面不会重新实例化。作用域当前页面
request
在一次请求中同一个对象,下次请求重新实例化一个request 对象.
session
- 一次会话.
- 只要客户端Cookie中传递的Jsessionid不变,Session不会重新实例化(不超过默认时间.)
- 实际有效时间:浏览器关闭.Cookie 失效.
- 默认时间.在时间范围内无任何交互.在 tomcat 的web.xml 中配置
1 2 3
| <session-config> <session-timeout>30</session-timeout-> </session-config>
|
application
只有在 tomcat 启动项目时才实例化.关闭 tomcat 时销毁 application
SpringMVC 作用域传值的几种方式
index.jsp

使用原生Servlet
在 HanlderMethod 参数中添加作用域对象


使用Map集合
- 把map内容放在request作用域中
- spring 会对 map 集合通过 BindingAwareModelMap 进行实例化

使用SpringMVC中Model 接口
把内容最终放入到 request 作用域中.


使用 SpringMVC 中 ModelAndView 类
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> request:${requestScope.req}<br> session:${sessionScope.session}<br> sessionParam:${sessionScope.sessionParam}<br> application:${applicationScope.application} <hr> map:${requestScope.map} <hr> model:${requestScope.model} <hr> mav:${requestScope.mav} </body> </html>
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
| package com.kylin.controller;
import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView;
import javax.servlet.ServletContext; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; import java.util.Map;
@Controller public class DemoController {
@RequestMapping("/demo1") public String demo1(HttpServletRequest abc, HttpSession sessionParam) { abc.setAttribute("req", "req的值"); abc.setAttribute("test", "@SessionAttributes"); HttpSession session = abc.getSession(); session.setAttribute("session", "session的值"); sessionParam.setAttribute("sessionParam", "sessionParam的值"); ServletContext application = abc.getServletContext(); application.setAttribute("application", "application的值"); return "/index.jsp"; }
@RequestMapping("/demo2") public String demo2(Map<String, Object> map) { map.put("map", "map的值"); return "/index.jsp"; }
@RequestMapping("/demo3") public String demo3(Model model) { model.addAttribute("model", "model的值"); return "/index.jsp"; }
@RequestMapping("/demo4") public ModelAndView demo4() { ModelAndView mav = new ModelAndView("/index.jsp"); mav.addObject("mav", "mav的值"); return mav; } }
|