Java 如何在 Tomcat 上的 Web 应用程序中提供静态文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22965738/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 19:40:41  来源:igfitidea点击:

How to serve static files in my web application on Tomcat

javatomcatservlets

提问by que1326

I have this servlet based web application project in eclipse and want to append some html tags like <script src="Chart.js">.

我在 Eclipse 中有这个基于 servlet 的 Web 应用程序项目,并且想要附加一些 html 标签,例如<script src="Chart.js">.

The folder structure is:

文件夹结构为:

  • C:/apache-tomcat-7.0.53/
  • my workspace is in D:/../../workplace/CpdApplication/src/cpd/MyServlet.java
  • cpd contains: MyServlet.java, Chart.js and other files.
  • CpdApplication/WebContent/META-INF/web.xml
  • C:/apache-tomcat-7.0.53/
  • 我的工作区在 D:/../../workplace/CpdApplication/src/cpd/MyServlet.java
  • cpd 包含:MyServlet.java、Chart.js 等文件。
  • CpdApplication/WebContent/META-INF/web.xml

I have some path problems, and I can't resolve them, I searched over and over again and still not working, I get a 404 (Not Found) for http://localhost:8080/CpdApplication/Chart.js.

我有一些路径问题,我无法解决它们,我一遍又一遍地搜索,但仍然无法正常工作,我收到 404(未找到)的http://localhost:8080/CpdApplication/Chart.js.

The problem is when I want to append <script src='Chart.js'></script>, Tomcat cannot resolve the Chart.jsstatic file.

问题是当我想追加时<script src='Chart.js'></script>,Tomcat 无法解析Chart.js静态文件。

采纳答案by VH-NZZ

I have some path problems, and I can't resolve them, I searched over and over again and still not working, I get a 404 (Not Found) for .../CpdApplication/Chart.js

我有一些路径问题,我无法解决它们,我一遍又一遍地搜索但仍然无法正常工作,我得到 404(未找到).../CpdApplication/Chart.js

Indeed, when writing <script src="/Chart.js"/>you are telling the browser to make its own, separate HTTP request to get the JavaScript file. For this to work:

实际上,在编写时,<script src="/Chart.js"/>您是在告诉浏览器发出自己的、单独的 HTTP 请求以获取 JavaScript 文件。为此,请执行以下操作:

  • The servlet container needs to be able to serve static files
  • To this end, you need to have a servlet-mappinginside your web.xml to serve static files(ie. the defaultservlet).
  • servlet 容器需要能够提供静态文件
  • 为此,您需要在 web.xml 中有一个servlet-mapping提供静态文件(即默认的servlet)。

This should do:

这应该做:

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

Then place your Chart.jsin the following folder: WebContent/js/and it should work.

然后将您的Chart.js放在以下文件夹中:WebContent/js/它应该可以工作。

EDIT: Of course, you'll need to update the <script>tag in your HTML. Also, make sure that you redeploy your web app to update web.xml on your servlet container (Tomcat I presume).

编辑:当然,您需要更新<script>HTML 中的标签。此外,请确保您重新部署您的 Web 应用程序以更新您的 servlet 容器(我认为是 Tomcat)上的 web.xml。

回答by Andres

It seems to me like Chart.js is stored in the same folder with your servlet source.

在我看来 Chart.js 与您的 servlet 源存储在同一文件夹中。

Usually you should have a structure like this one (I have simplified it):

通常你应该有一个这样的结构(我已经简化了它):

/css/your-css.css
/js/your-script.js
/src/your-package/YourServlet.java

Whenever you run your application, your compiler creates a set of files that will be copied to your web container. The copied files do not include your srcfolder, but instead a copy of your built (compiled) classes. All other files (with some exceptions that we should not care about right now) must be outside your srcfolder in order to get copied.

每当您运行应用程序时,您的编译器都会创建一组文件,这些文件将被复制到您的 Web 容器中。复制的文件不包括您的src文件夹,而是您构建(编译)类的副本。所有其他文件(除了一些我们现在不应该关心的例外)必须在您的src文件夹之外才能被复制。

Try moving your JS inside a js directory outside your src directory. Then, link it like this:

尝试将您的 JS 移动到 src 目录之外的 js 目录中。然后,像这样链接它:

<script src='/Your-Context-Path/js/Chart.js'>

There must be a function to get your context path automatically, I think it is

必须有一个功能可以自动获取您的上下文路径,我认为是

ServletContext.getContextPath()

You can read about it here.

你可以在这里阅读它。

That should make the trick.

这应该是诀窍。

回答by Luiggi Mendoza

As @Andy replied, you need to set all your resource (JS, CSS, images, etc.) in a folder in your application, then access to them using <context_path>/folder/to/your/resource/<resource_name>.<ext>. Here's a sample of how to do it:

正如@Andy 回答的那样,您需要在应用程序的文件夹中设置所有资源(JS、CSS、图像等),然后使用<context_path>/folder/to/your/resource/<resource_name>.<ext>. 以下是如何执行此操作的示例:

  • Create a folder inside the root folder (usually named webor WebContent) of your web application with name res.
  • Inside res, create a folder called jsto put all the JavaScript files there. You may create a cssfolder to handle all your CSS stylesheets, imgfor images, and on.
  • In your view, this mean, your JSP, you should access to your resources via context path.
  • 在 Web 应用程序的根文件夹(通常命名为webWebContent)中创建一个名为res 的文件夹。
  • res 中,创建一个名为js的文件夹,将所有 JavaScript 文件放在那里。您可以创建一个css文件夹来处理您所有的 CSS 样式表、图像的img等等。
  • 在您看来,这意味着您的 JSP,您应该通过上下文路径访问您的资源。

This is how your application folders should look:

这是您的应用程序文件夹的外观:

- WebContent
  - res
    - js
      Chart.js

In your JSP:

在您的 JSP 中:

<script src="${request.contextPath}/res/js/Chart.js"></script>

Since you're creating the view content from your Servlet (a shoot on the foot, by the way), use request#getContextPath()to attach it:

由于您是从 Servlet 创建视图内容(顺便说一句,request#getContextPath()这是在脚上拍摄的),请使用附加它:

"script src=\"" + request#getContextPath() + "/res/js/Chart.js\"></script>";

回答by Vahe Gharibyan

This is works for me. Thanks 沖原ハーベスト

这对我有用。谢谢冲原ハーベスト

welcome.jsp

欢迎.jsp

  <head>
    <script src="resources/js/jsx/browser.min.js"></script>
    <script src="resources/js/react/react.min.js"></script>
    <script src="resources/js/react/react-dom.min.js"></script>
    <script src="resources/js/main.js"></script>
    <link rel="stylesheet" type="text/css" href="resources/css/style.css">
  </head>

File hierarchy tree

文件层次树

enter image description here

在此处输入图片说明

Web.xml

网页.xml

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

回答by Hemant Nagpal

Rightly said by @VH-NZZ but in case you are using Spring 4x or above, you need to add static resources into ResourceHandlerRegistry. You can do this into your "AppConfig"(your application configuration file), like this :

@VH-NZZ 说得对,但如果您使用的是 Spring 4x 或更高版本,则需要将静态资源添加到 ResourceHandlerRegistry 中。您可以在“AppConfig”(您的应用程序配置文件)中执行此操作,如下所示:

@Configuration
@EnableWebMvc
@EnableScheduling
@ComponentScan(basePackages = "com.packagename")
public class AppConfig extends WebMvcConfigurerAdapter {

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/build/**").addResourceLocations("/build/");
    registry.addResourceHandler("/dist/**").addResourceLocations("/dist/");
    registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
    registry.addResourceHandler("/assets/**").addResourceLocations("/assets/");
    registry.addResourceHandler("/images/**").addResourceLocations("/images/");
}

Again as rightly said above, you should not keep your java files and static content together at the same location. These should always be available at a separate location. You can put your static content directly under your webapp folder.

再次如上所说,您不应将 Java 文件和静态内容放在同一位置。这些应始终在单独的位置提供。您可以将静态内容直接放在 webapp 文件夹下。