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