java - 如何从文件系统调用图像?

标签 java jsp tomcat servlets jstl

我正在使用 eclipse WTP 在部署在 tomcat 服务器上的 Ubuntu 操作系统上开发 Web 应用程序。我想在 Web 应用程序中使用文件系统中的图像(显示它们)。我怎样才能有效地做到这一点?是通过使用上下文路径定位到驱动器上吗?还是通过使用流加载它们(或类似的东西)?另外,我在 WTP 项目中找不到任何 web.xml 或 server.xml 文件(因为新版本甚至不需要它们)。

改写:我想在我的网络应用程序中使用文件系统中的图像(静态内容)。在前端使用 JSTL。

编辑:

如果网络应用程序是 xyz 那么它的位置是:/home/webaapp/xyz/..... 图像在 /home/akshay/图像/.......

我想从网络应用程序访问一个远离(在同一硬盘驱动器中)的文件夹

最佳答案

您可以使用 Tomcat Default Servlet提供静态资源。

web.xml:

<servlet-mapping>
    <servlet-name>default</servlet-name>
    <url-pattern>/resources/*</url-pattern>
</servlet-mapping>

最好使用 c:url 并在值中使用前缀 / 以使 url 相对于上下文路径。

<img id="logo" src="<c:url value='/resources/images/logo.png'/>" />

动态项目结构:

WebContent
         |
         |__resources
         |          |
         |          |__images
         |                   |
         |                   |__logo.png
         |
         |__WEB-INF
                  |
                  |__web.xml

编辑

由于图像不是 war 的一部分,因此您可以尝试使用 Servlet。只需将路径存储在属性文件中的某处或将其作为 VM 参数传递或使其保持不变。

JSP:

<img src="${pageContext.servletContext.contextPath}/servletURL?name=logo.png"/>

小服务程序:

protected void doGet(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    String imageName=request.getParameter("name")
    String path = "absolute path of the image directory"+imageName;
    BufferedInputStream inputStream = null;
    try {
        inputStream = new BufferedInputStream(new FileInputStream(new File(path)));
        OutputStream outputStream = response.getOutputStream();
        byte[] bytes = new byte[1024 * 2];
        int bytesRead = -1;
        while ((bytesRead = inputStream.read(bytes)) != -1) {
            outputStream.write(bytes, 0, bytesRead);
        }
        outputStream.flush();
    } finally {
        if (inputStream != null) {
            inputStream.close();
        }
    }
}

使用The try-with-resources Statement处理资源,如果您使用的是 Java 7。

关于java - 如何从文件系统调用图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25097408/

相关文章:

Java/斯卡拉 Swing : Make a component fill all available space in a row

javascript - 如何从 Angularjs 访问 Session 值?

java - 向 Tomcat 添加更高优先级的 webapp 类加载器

java - 助手 : marven libraries can't be downloaded

java - android新手,无法在手机上运行github上的项目

java - JTable 行排序器 - 过滤器管理

java - 我们如何在 Struts 中追加 2 个字符串

java - 将.chm帮助文件集成到java应用程序(jsp页面)中的步骤

tomcat - 帮助使用 mod_jk 转发到后端应用服务器

java - 测量某个数据结构的内存使用情况