1

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?

Charles
  • 50,943
  • 13
  • 104
  • 142
  • You shouldn't send a page if you're on a single-page site... Also, what is an uber jar? – Elliott Frisch Jan 13 '14 at 21:19
  • @ElliottFrisch Thank you for looking Elliot Frisch! My app is a self-contained webapp. The `HttpServlet` sends the only html file with all of the css, javascript, etc to the user so the user can connect and interact with the WebSocket side of the server. In other words, hopefully the user will be able to execute the jar, open up the browser, and go to `https://localhost` (or some other port if necessary), and have everything in one shot. This is an uber jar: http://stackoverflow.com/questions/11947037/what-is-an-uber-jar –  Jan 13 '14 at 21:56

2 Answers2

0

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);
        }
    }
}
Stefan Nuxoll
  • 867
  • 5
  • 15
  • That was the bulk of the answer. You can access any file inside of a JAR as a resource, line 4/5 of the answer has the relevant code to do that (getResourceAsStream and placing it into a BufferedReader). – Stefan Nuxoll Jan 13 '14 at 22:01
  • 1
    @Gracchus It actually references the classpath, not a specific JAR. You can have /path/to/this.html in any JAR inside your classpath and this will load it. You may find http://docs.oracle.com/javase/7/docs/api/java/lang/Class.html#getResourceAsStream%28java.lang.String%29 useful. – Stefan Nuxoll Jan 13 '14 at 22:04
0

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