javaweb:ServletContext应用(三)——读取资源文件
1.首先建立两个资源文件用以测试
一个在src/main/resources目录下建立db.properties,内容如下:
username=root
passward=123456
另一个在java项目目录下建立一个aa.properties.内容如下:
username=root2
passward=123456789
2.接下来建立一个类ServletDemo003用来读取刚刚建立的这两个资源文件
1 package com.jms.servlet; 2 3 import java.io.IOException; 4 import java.io.InputStream; 5 import java.util.Properties; 6 7 import javax.servlet.ServletException; 8 import javax.servlet.http.HttpServlet; 9 import javax.servlet.http.HttpServletRequest; 10 import javax.servlet.http.HttpServletResponse; 11 12 13 14 public class ServletDemo003 extends HttpServlet{ 15 16 @Override 17 protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 18 19 InputStream is = this.getServletContext().getResourceAsStream("./WEB-INF/classes/db.properties");//通过ServletContext获取资源文件的流 20 //需要注意的是,它这个路径是以WEB项目为根目录,所以可以写为“/WEB-INF/classes/db.properties”和“./WEB-INF/classes/db.properties”和“WEB-INF/classes/db.properties”三种形式 21 22 Properties prop = new Properties(); 23 prop.load(is); 24 String username = prop.getProperty("username");//获取属性名为“username”的值 25 String passward = prop.getProperty("passward"); 26 resp.getWriter().println(username + "\n" + passward); 27 InputStream is2 = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/jms/servlet/aa.properties"); 28 prop.load(is2); 29 username = prop.getProperty("username"); 30 passward = prop.getProperty("passward"); 31 resp.getWriter().println(username + "\n" + passward); 32 } 33 34 @Override 35 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 36 doGet(req, resp); 37 } 38 39 40 }
3.修改web.xml文件
建立servlet连接和路径
<servlet> <servlet-name>demo003</servlet-name> <servlet-class>com.jms.servlet.ServletDemo003</servlet-class> </servlet> <servlet-mapping> <servlet-name>demo003</servlet-name> <url-pattern>/demo003</url-pattern> </servlet-mapping>
4.接下来进行测试
读取资源文件成功
(本文仅作个人学习记录用,如有纰漏,敬请指正)