Servlet(19)web.xml 配置之Servlet参数配置和读取资源文件,获取文件全路径

时间:2022-02-23 13:23:07

如果涉及到不同用户共享数据,而这些数据量不大,同时又不希望写入数据库中,我们可以考虑使用ServletContext来实现。

// ------------为servlet1配置相关参数
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>Servlet1</servlet-name>
<servlet-class>com.test.Servlet1</servlet-class>
<!-- 这样配置,相当于只给该servlet使用 -->
<init-param>
<param-name>username</param-name>
<param-value>scott</param-value>
</init-param>
</servlet>
<!-- 这样配置,相当于在整个应用有效 -->
<context-param>
<param-name>name</param-name>
<param-value>jiaozl</param-value>
</context-param>
//--------在Servlet1中获取配置好的参数----------
String val1 = this.getServletConfig().getInitParameter("username");
out.println(val1 + "<br />");
//--------获取在web应用中配置好的参数----------
String val = this.getServletContext().getInitParameter("name");
out.println(val + "<br />");

读取src目录下的文件,采用类加载器读取:http://blog.csdn.net/u013943420/article/details/70161253
读取资源文件(.properties文件 web目录或web-inf目录下的文件)

// 读取文件
InputStream is = this.getServletContext().getResourceAsStream("dbinfo.properties");
// 创建属性对象
Properties pp = new Properties();
pp.load(is);
out.println(pp.getProperty("name") + "<br/>");

②获得文件的全路径

// 获得文件的全路径
String path = this.getServletContext().getRealPath("dbinfo.properties");
out.println(path + "<br/>");