这篇文章主要介绍了JavaWeb_servlet(11)_ 通过 ServletContex 获得类路径下的文件路径的讲解,通过具体代码实例进行16555 讲解,并且分析了JavaWeb_servlet(11)_ 通过 ServletContex 获得类路径下的文件路径的详细步骤与相关技巧,需要的朋友可以参考下https://www.b2bchain.cn/?p=16555
本文实例讲述了2、树莓派设置连接WiFi,开启VNC等等的讲解。分享给大家供大家参考文章查询地址https://www.b2bchain.cn/7039.html。具体如下:
目录
- 通过 ServletContex 获得类路径下的文件路径
通过 ServletContex 获得类路径下的文件路径
-
demo1
-
web.xml
-
启动 Tomcat
-
测试
-
以上操作完整源码
package com.wyx.servlet; import java.io.IOException; import java.io.InputStream; import java.util.Properties; import javax.servlet.ServletConfig; import javax.servlet.ServletContext; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class demo1 extends HttpServlet { @Override public void init(ServletConfig config) throws ServletException { // 获得到ServletContext对象 ServletContext sc = config.getServletContext(); // 获得 classpath 下的资源的文件的流,用于 classpath 下的文件发布之后是在/WEB-INF/classes下, // 所以去指定/WEB-INF/classes/test1.properties // InputStream in = sc.getResourceAsStream("/WEB-INF/classes/test1.properties"); // 使用类加载器的方式来读取 classpath 下的资源文件,好处不依赖与ServletContext,任何类都可以获得classpath下的资源文件, // 不需要再自己指定/WEB-INF/classes InputStream in = this.getClass().getClassLoader().getResourceAsStream("test1.properties"); Properties prop = new Properties(); try { prop.load(in); System.out.println(prop.get("key")); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5"> <display-name>servlet_demo</display-name> <!-- 全局(ServletContext)的容器参数 --> <context-param> <param-name>context_key</param-name> <param-value>context_value</param-value> </context-param> <servlet> <!-- 设置servlet的名字 --> <servlet-name>helloServlet</servlet-name> <!-- 具体的servlet的类 --> <servlet-class>com.wyx.servlet.demo1</servlet-class> </servlet> <servlet-mapping> <servlet-name>helloServlet</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app>
工程文件下载
如有错误,欢迎指正!
本文转自互联网,侵权联系删除JavaWeb_servlet(11)_ 通过 ServletContex 获得类路径下的文件路径
最新评论