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

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

问题描述

我在两个不同的容器(Tomcat 和 Jetty)上部署了一个 web 应用程序,但是它们用于提供静态内容的默认 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).

因此,我希望在 web 应用程序中包含一个小型 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:

这样的 servlet 在某处可用吗?我能找到的最接近的是 示例 4-10 来自 servlet 手册.

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 编码,并且应该能够从战争文件中提供静态文件.这不是很难的代码,但也不完全是微不足道的.

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 询问了 StaticServlet 中引用的 ServletUtils 类.它只是一个带有辅助方法的类,用于我的项目.您需要的唯一方法是 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天全站免登陆