新建一个Servlet:
我这里是getPropertiesServlet extends HttpServlet
里面重写doGet方法:
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html;charset=utf-8");
ServletContext servletContext = getServletContext();
InputStream is = servletContext.getResourceAsStream("/WEB-INF/classes/db.properties");
Properties prop=new Properties();
prop.load(is);
String username = prop.getProperty("username");
String password = prop.getProperty("password");
PrintWriter printWriter=resp.getWriter();
printWriter.println(username+""+password);
}
db.properties:
username=root
password=123456
web.xml里配置路径映射
<servlet>
<servlet-name>getPropertiesServlet</servlet-name>
<servlet-class>com.cx.servlet.getPropertiesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>getPropertiesServlet</servlet-name>
<url-pattern>/getPropertiesServlet</url-pattern>
</servlet-mapping>
servletContext.getResourceAsStream("/WEB-INF/classes/db.properties"); 路径:/WEB-INF/classes/db.properties
第一个/ 表示当前项目 既javaweb文件夹下
类路径写法:classpath:db.properties(PS:替换上面不知道为什么用不了)
idea快捷键:Ctrl+Alt+T. 快速加surround with