栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 系统运维 > 运维 > Linux

servlet三大作用域 session ,request,application ,Javaweb

Linux 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

servlet三大作用域 session ,request,application ,Javaweb

Servlet中的三大域对象 共同的功能 存值/取值
getAttribute 存值
setAttribute 取值
1.request 请求域 使用范围: 一次请求
@WebServlet("/as")
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        

        
        req.setAttribute("salary",10000);
       
    }
}
@WebServlet("/bs")
public class BServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
       

        
        Object salary = req.getAttribute("salary");
        System.out.println(salary);

    }
}
2.session 会话域 使用范围: 多次请求
@WebServlet("/cs")
public class CServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("====在cs中向session域存值====");
        req.getSession().setAttribute("salary",1000000);

    }
}
@WebServlet("/ds")
public class DServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("====在ds中从session域取值====");
        Object salary = req.getSession().getAttribute("salary");
        System.out.println(salary);
    }
}
3.application 全局域 使用范围:与服务器相同寿命
@WebServlet("/es")
public class EServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("====在es中向application域存值====");
        req.getSession().getServletContext().setAttribute("salary",123456);
    }
}
@WebServlet("/fs")
public class FServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        System.out.println("====在fs中从application域中取值====");
        Object salary = req.getSession().getServletContext().getAttribute("salary");
        System.out.println(salary);
    }
}
去浏览器输入:






输出的结果:




发现:

request只能用一次

session在网页没有关闭的时候可以一直使用,但关闭网页就不可以

application在网页上可以一直使用,浏览器从新打开也可以继续使用,直到关闭服务器不可以使用

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/618705.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号