Deliver javascripts from jar

92 Views Asked by At

I have a java web application. Here I have some javascript files which I want to be inside a jar file. I want there will be a servlet which will deliver the javascript files from the jar. The feature is like DWR library. They have some javascript files which is not included in the file system. Rather they deliver the javascripts from the jar. DWRServlet class do that. But the path is included in the html header. I want to implement such a feature. Could you guys give me some idea how to implement that

1

There are 1 best solutions below

0
On BEST ANSWER

Resources in JARs are part of the classpath. You can get an InputStream of a classpath resource by ClassLoader#getResourceAsStream(). So, just let your Servlet do exactly that.

Assuming that you have those JS resources in /META-INF/resources of the JAR:

@WebServlet("/resources/*")
public class ResourceServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String path = request.getPathInfo();
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        InputStream input = loader.getResourceAsStream("/META-INF/resources" + path);

        if (input != null) {
            response.setContentType(getServletContext().getMimeType(path));
            OutputStream output = response.getOutputStream();
            // Now just write input to output the usual way.
        } else {
            response.sendError(404);
        }
    }

}

Then you can get /META-INF/resources/some.js of the JAR by http://localhost:8080/contextname/resources/some.js.