假设 Web 工程的目录结构如下图所示,并且 HelloServlet 配置为 @WebServlet(name = "helloServlet", urlPatterns = {"/hello"})

访问类路径下的资源

对于类路径下的文件,如 jms.properties 和 100.jpg,使用类加载器获取资源路径。

properties = new Properties();
try {
InputStream inStream = PropertiesUtils.class.getResourceAsStream("/config/jms.properties");
properties.load(inStream);
} catch (Exception e) {
e.printStackTrace();
} InputStream inStream = this.getClass().getResourceAsStream("/images/100.jpg");
if (inStream != null) {
resp.getOutputStream().write(IOUtils.toByteArray(inStream));
resp.setContentType("image/jpeg");
}

访问上下文路径下的资源

对于上下文环境的文件,如 webapp/images/101.jpg 文件。在浏览器地址栏上可以使用 http://localhost:8080/hello-mvn-web/images/101.jpg 访问。在 servlet 中可以通过 ServletContext 访问资源。

protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
InputStream inStream = context.getResourceAsStream("/images/100.jpg");
if (inStream != null) {
resp.getOutputStream().write(IOUtils.toByteArray(inStream));
resp.setContentType("image/jpeg");
} else {
resp.setStatus(HttpServletResponse.SC_NOT_FOUND);
}
}

获取各种路径

1. 获取上下文的路径。
  req.getContextPath()

2. 获取相对于上下文的 servlet 路径。
  req.getServletPath()

3. 获取请求 URL 的路径部分。
  req.getRequestURI()

4. 获取完整的请求 URL,除了查询字符串参数部分。
  req.getRequestURL()

5. 获取相对上下文路径对应于服务器文件系统上的绝对文件路径。
  context.getRealPath("/")

对于 http://localhost:8080/hello-mvn-web/hello?q=hello 请求,上述几种方法返回的结果:

C:\Users\huey> curl http://localhost:8080/hello-mvn-web/hello?q=hello
req.getContextPath(): /hello-mvn-web
req.getServletPath(): /hello
req.getRequestURI(): /hello-mvn-web/hello
req.getRequestURL(): http://localhost:8080/hello-mvn-web/hello
context.getRealPath("/"): E:\workspace\.metadata\.plugins\org.eclipse.wst.server.core\tmp1\wtpwebapps\hello-mvn-web\

最新文章

  1. jQuery学习笔记--JqGrid相关操作 方法列表(上)
  2. Java 开发环境的搭建
  3. 网络流量监控工具----iftop
  4. 现代程序设计homework——04
  5. 几个linux命令
  6. UESTC_Rain in ACStar 2015 UESTC Training for Data Structures<Problem L>
  7. javaScript 工作必知(八) 属性的特性 值、写、枚举、可配置
  8. Intger To Roman
  9. IEEE Trans 2009 Stagewise Weak Gradient Pursuits论文学习
  10. dotnetcore vue+elementUI 前后端分离架二(后端篇)
  11. 插入排序(Java实现)
  12. J2EE学习从菜鸟变大鸟之七 Servlet
  13. FastJson:Json树的CRUD操作方法实现
  14. 【mybatis】mybatis中 <if test=>等于的条件怎么写
  15. css 实现等分布局
  16. js的window.open()改写
  17. C语言编程常见技巧(问题???)
  18. 安装Prometheus-Opeartor
  19. centos7 使用cgroup进行资源限制
  20. 多媒体开发之rtmp---rtmp client 端的实现

热门文章

  1. UIImageView旋转任意角度---实现方法
  2. powershell里添加对git的支持
  3. MsSQL的游标的综合运用
  4. jdbc线程池
  5. eclipse 插件
  6. 在Linux下怎么确定哪个网卡对应哪个接口?
  7. C#实现对Word文件读写[转]
  8. delphi 文件或目录转换成 TreeView
  9. 关于AutoComplete整合
  10. java后端模拟表单提交