编程自学指南:java程序设计开发,JavaWeb Servlet 与 application、session 内置对象关系学习笔记

编程自学指南:java程序设计开发,JavaWeb Servlet 与 application、session 内置对象关系学习笔记

Servlet 与 application

一、核心概念与生活类比

定义

  • Servlet:处理请求的核心组件(如银行柜员处理业务)
  • application:代表整个 Web 应用的上下文(如银行的总行数据库)

生活类比

  • application → 图书馆的公告栏
    • 所有读者(Servlet)都可以查看公告内容(共享数据)
    • 公告内容在图书馆开放期间持久存在(应用生命周期)

二、核心关系与协作案例

1. 获取 application 对象

方法

ServletContext application = getServletContext();

案例:读取全局配置

@WebServlet("/config")
public class ConfigServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        String appName = application.getInitParameter("appName");
        resp.getWriter().write("应用名称:" + appName);
    }
}

2. 共享全局数据

场景:统计网站总访问量

@WebServlet("/counter")
public class CounterServlet extends HttpServlet {
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) {
        int count = (int) application.getAttribute("count");
        application.setAttribute("count", ++count);
        resp.getWriter().write("总访问量:" + count);
    }
}

3. 访问资源文件

场景:读取位于 WEB-INF/conf/db.properties 的配置文件

InputStream inputStream = application.getResourceAsStream("/WEB-INF/conf/db.properties");
Properties props = new Properties();
props.load(inputStream);

三、生命周期协作

1. Servlet 初始化时设置全局数据

public void init() {
    application.setAttribute("dataSource", createDataSource());
}

2. Servlet 销毁时清理资源

public void destroy() {
    DataSource dataSource = (DataSource) application.getAttribute("dataSource");
    dataSource.close();
}

四、线程安全注意事项

问题:application 是单例,成员变量共享
解决方案

  1. 使用 AtomicInteger 统计访问量
  2. 避免在 application 中存储可变对象

案例

application.setAttribute("counter", new AtomicInteger(0));
AtomicInteger counter = (AtomicInteger) application.getAttribute("counter");
counter.incre
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zl515035644

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值