Vaadin:在bootstrap页面添加自定义javascript

时间:2016-11-10 13:14:40

标签: java vaadin

我需要将jquery添加到我的vaadin应用程序的bootstrap页面。我在自定义Servlet

中添加了以下内容
@Override
public void sessionInit(SessionInitEvent event) throws ServiceException {
    event.getSession().addBootstrapListener(new BootstrapListener() {
        @Override
        public void modifyBootstrapPage(BootstrapPageResponse response) {
            //Jquery is necessary for open in new window button
            String contextPath = event.getRequest().getContextPath();
            response.getDocument().head().prependElement("script").attr("type", "text/javascript").attr("src", contextPath + "/VAADIN/js/jquery.min.js");
            response.getDocument().head().prependElement("script").attr("type", "text/javascript").attr("src", contextPath + "/VAADIN/js/jquery-ui.js");
        }

        @Override
        public void modifyBootstrapFragment(BootstrapFragmentResponse response) {
        }
    });
}

此代码有时会在event.getRequest().getContextPath();

中抛出空指针异常
Caused by: java.lang.NullPointerException
at org.apache.catalina.connector.Request.getServletContext(Request.java:1598) ~[catalina.jar:8.0.24]
at org.apache.catalina.connector.Request.getContextPath(Request.java:1915) ~[catalina.jar:8.0.24]
at org.apache.catalina.connector.RequestFacade.getContextPath(RequestFacade.java:783) ~[catalina.jar:8.0.24]
at javax.servlet.http.HttpServletRequestWrapper.getContextPath(HttpServletRequestWrapper.java:150) ~[servlet-api.jar:?]
at com.mycompany.MyServlet$1.modifyBootstrapPage(YaanServlet.java:56) ~[web-yaan-ui-base-1.3.39.jar:?]

在这种情况下获取上下文路径的正确方法是什么?

1 个答案:

答案 0 :(得分:3)

更简单的方法是在UI类上使用@JavsScript注释

package com.company.mine;
@JavaScript({"jquery.min.js","jquery-ui.js"})
public class YourUI extends UI 
{

}

然后,您需要将两个javascript文件放入与YourUI类匹配的文件夹中。我使用maven所以它需要在src / main / resources / com / company / mine / jquery.min.js