gpt4 book ai didi

java - 创建 GZip 响应的 JSP 过滤器

转载 作者:行者123 更新时间:2023-12-01 04:46:36 26 4
gpt4 key购买 nike

我刚刚编写了一个过滤器来对我的回复进行 gzip 压缩,并取得了惊人的结果。我最大的 JSP 页面已从 80K 变为 5.7K。但是,我编写的过滤器 gzip 包含来自服务器的所有响应,包括图像。然而,Yahoo说这是一种非常糟糕的做法。

Image and PDF files should not be gzipped because they are already compressed. 
Trying to gzip them not only wastes CPU but can potentially increase file sizes.

这是我编写的过滤器的 web.xml 足迹

<!-- THIS FILTER WILL TAKE MY OUTPUT AND GZIP IT TO LESSEN MY BANDWIDTH FOOTPRINT -->
<filter>
<filter-name>GZip</filter-name>
<filter-class>org.instride.gzip.GZIPFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>GZip</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

正如您所看到的,所有响应都已被压缩。但是,我只想 gzip css js 和 jsp 页面。所以你可能认为我可以添加这些人

<url-pattern>*.jsp</url-pattern>
<url-pattern>*.css</url-pattern>
<url-pattern>*.js</url-pattern>

但这会给我带来一个问题,因为我的所有 jsp 页面都隐藏了扩展名,因为它们是 servlet,而且我还使用 tuckey's网址重写。例如,我想要 gzip 压缩的页面的 URL 如下所示。

https://example.com/user/1/admin

因此 servlet (user) 在 web.xml 文件中没有可精确定位的扩展名,并且 servlet 后面是正斜杠参数。所以我正在考虑两种可能的解决方案。

  1. 不包含我想要 gzip 的文件类型,而是包含我想要跳过的文件类型,例如 jpeg 或 gif。
  2. 我仅根据内容类型指定 gzip 文件,例如 text/html;charset=UTF-8

任何关于我如何做这些事情的指导,或者更好的解决我的问题的方案,将不胜感激。感谢大家阅读本文。

最佳答案

我放弃了第二个想法并编写了这个解决方案。在我的解决方案中,我查看请求 header 中的接受属性。根据我收集的 Firebug 的信息,我网站上的所有图像,无论其格式如何,都有一个接受属性

image/png,image/*;q=0.8,*/*;q=0.5

老实说,我不知道这到底意味着什么,但所有 jpg、png 和 gif 都有它,而其他文件类型都没有,所以这就是我所做的。

...

public class GZIPFilter implements Filter 
{
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
if (servletRequest instanceof HttpServletRequest)
{
HttpServletRequest httpRequest;
HttpServletResponse httpResponse;
String acceptedEncoding, accept;
GZIPResponseWrapper wrappedResponse;

httpRequest = (HttpServletRequest) servletRequest;
httpResponse = (HttpServletResponse) servletResponse;

accept = httpRequest.getHeader("accept");
acceptedEncoding = httpRequest.getHeader("accept-encoding");

if (acceptedEncoding != null && acceptedEncoding.indexOf("gzip") != -1 && !accept.equals("image/png,image/*;q=0.8,*/*;q=0.5"))
{
wrappedResponse = new GZIPResponseWrapper(httpResponse);
filterChain.doFilter(servletRequest, wrappedResponse);
wrappedResponse.finishResponse();
return;
}

filterChain.doFilter(servletRequest, servletResponse);
}
}

public void init(FilterConfig filterConfig)
{

}

public void destroy()
{

}
}

关于java - 创建 GZip 响应的 JSP 过滤器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15723022/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com