四个常用的域对象

四个常用的域对象

:看了下web课上的PPT,我承认之前太大声了╥﹏╥

四大域对象

常用的四大域,即pageContext,request,session,application

功能:都是存取数据,但对数据的存取范围不同

代码

除xml的配置方式还可以用

注解的方式映射路径

@WebServlet(name = "ActionScope",urlPatterns = "/index")
  • 创建ActionScope类
@WebServlet(name = "ActionScope",urlPatterns = "/index")
public class ActionScope extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("来过此类");
        //        获取session对象
        HttpSession session = req.getSession();
//        获取servletContext对象,即jsp的application对象
        ServletContext servletContext = this.getServletContext();

//        存数据
        req.setAttribute("reqKey","存在request中的数据");
        session.setAttribute("sessionKey","存在session中的数据");
        servletContext.setAttribute("applicationKey","存在servletContext中的数据");
        req.getRequestDispatcher("index.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
  • index.jsp代码
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>域对象</title>
</head>
<body>
<%
    pageContext.setAttribute("pageContextKey","保存在pageContext对象中的数据");
%>
<%= pageContext.getAttribute("pageContextKey") %> <br>
<%= request.getAttribute("reqKey") %> <br>
<%= session.getAttribute("sessionKey") %> <br>
<%= application.getAttribute("applicationKey") %> <br>
</body>
</html>
  • index02.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>域对象</title>
</head>
<body>
    <%= pageContext.getAttribute("pageContextKey") %> <br>
    <%= request.getAttribute("reqKey") %> <br>
    <%= session.getAttribute("sessionKey") %> <br>
    <%= application.getAttribute("applicationKey") %> <br>
    <a href="index03.jsp">跳转到index03.jsp页面</a>
</body>

</html>
  • index03.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%= pageContext.getAttribute("pageContextKey") %> <br>
<%= request.getAttribute("reqKey") %> <br>
<%= session.getAttribute("sessionKey") %> <br>
<%= application.getAttribute("applicationKey") %> <br>
</body>
</html>
运行tomcat
  • 初始页面

结论:
pageContext存取范围只能在当前jsp页面

  • url栏输入index

得到

  • url栏输入index.jsp

得到

结论:
request只在一次请求内有效

  • url栏输入

得到!

  • 点击跳转index03.jsp

结论:
session和context都能在一次会话范围内有效

  • 关闭浏览器
  • url栏输入index02.jsp

得到

查看index03.jsp

结论:
servletContext整个web工程内都有效

结论

posted on 2023-01-08 23:25  lsyorha  阅读(67)  评论(0编辑  收藏  举报