title: Is it possible to get HTML Response in a Java Servlet
body: <p>Considering that I am running http java servlet, I would like to have my index.html have an alert from my java servlet. Most of the example I found on web are of .jsp but I am using html/html5 implementation. I would like to be able use javascript to call my server and display the server message.</p>
  
  <p>The alert should display the String message "This is the response"</p>
  
  <pre><code>import java.io.IOException;
  import java.io.OutputStream;
  import java.net.InetSocketAddress;
  
  import com.sun.net.httpserver.HttpExchange;
  import com.sun.net.httpserver.HttpHandler;
  import com.sun.net.httpserver.HttpServer;
  
  public class JavaHttpServer {
  
      public static void main(String[] args) throws Exception {
          HttpServer server = HttpServer.create(new InetSocketAddress(8000), 0);
          server.createContext("/test", new MyHandler());
          server.setExecutor(null); // creates a default executor
          server.start();
      }
  
      static class MyHandler implements HttpHandler {
          @Override
          public void handle(HttpExchange t) throws IOException {
              String response = "This is the response";
              t.sendResponseHeaders(200, response.length());
              OutputStream os = t.getResponseBody();
              os.write(response.getBytes());
              os.close();
          }
      }
  
  }
  </code></pre>
  
  <p>I have a index.html as follows</p>
  
  <pre><code>&lt;!DOCTYPE HTML&gt;
  &lt;html&gt;
  &lt;body&gt;
  
      &lt;script type="text/javascript"&gt;
      function start() {
  
          var eventSource = new EventSource("http://localhost:8000/test");
  
        eventSource.onmessage = function(event) {
  
      alert(event.data);
  
          };
  
      }
      &lt;/script&gt;
  &lt;/body&gt;
  &lt;/html&gt;
  </code></pre>