发布时间:2022-11-09 文章分类:编程知识 投稿人:李佳 字号: 默认 | | 超大 打印

注意!

无论是request,session,application必须先调用setAttribute得到保存作用域中保存数据

request:一次请求响应范围

@WebServlet("/demo01")
public class Demo01Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setAttribute("uname","request保存作用域");
        request.getRequestDispatcher("demo02").forward(request,response);
    }
}
@WebServlet("/demo02")
public class Demo02Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Object unameObj = request.getAttribute("uname");
        System.out.println("unameObj = " + unameObj);
    }
}

使用request保存作用域必须每次先调用demo01获取数据才能在demo02中获取到demo01中保存的数据(从demo01请求转发/地址重定向到demo02)

session:一次会话范围有效

@WebServlet("/demo03")
public class Demo03Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.setAttribute("uname","session保存作用域");
        response.sendRedirect("demo04");
    }
}
@WebServlet("/demo04")
public class Demo04Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        Object unameObj = session.getAttribute("uname");
        System.out.println("unameObj = " + unameObj);
    }
}

一次会话可以简单理解为一个(谷歌)浏览器,只要在某一(谷歌)浏览器保存了作用域的信息,无论demo03通过地址重定向/请求转发还是手动输入demo04地址跳转都能获取demo03的保存作用域的信息。期间如果更换了(Edge)浏览器或者将此(谷歌)浏览器关闭了再打开即本来的sessionID丢失生成新的sessionID,这种情况下就需要重写访问demo03获取作用域的信息才能在demo04中获取信息

application: 一次应用程序范围有效

@WebServlet("/demo05")
public class Demo05Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.向application保存作用域保存数据
        //ServletContext : Servlet上下文
        ServletContext application = request.getServletContext();
        application.setAttribute("uname","session保存作用域");
        response.sendRedirect("demo06");
    }
}
@WebServlet("/demo06")
public class Demo06Servlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletContext application = request.getServletContext();
        Object unameObj = application.getAttribute("uname");
        System.out.println("unameObj = " + unameObj);
    }
}

一次应用程序可以理解为一个服务器Tomcat,只要某一(谷歌)浏览器通过demo05生成了了作用域信息即使更换(Edge)浏览器或者重启此(谷歌)浏览器访问demo06都能得到demo05保存的作用域信息