Question

I'm writing a localhost web/websocket application bundled inside an uber jar.

It's a single-page site, and the HttpServlet will send the html that communicates with the WebSocket server. I'd like the page to remain inside the jar and have the HttpServlet be able to load it from there and send it to the client.

Is this possible? If so, how?

Was it helpful?

Solution

An HttpServlet can return whatever it wants, all you need to do is set what you want in the response.

I'm guessing the answer you are actually looking for looks something like this though

public class MyServlet extends HttpServlet {
    public void doGet(HttpServletRequest request, HttpServletResponse response) {
        PrintWriter out = response.getWriter();
        InputStream input = this.class.getResourceAsStream("/path/to/this.html");
        BufferedReader reader = new BufferedReader(new InputStreamReader(input));
        String line;
        while ((line = reader.readLine()) != null) {
            out.println(line);
        }
    }
}

OTHER TIPS

It's not clear what you are asking for.

If you are trying to load a file from the classpath (for example in a jar), you can do it in this way

public class Test {

    public static void main(String[] args) {
        InputStream resourceAsStream = Test.class.getResourceAsStream("/test.html");
        // use the stream here...
        System.out.println(resourceAsStream);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top