编程自学指南: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 是单例,成员变量共享
解决方案:
- 使用
AtomicInteger
统计访问量 - 避免在 application 中存储可变对象
案例:
application.setAttribute("counter", new AtomicInteger(0));
AtomicInteger counter = (AtomicInteger) application.getAttribute("counter");
counter.incre