Lahiru Chandima Lahiru Chandima - 25 days ago 9
Java Question

Vaadin: adding a custom javascript to bootstrap page

I need to add jquery to bootstrap page of my vaadin application. I added following in my custom

Servlet
class

@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) {
}
});
}


This code sometimes throws a null pointer exception in
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:?]


What is the correct way to get the context path in this situation?

Answer

A much simpler way would be to use the @JavsScript annotation on your UI class

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

}

You will then need to put the two javascript files into a folder matching the class of YourUI. I use maven so it need to be in src/main/resources/com/company/mine/jquery.min.js

Comments