ServletContext:
在web.xml中配置ServletContext:
<context>
<param-name>name</param-name>
<param-value>value</param-value>
</context>
获得配置中的参数:
指定的
PrintWriter out = response.getWriter();
String value=this.getServletContext().getInitParameter("data");
out.print(value);
所有的
Enumeration<String> e=this.getServletContext().getInitParameterNames();
while(e.hasMoreElements()){
String name=e.nextElement();
System.out.println(name);
String date=this.getServletContext().getInitParameter(name);
out.println(name + "|" + date);
利用ServletContext对象读取文本资源
*得到文件路径
*读取初始文件的三种路径
*properties文件(属性文件)
->在web开发中用作资源的文件一般有两种xml和properties(配置文件有关系就用前者,没关系就用后者)
way1:
public void test1() throws IOException{
/*用户访问的是服务器中的test.properties文件,在src所有的文件最后都会被发布到classes文件中,
服务器中是没有src的
*/
//把资源作为流返回
InputStream in=this.getServletContext().getResourceAsStream("/WEB-INF/classes/test.properties");
//所有的properties文件都可以通过Java中的Properties对象来获取
Properties p=new Properties();//会用map集合来保存
p.load(in);//加流的数据load到p中
String url=p.getProperty("URL");
String name=p.getProperty("name");
String password=p.getProperty("password");
System.out.println(url);
System.out.println(name+"|" + password);
System.out.println(p.get("URL"));
}
//这种方法不好,动不动就在JVM的目录下放文件,最好采用ServletConfig来读取
public void test2() throws IOException{
//由服务器调,由java虚拟机运行,这是相对于java虚拟机的启动目录(bin下有src->test.properties才行)
FileInputStream in=new FileInputStream("classes/test.properties");
......
}
//通过ServletContext的getRealPath方法获得资源的绝对路径后,在通过传统的方法读取资源文件
public void test3() throws IOException{
String path=this.getServletContext().getRealPath("/WEB-INF/classes/test.properties");
//使用这个方法还可以得到资源的名称
System.out.println(path.substring(path.lastIndexOf("\\")+1));
FileInputStream in=new FileInputStream(path);
.......
}
在web应用中的普通java程序如何读取资源文件:
*首先想到的是通过Servlet得到,然后传给普通java程序,---》但是这样是不行的,web层侵略了数据访问层,
层与层耦合在一起了。
那应该怎么做呢?那就通过类装载器去做了(如果获取资源不是在Servlet中,就只能通过类装载器去读了)
way1:
//这种方式的缺点是:无法更新数据(类装载器只装载这个文件一次,修改了数据,在内存中发现还有这个文件,就不会装载)
InputStream in=this.getClass().getClassLoader().getResourceAsStream("test.properties");
Properties p=new Properties();
p.load(in);
System.out.println(p.getProperty("URL"));
way2:
//通过类装载的方式获得路径,然后再用传统的方式获得资源数据的数据,从而更新数据
String path=this.getClass().getClassLoader().getResource("test.properties").getPath();
FileInputStream i=new FileInputStream(path);