假设 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:Usershuey> 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.pluginsorg.eclipse.wst.server.core mp1wtpwebappshello-mvn-web