Servlet中三大作用域的区别

servlet中三个重要的对象request,session,application在页面间的传值有着重要作用,其作用域如下:


三大作用域对照表.png
具体的代码测试如下:
@WebServlet("/scope01")
public class TestScope01 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    
        request.setAttribute("name", "zhangsan");
        //request.getRequestDispatcher("scope02").forward(request, response);
        
        request.getSession().setAttribute("age", 25);
        
        request.getServletContext().setAttribute("address", "天河区");
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

@WebServlet("/scope02")
public class TestScope02 extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        Object name = request.getAttribute("name");
        System.out.println(name);
        
        Object age = request.getSession().getAttribute("age");
        System.out.println(age);
        
        Object address = request.getServletContext().getAttribute("address");
        System.out.println(address);
        
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }

}

你可能感兴趣的:(Servlet中三大作用域的区别)