如何在 Spring 中缩小动态 HTML 响应?

2024-01-01

遵循 Google 的 pagespeed 建议,我希望缩小 Spring 应用程序的 HTML 响应。我指的不是 GZip,而是在发送 HTML 之前从 HTML 中删除注释和空格。

我想动态地执行此操作,而不是在我的模板中执行此操作。我的模板包含许多有用的评论,但不应成为响应的一部分。

以下是我的控制器;

@Controller
public class IndexController {

    @GetMapping("/")
    public ModelAndView index() {
        Data data = ....
        return new ModelAndView("index", data);
    }
}

我设法通过添加一个来做到这一点javax.servlet.Filter http://www.java2s.com/Tutorial/Java/0400__Servlet/Filterthatusesaresponsewrappertoconvertalloutputtouppercase.htm正在使用的组件com.googlecode.htmlcompressor https://mvnrepository.com/artifact/com.googlecode.htmlcompressor/htmlcompressor/1.5.2进入春天

首先是Filter;

@Component
public class HtmlFilter implements Filter {
    protected FilterConfig config;

    public void init(FilterConfig config) throws ServletException {
        this.config = config;
    }

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        ServletResponse newResponse = response;

        if (request instanceof HttpServletRequest) {
            newResponse = new CharResponseWrapper((HttpServletResponse) response);
        }

        chain.doFilter(request, newResponse);

        if (newResponse instanceof CharResponseWrapper) {
            String text = newResponse.toString();
            if (text != null) {
                HtmlCompressor htmlCompressor = new HtmlCompressor();
                response.getWriter().write(htmlCompressor.compress(text));
            }
        }
    }
}

和相关的CharResponseWrapper;

class CharResponseWrapper extends HttpServletResponseWrapper {
    protected CharArrayWriter charWriter;
    protected PrintWriter writer;
    protected boolean getOutputStreamCalled;
    protected boolean getWriterCalled;

    public CharResponseWrapper(HttpServletResponse response) {
        super(response);

        charWriter = new CharArrayWriter();
    }

    public ServletOutputStream getOutputStream() throws IOException {
        if (getWriterCalled) {
            throw new IllegalStateException("getWriter already called");
        }

        getOutputStreamCalled = true;
        return super.getOutputStream();
    }

    public PrintWriter getWriter() throws IOException {
        if (writer != null) {
            return writer;
        }
        if (getOutputStreamCalled) {
            throw new IllegalStateException("getOutputStream already called");
        }
        getWriterCalled = true;
        writer = new PrintWriter(charWriter);
        return writer;
    }

    public String toString() {
        String s = null;

        if (writer != null) {
            s = charWriter.toString();
        }
        return s;
    }
}

效果非常好。转换成这么难看的html;

<!DOCTYPE HTML>
<html>
<head>
    <title>
        A Simple
        <!--        Test-->
        HTML Document
        <!--        Test-->

    </title>



</head>
<body>
                 <p>This is a very simple HTML document</p>


                 <!--        Test-->



<p>It only has two<!--        Test--> paragraphs</p>

                 <!--        Test-->

</body>
</html>

进入这个;

<!DOCTYPE HTML> <html> <head> <title> A Simple HTML Document </title> </head> <body> <p>This is a very simple HTML document</p> <p>It only has two paragraphs</p> </body> </html>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 Spring 中缩小动态 HTML 响应? 的相关文章

随机推荐

  • DataGridView 行添加事件

    我正在使用 DataGridView 并将列表绑定到数据源 我已经有了正确的列 并且准确地映射了字段 我想做的是处理一种RowAdded or RowDataBound 就像在 aspx GridView 中一样 事件 我发现的唯一事件是R
  • 我是否必须创建新的可见元素才能遵守 Google 的 Microdata Schema.org 要求?

    我已将 Schema org Microdata 属性添加到我网站上的列表组件中 This is one item in my list div span The Awesome Web App 01 span span span span
  • 更改文件的单个字符

    我需要更改文件中的单个字符 我不想使用像这样的辅助文件 伪代码 read theFile change theFile write theFile2 erase theFile rename theFile2 theFile 因为通过这种方
  • 通过 Javascript 查找何时在 EPUB FXL 中查看页面

    是否可以找出何时使用 Javascript 查看 EPUB 固定布局的页面 有 DOMContentLoaded 事件 但相邻页面在 iBooks 中预加载时也会触发此事件 导致动画或声音在页面可见之前启动 不 这不对 这是iBooks的一
  • 如何将正则表达式的匹配分配给变量?

    我有一个文本文件 其中包含各种条目 每个条目都以包含所有星号的行结束 我想使用 shell 命令来解析该文件并将每个条目分配给一个变量 我怎样才能做到这一点 这是一个示例输入文件 Field1 Lorem ipsum Data to mat
  • 将 VARCHAR 时间戳转换为 TIMESTAMP?

    我在 MySQL 数据库中有一个格式为 17 16 28 Sep 13 2011 PDT 的时间戳 数据库中字段的类型是VARCHAR 我想将这个 VARCHAR 转换为 MySQL 中 TIMESTAMP 类型的字段 我尝试了几个本网站其
  • 如何让 slc 命令在 Ubuntu 上运行?

    我已经使用安装了 Strongloopnpm install g strongloop在我的 Ubuntu 14 04 服务器上 这slc命令不起作用 它说 The program slc is currently not installe
  • 使用实体框架更新外键

    我再次遇到了实体框架的问题唷 我正在尝试使用外键更新表 我在插入时遇到问题 但通过编辑 edmx 文件解决了这个问题 我使用以下代码来更新与角色表具有外部关系的用户表 Domain Data Role role db Role FirstO
  • 使用selenium打开的Chrome页面仍然是空白

    我正在尝试保存网页的屏幕截图 为此我尝试使用 Selenium 问题是 一旦打开网页 URL 中的 data 就会保持空白 这是我的代码 from selenium import webdriver options webdriver Ch
  • 如何以相反的顺序打印文件中的行

    我正在尝试以相反的顺序打印文件 我正在使用数组来保存每行数据 到目前为止 我能够按正常顺序打印每一行 index 是我指的行数 FuncIndex 是同一件事 但已在函数中再次声明 file fopen quotes data r whil
  • 更改 spring-boot 中默认的 Mongo 连接池大小

    我想更改java mongodb驱动程序提供的连接池的默认大小根据 mongo 文档 这是 100 下面是我用来自定义连接池大小的mongo客户端bean 参考这个问题 https stackoverflow com questions 2
  • 解释这个 C 程序的输出

    在以下位置找到此代码C 谜题 http www gowrikumar com c index php include
  • Zend 打开 Zend/Application.php 失败

    好的 我对 Zend 还比较陌生 我创建了一个新的应用程序并开始构建基于的身份验证系统a guide http akrabat com zend auth tutorial 但是 服务器正在排除内部服务器错误 在检查 PHP 错误日志时 我
  • 如何使用System.Net.Mail设置退回邮件地址?

    我正在尝试实施可变信封返回路径 VERP http en wikipedia org wiki Variable envelope return path管理电子邮件地址的方法 即 当我发送的电子邮件被退回时 我希望将其发送到特定的电子邮件
  • 如何在我的 ejs 文件中包含 bootstrap 文件?

    因此 我已经使用 npm bootstrap 3 安装了 bootstrap 但是当我尝试在我的应用程序中包含来自 node modules 的 bootstrap min css 文件时 它在我的控制台中显示此错误 错误信息 在网络选项卡
  • 如何使用 capistrano 3 部署特定修订版

    如何使用 Capistrano 3 部署特定的 git 修订版 Capistrano 2 9 方法不再有效 cap S revision 80655da8d80aaaf92ce5357e7828dc09adb00993 deploy inv
  • 使用特征库从旋转矩阵中获取横摇、俯仰和偏航

    我需要从旋转矩阵中提取横滚 俯仰 偏航角 并且我想确保我所做的事情是正确的 Eigen Matrix lt simFloat 3 1 gt rpy orientation toRotationMatrix eulerAngles 0 1 2
  • 在过滤分支之后将每个人重新基于更改的 git 历史记录

    我们的 git 存储库历史上有一堆不再需要的大文件 我想使用 Pro Git 中解释的过滤分支技术删除它们 http git scm com book en v2 Git Internals Maintenance and Data Rec
  • Zoho API V2 更新记录

    我正在尝试使用 Zoho API 版本 2 在潜在客户中进行简单的记录更新 我使用 PHP 和 CURL 此调用的示例代码 更新记录中的单个字段 如下 apiUrl https www zohoapis com crm v2 Leads v
  • 如何在 Spring 中缩小动态 HTML 响应?

    遵循 Google 的 pagespeed 建议 我希望缩小 Spring 应用程序的 HTML 响应 我指的不是 GZip 而是在发送 HTML 之前从 HTML 中删除注释和空格 我想动态地执行此操作 而不是在我的模板中执行此操作 我的