Search code examples
javamavenservletsuberjarfile-location

Can an HttpServlet inside an uber jar send a page located inside the jar?


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?


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