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获取资源文件的流,最前面的“/”不能省略,他代表这个web项目 20 Properties prop = new Properties(); 21 prop.load(is); 22 String username = prop.getProperty("username");//获取属性名为“username”的值 23 String passward = prop.getProperty("passward"); 24 resp.getWriter().println(username + "\n" + passward); 25 InputStream is2 = this.getServletContext().getResourceAsStream("/WEB-INF/classes/com/jms/servlet/aa.properties"); 26 prop.load(is2); 27 username = prop.getProperty("username"); 28 passward = prop.getProperty("passward"); 29 resp.getWriter().println(username + "\n" + passward); 30 } 31 32 @Override 33 protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { 34 doGet(req, resp); 35 } 36 37 38 }
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.接下来进行测试
读取资源文件成功
(本文仅作个人学习记录用,如有纰漏,敬请指正)
标签:username,文件,读取,resp,prop,passward,ServletContext,import,servlet 来源: https://www.cnblogs.com/jmsstudy/p/16515255.html