在Spring中访问webapp文件夹中的文件/目录 [英] Accessing files/directories in webapp folder in Spring

查看:94
本文介绍了在Spring中访问webapp文件夹中的文件/目录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Spring方面缺乏经验,现在我需要做的就是访问并获取webapp文件夹中文件和文件夹的引用。这是我的相关项目层次结构:

I'm inexperienced in Spring and everything I need to do now is to access and obtain a reference to files and folders in the webapp folder. Here is my relevant project hierarchy:

-src
--main
---java (marked as source root)
----my
-----package
------controller
-------Home.java
---webapp
----images
-----avatars

我在Home.java中的代码:

My code in Home.java:

@Controller
@RequestMapping("/")
public class Home
{
    @RequestMapping(method = RequestMethod.GET)
    public String index(Model model,
                        HttpServletRequest request) throws Exception
    {
        String test1 = request.getSession().getServletContext().getRealPath("");
        String test2 = request.getSession().getServletContext().getRealPath("/");
        String test3 = request.getRealPath("");
        String test4 = request.getRealPath("/");
        String test5 = request.getSession().getServletContext().getRealPath(request.getServletPath());

        return "index";
    }
}

所有5个请求都返回null。我做错了吗?

web.xml:

<web-app xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
         http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
         version="2.5">

    <display-name>Test</display-name>

    <servlet>
        <servlet-name>test</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>test</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <session-config>
        <session-timeout>10</session-timeout>
    </session-config>
</web-app>

我正在努力实现的目标(本例中未显示)是编码负责的控制器用于缩放图像。出于这个原因,我需要访问src / main / webapp / _images文件夹。

What I'm trying to achieve (not shown in this example), is to code a controller responsible for the scaling of an image. For this reason I would need access to the src/main/webapp/_images folder.

谢谢!

更新:简化了示例以便更好地理解。

Update: simplified the example for better understanding.

Update2:感谢@gigadot的建议,我将应用程序部署为爆炸式WAR,问题部分得到解决。有人能告诉我部署WAR的区别是什么?是不是建议在生产服务器上做什么?优点/缺点?

Update2: thanks to the suggestion of @gigadot, I deployed the application as an exploded WAR and the problem is partly solved. Can someone tell me what's the difference in deploying the WAR as exploded? Is it something not recommended to do on a production server? Advantages/disadvantages?

我认为用一个例子解释这种情况是值得的。假设我正在编写社交网络,我必须上传我的个人资料图片。此图片将上传到 src / main / webapp / _images / avatars / [myid] .jpg 文件夹。
是否建议将图片上传到 webapp 文件夹?或者有更好的解决方案吗?
我希望能够在访问URL / images / [width] x [height] / [userid] .jpg 。

I think it's worth to explain the situation with an example. Let's say I'm coding a social network and I have to possibility to upload my personal profile picture. This picture will be uploaded to the src/main/webapp/_images/avatars/[myid].jpg folder. Is it recommended to upload pictures to the webapp folder? Or is there a better solution? I would like to be able to return a scaled instance of the image when accessing the URL /images/[width]x[height]/[userid].jpg.

将WAR部署为爆炸并实施 ResourceLoaderAware (感谢@KevinSchmidt),我可以使它工作使用此:

Deploying the WAR as exploded and implementing the ResourceLoaderAware (thanks @KevinSchmidt), I can make it work using this:

resourceLoader.getResource("file:" + request.getSession().getServletContext().getRealPath("/") + "_images/avatars/");

对我来说,它看起来很脏,对生产服务器来说是个好主意吗?有没有更好的解决方案?

To me it looks quite dirty, is it a good idea for a production server? Is there a better solution?

推荐答案

您是如何部署应用程序的?

How exactly did you deploy your application?

ServletContext()。getRealPath(/)如果未部署为已爆炸,则可能返回null。请阅读以下链接以获取更多信息。但是,配置它的方法可能与您的servlet容器不同。

ServletContext().getRealPath("/") may return null if it is not deployed as exploded. Read the link below for further information. However, the method to configure this may not be the same for your servlet container.

http://ananthkannan.blogspot.com/2009/12/servletcontextgetrealpath-returns-null.html

更新


有人能告诉我将WAR部署为$ b $的区别是什么b爆炸?

Can someone tell me what's the difference in deploying the WAR as exploded?

当您将war文件部署为爆炸时,servlet容器,例如Tomcat会将war文件的内容解压缩到一个临时文件夹中并运行该文件夹中的所有内容,以便实际存在 {WEB_ROOT] / _ images / avatars / [myid] .jpg 在文件系统(硬盘)上。因此,您实际上可以获得真实路径(正如它已经在方法的名称中所述)。但是,如果您的servlet容器没有提取war文件,那么您要查找的文件夹位于war文件中,并且没有真正的路径,因此它将返回 null

When you deploy the war file as exploded, the servlet container, e.g. Tomcat, will extract the content of war file into a temporary folder and runs everything from that folder so the {WEB_ROOT]/_images/avatars/[myid].jpg is actually exist on file system (hard disk). Therefore, you can actually get the real path (as it already says in the name of the method). However, if your servlet container does not extract the war file, the folder you are looking for is inside the war file and there is no real path to it so it will return null.


是否不建议在生产服务器上执行此操作?
优点/缺点?

Is it something not recommended to do on a production server? Advantages/disadvantages?

您不应将动态内容存储在源文件夹或webroot文件夹(webapp)之下,因为servlet容器将临时使用它并在重新部署Web应用程序时将其删除或更改为新文件夹。您可能会丢失放入这些文件夹的动态数据。 Web根文件夹通常用于存储静态内容,这意味着您不想更改的内容 - 例如,Web组件的图形图像,如背景图像,CSS等。

You should not store dynamic contents under your source folder or the webroot folder (webapp) since servlet container will use it temporarily and delete it or change to a new folder when you redeploy your web application. You will likely lost the dynamic data you put into these folders. The web root folder is usually designed for storing static content, which means content you don't want to change - for example, graphic images for your web component like background images, css, etc.

存储用户数据的常用方法是以某种方式在用户空间中创建一个文件夹并将动态数据放在那里。但是,您将无法提供webroot外部文件夹的内容。在请求数据时,您需要编写自己的静态servlet来管道数据。这对初学者来说非常复杂。

The usual method for storing user data is to somehow create a folder in userspace and put your dynamic data in there. However, you will not be able to serve the content of the folder outside webroot. You will need to write your own static servlet to pipe the data when they are requested. This is quite complicated for a beginner.

实现自己的静态servlet以提供动态内容的最简单方法是扩展servlet容器的静态servlet。但是,您的代码将高度依赖于您正在部署的servlet容器。

The easiest way for implementing your own static servlet to serve dynamic content is to extend the static servlet of your servlet container. However, your code will highly depend on the servlet container you are deploying to.

由于您要提供用于调整图像大小的REST接口,因此可以创建一个控制器,从动态内容文件夹中读取原始图像,进行大小调整,将其保存为临时文件或刷新 HttpResponse 的内容。

Since you are going to provide a REST interface for resizing images, you can create a controller which reads in the original images from the dynamic content folder, do the resizing, save it as a temporary file or flush the content of the HttpResponse.

这篇关于在Spring中访问webapp文件夹中的文件/目录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆