码迷,mamicode.com
首页 > Web开发 > 详细

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

时间:2014-07-02 00:40:26      阅读:280      评论:0      收藏:0      [点我收藏+]

标签:style   blog   http   java   color   文件   

bubuko.com,布布扣
 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
bubuko.com,布布扣
1 url=jdbc:mysql://localhost:3306/test
2 username=root
3 password=root
View Code

 

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

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

标签:style   blog   http   java   color   文件   

原文地址:http://www.cnblogs.com/aineko/p/3815796.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!