Vaadin 8 向 html head 标签添加代码的方式是什么?

Ret*_*ner 1 javascript vaadin vaadin8

其他 SO 答案建议覆盖ApplicationServlet.writeAjaxPageHtmlHeader,但我在 Vaadin 8 中找不到这些类和方法。

我在com.vaadin.server.VaadinServlet或 中找不到任何类似的东西com.vaadin.ui.UI

@JavaScript注释,但如果我把它放在我的 UI 类上,脚本将被加载到我的应用程序的每个页面。我只需要在一个特定的页面上使用它。

Mik*_*ika 5

初始 HTML 页面在 Vaadin 中称为引导页面。有一些文档提示您在Book of Vaadin 中找到正确的方向。

在 Vaadin 8 中,您需要将 BootstrapListener 添加到会话中。您可以通过在 VaadinServlet 中添加 SessionInitListener 来获取创建的会话。

注册会话

此示例将 Vaadin 与 Spring Boot 结合使用,但在不使用 Spring Boot 时也适用相同的原则。

@Component("vaadinServlet")
@WebServlet(urlPatterns = "/*", name = "BootstrapVaadinServlet", asyncSupported = true)
@VaadinServletConfiguration(ui = BoostrapUi.class, productionMode = false)
public class BootstrapVaadinServlet extends SpringVaadinServlet {
    private static final Logger logger = LoggerFactory.getLogger(BootstrapVaadinServlet.class);
    @Override
    protected void servletInitialized() throws ServletException {
        super.servletInitialized();
        getService().addSessionInitListener(this::addBoostrapListenerOnSessionInit);
    }

    private void addBoostrapListenerOnSessionInit(SessionInitEvent sessionInitEvent) {
        sessionInitEvent.getSession().addBootstrapListener(new AppBootstrapListener());
    }
}
Run Code Online (Sandbox Code Playgroud)

实现html head标签修改

public class AppBootstrapListener implements BootstrapListener {
    @Override
    public void modifyBootstrapFragment(BootstrapFragmentResponse bootstrapFragmentResponse) {

    }

    @Override
    public void modifyBootstrapPage(BootstrapPageResponse res) {
        Elements headTags = res.getDocument().getElementsByTag("head");
        Element head = headTags.get(0);
        head.appendChild(metaExample(res.getDocument()));
    }

    private Node metaExample(Document document) {
        Element meta = document.createElement("meta");
        meta.attr("author", "Me");
        return meta;
    }
}
Run Code Online (Sandbox Code Playgroud)