1.在resources文件夹下新建一个db.properties文件,写入;
username=root password=123456
2.java文件夹下建一个文件Demo05
package com.yin; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.util.Properties; public class Demo05 extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { InputStream is=this.getServletContext().getResourceAsStream("/WEB-INF/classes/db.properties"); Properties prop = new Properties(); prop.load(is); String user = prop.getProperty("username"); String pwd = prop.getProperty("password"); resp.getWriter().print(user + ":" + pwd); } @Override protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { super.doGet(req, resp); } }
3.web.xml配置访问路径
<servlet> <servlet-name>sd5</servlet-name> <servlet-class>com.yin.Demo05</servlet-class> </servlet> <servlet-mapping> <servlet-name>sd5</servlet-name> <url-pattern>/sd5</url-pattern> </servlet-mapping>
4.运行TOMCAT,跳出页面后,地址加上/sd5,如下图;
标签:文件,java,读取,sd5,resp,Serverlet,import,servlet,javax From: https://www.cnblogs.com/insoon/p/17047802.html