ServletContext读取Web应用中的资源文件

ServletContext读取Web应用中的资源文件
 1 package cn.itcast;
 2 
 3 import java.io.FileInputStream;
 4 import java.io.IOException;
 5 import java.io.InputStream;
 6 import java.io.PrintWriter;
 7 import java.util.Properties;
 8 
 9 import javax.servlet.ServletContext;
10 import javax.servlet.ServletException;
11 import javax.servlet.http.HttpServlet;
12 import javax.servlet.http.HttpServletRequest;
13 import javax.servlet.http.HttpServletResponse;
14 
15 //读取资源文件
16 public class ServletDemo1 extends HttpServlet {
17 
18     
19     public void doGet(HttpServletRequest request, HttpServletResponse response)
20             throws ServletException, IOException {
21 
22         test2();
23     }
24     
25     //通过servletContext的getReadlPath得到资源的绝对路径后,再通过传统流读取资源文件
26     public void test2() throws IOException {
27         
28         String path = this.getServletContext().getRealPath("/WEB-INF/classes/cn/itcast/db.properties");
29         System.out.println(path);
30         String filename = path.substring(path.lastIndexOf("\\")+1);
31         System.out.println("当前读取到资源名称是:"+filename);
32         
33         FileInputStream in = new FileInputStream(path);
34         
35         Properties props = new Properties();
36         props.load(in);
37         
38         String url = props.getProperty("url");
39         String username = props.getProperty("username");
40         String password = props.getProperty("password");
41         
42         System.out.println(url+username+password);
43     }
44 
45 
46     public void test1() throws IOException {
47         InputStream in = this.getServletContext().getResourceAsStream("/WEB-INF/classes/cn/itcast/db.properties");
48     
49         Properties props = new Properties();
50         props.load(in);
51         
52         String url = props.getProperty("url");
53         String username = props.getProperty("username");
54         String password = props.getProperty("password");
55         
56         System.out.println(url+username+password);
57     }
58 
59     
60     public void doPost(HttpServletRequest request, HttpServletResponse response)
61             throws ServletException, IOException {
62 
63         
64     }
65 
66 }
View Code
ServletContext读取Web应用中的资源文件
1 url=jdbc:mysql://localhost:3306/test
2 username=root
3 password=root
View Code

 

ServletContext读取Web应用中的资源文件,布布扣,bubuko.com

ServletContext读取Web应用中的资源文件

上一篇:高性能网站建设


下一篇:JS图片Switchable切换大集合