随笔 - 750  文章 - 1  评论 - 107  阅读 - 34万

[Java][Web]ServletContext 方法的应用

由于一个 Web 应用中的所有 Servlet 共享同一个 ServletContext 对象,所以多个 Servlet 通过 ServletContext 对象实现数据共享。

ServletContext 对象通常也被称之为 context 域对象。(还有 request session page)

String data = "aaaa123";
this.getServletContext().setAttribute("data", data);
String value = (String) this.getServletContext().getAttribute("data");
response.getOutputStream().write(("data:" + value).getBytes());

这两个放在两个 ServletDemo 类中时,在不同浏览器的不同页面都可以访问到 ServletContext 的值。

// 读取 WebRoot\WEB-INF\web.xml 中的属性值
String value = this.getServletContext().getInitParameter("data1");
response.getOutputStream().write(value.getBytes());
<servlet>
    <servlet-name>ServletDemo5</servlet-name>
    <servlet-class>cn.itcast.ServletDemo5</servlet-class>
    <init-param>
        <param-name>data1</param-name>
        <param-value>x1x2x3</param-value>
    </init-param>
</servlet>

以下代码实现了 Servlet 的转发: ( 1.jsp 位于 WebRoot\1.jsp ),但因为 ServletContext 是所有用户共用的域,因此此处使用并不合适。

String data = "aaa5";
// 把数据带给 1.jsp 不能通过 ServletContext 域,而要通过 request 域。
this.getServletContext().setAttribute("data", data);

RequestDispatcher rDispatcher = this.getServletContext()
        .getRequestDispatcher("/1.jsp");
rDispatcher.forward(request, response);
<div style="border:1px solid red;">
 <%
     String data = (String) application.getAttribute("data");
     out.write(data);
  %>
  </div>

以下代码用于读取 src 目录下的 db.properties 配置文件中的键值

复制代码
// 资源文件在源代码中放在 src 目录下,但发布后会出现在 WEB-INF\classes 目录下。
InputStream inputStream = this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties");
Properties properties = new Properties();
properties.load(inputStream);

String urlString = properties.getProperty("url");
String username = properties.getProperty("username");
String password = properties.getProperty("password");

response.getOutputStream().write(("url:" + urlString).getBytes());
response.getOutputStream().write(("\r\nusername:" + username).getBytes());
response.getOutputStream().write(("\r\npassword" + password).getBytes());
复制代码

如果配置文件放在包下,路径会在 /WEB-INF/classes/cn/itcast/ 目录下

如果配置文件在 WebRoot 目录下,路径会成为  /db.properties 

如果要使用 FileInputStream 来读取资源文件,可使用以下代码取得文件真实路径:

String path = this.getServletContext().getRealPath("/WEB-INF/classes/db.properties");

如果是 java 类等,不是 Servlet 的类来读资源文件,则使用以下代码

InputStream inputStream = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
Properties properties = new Properties();
properties.load(inputStream);

然后因为只需应用启动时读取一次,所以通常写成以下代码来使用:

复制代码
private static Properties dbconfig = new Properties();

static {
    try {
        InputStream inputStream = UserDao.class.getClassLoader()
                .getResourceAsStream("db.properties");
        dbconfig.load(inputStream);
    } catch (Exception e) {
        throw new ExceptionInInitializerError(e);
    }
}

// 如果读取资源文件的程序不是 Servlet 的话,就只能通过类装载器来读取
public void update() throws IOException {
    System.out.println(dbconfig.getProperty("url"));
}
复制代码

 这样的代码发布后,修改配置文件需要重启应用,可以使用以下方法改进:

InputStream inputStream = UserDao.class.getClassLoader().getResourceAsStream("db.properties");
// 按上面代码加载的配置文件 修改后仍读到原来的值
String path = UserDao.class.getClassLoader().getResource("db.properties").getPath();
FileInputStream inputStream = new FileInputStream(path);

不使用第一句代码,而使用后面的代码即可。

posted on   z5337  阅读(142)  评论(0编辑  收藏  举报
编辑推荐:
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
阅读排行:
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示