首页 > 代码库 > 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 }
1 url=jdbc:mysql://localhost:3306/test2 username=root3 password=root
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。