黑马程序员javaweb教程:ServletContext

2026/4/29 23:30:05

6 存取项目(上下文)数据

ServletContext中可以存放项目共享数据。因为在一个项目中只有一个ServletContext对象,而且在Tomcat启动时就已经创建它,在Tomcat关闭时才会销毁它,所以它的生命周期是最长的!只要在ServletContext中存放了数据,只要不关闭,不重启Tomcat,那么数据就一直存在。

下面我们做一个小练习,需求如下:

在一个TXT文件中给出本网站的欢迎信息,然后在Tomcat启动时把文本内容添加到ServletContext中,当用户访问本网站时显示欢迎信息的内容。

步骤:

1. 创建TXT文件,例如:/WEB-INF/initdata/welcome.txt。内容如下: welcome.txt 您好,这里是XXX系统的欢迎信息,感谢您对XXX系统的大力支持! 2. 在web.xml文件中配置上下文初始化信息,指定欢迎文件路径。内容如下: web.xml initContextFile /WEB-INF/initdata/welcome.txt

3. 编写SetServlet,只给出init()方法,不给出doGet()和doPost()。让SetServlet在Tomcat

启动时完成创建Servlet!在init()方法中获取上下文初始化信息,找到欢迎文件,把欢迎文件中的数据加载到ServletContext对象中。内容如下:

SetServlet.java public class SetServlet extends HttpServlet { } public void init() throws ServletException { } private static String getText(String filePath) } } throws ServletException { return FileUtils.readFileToString(new File(filePath), \); throw new ServletException(e); try { } catch (IOException e) { ServletContext application = this.getServletContext(); String filePath = application.getInitParameter(\); filePath = application.getRealPath(filePath); String text = getText(filePath); application.setAttribute(\, text);

SetServlet cn.itcast.servlet.SetServlet 1

4. 编写GetServlet,给出doGet()或doPost()方法,获取ServletContext中保存的数据,

然后响应给客户端。内容如下:

GetServlet.java public void doGet(HttpServletRequest request, HttpServletResponse response) } throws ServletException, IOException { response.setContentType(\); String text = (String)this.getServletContext().getAttribute(\); response.getWriter().print(\ + text + \); 7 练习:访问量统计

相信各位一定见过很多访问量统计的网站,即“本页面被访问过XXX次”。因为无论是哪个用户访问指定页面,都会累计访问量,所以这个访问量统计应该是整个项目共享的!很明显,这需要使用ServletContext来保存访问量。 ServletContext application = this.getServletContext(); Integer count = (Integer)application.getAttribute(\); if(count == null) { } response.setContentType(\); response.getWriter().print(\本页面一共被访问\ + count + \次!\); application.setAttribute(\, count); count = 1; count++; } else {


黑马程序员javaweb教程:ServletContext.doc 将本文的Word文档下载到电脑
搜索更多关于: 黑马程序员javaweb教程:ServletContext 的文档
相关推荐
相关阅读
× 游客快捷下载通道(下载后可以自由复制和排版)

下载本文档需要支付 10

支付方式:

开通VIP包月会员 特价:29元/月

注:下载文档有可能“只有目录或者内容不全”等情况,请下载之前注意辨别,如果您已付费且无法下载或内容有问题,请联系我们协助你处理。
微信:xuecool-com QQ:370150219