Servlet读取资源(properties)
1、在resources目录下新建一个properties文件,文件名bb.properties
文件内容:
username: root
password: 123
2、在maven中先进行一下clearn,清楚target目录
3、第一次启动tomcat,生成一个新的target目录,该目录下,找到编译过的bb.properties文件路径
并且在java目录下新建一个文件
内容如下,getResourceAsStream地址为编译过的bb.properties文件路径
import javax.servlet.RequestDispatcher;
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 PropServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/bb.properties");
Properties properties = new Properties();
properties.load(is);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
resp.getWriter().print(username+password);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
4、最后在web.xml中注册servlet
内容
<!--注册Servlet-->
<servlet>
<servlet-name>fuck1</servlet-name>
<servlet-class>com.donric.servlet.PropServletDemo05</servlet-class>
</servlet>
<!--Servlet的请求路径-->
<servlet-mapping>
<servlet-name>fuck1</servlet-name>
<url-pattern>/fuck1</url-pattern>
</servlet-mapping>
5、启动tomcat
版权声明:本文为qq_45239614原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。