用于提供静态内容的Servlet [英] Servlet for serving static content

查看:130
本文介绍了用于提供静态内容的Servlet的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在两个不同的容器(Tomcat和Jetty)上部署了一个webapp,但是他们用于提供静态内容的默认servlet有一种不同的方式来处理我想要使用的URL结构(详情)。

I deploy a webapp on two different containers (Tomcat and Jetty), but their default servlets for serving the static content have a different way of handling the URL structure I want to use (details).

因此,我希望包含一个webapp中的小servlet用于提供自己的静态内容(图像,CSS等)。 servlet应具有以下属性:

I am therefore looking to include a small servlet in the webapp to serve its own static content (images, CSS, etc.). The servlet should have the following properties:

  • No external dependencies
  • Simple and reliable
  • Support for If-Modified-Since header (i.e. custom getLastModified method)
  • (Optional) support for gzip encoding, etags,...

这样的servlet是否可用?我能找到的最近的是例4-10 来自servlet book。

Is such a servlet available somewhere? The closest I can find is example 4-10 from the servlet book.

更新:我想要使用的URL结构 - 如果您想知道 - 只是:

Update: The URL structure I want to use - in case you are wondering - is simply:

    <servlet-mapping>
            <servlet-name>main</servlet-name>
            <url-pattern>/*</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
            <servlet-name>default</servlet-name>
            <url-pattern>/static/*</url-pattern>
    </servlet-mapping>

因此所有请求都应传递给主servlet,除非它们是 static 路径。问题是Tomcat的默认servlet不考虑ServletPath(因此它在主文件夹中查找静态文件),而Jetty则这样做(所以它看起来在 static 文件夹)。

So all requests should be passed to the main servlet, unless they are for the static path. The problem is that Tomcat's default servlet does not take the ServletPath into account (so it looks for the static files in the main folder), while Jetty does (so it looks in the static folder).

推荐答案

我最终滚动了自己的 StaticServlet 。它支持 If-Modified-Since ,gzip编码,它也应该能够从war-files提供静态文件。代码并不是很难,但它也不是完全无关紧要。

I ended up rolling my own StaticServlet. It supports If-Modified-Since, gzip encoding and it should be able to serve static files from war-files as well. It is not very difficult code, but it is not entirely trivial either.

代码可用: StaticServlet.java 。随意发表评论。

The code is available: StaticServlet.java. Feel free to comment.

更新: Khurram询问 ServletUtils 类是什么在 StaticServlet 中引用。它只是一个带有我用于项目的辅助方法的类。你需要的唯一方法是 coalesce (这与SQL函数相同 COALESCE )。这是代码:

Update: Khurram asks about the ServletUtils class which is referenced in StaticServlet. It is simply a class with auxiliary methods that I used for my project. The only method you need is coalesce (which is identical to the SQL function COALESCE). This is the code:

public static <T> T coalesce(T...ts) {
    for(T t: ts)
        if(t != null)
            return t;
    return null;
}

这篇关于用于提供静态内容的Servlet的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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