考虑到我正在运行http java servlet,我想让我的index.html有一个来自我的java servlet的警报。我在网上找到的大部分示例都是.jsp,但我使用的是html / html5实现。我希望能够使用javascript来调用我的服务器并显示服务器消息。
警报应显示字符串消息“这是响应”
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();
}
}
}
我有一个index.html如下
<!DOCTYPE HTML>
<html>
<body>
<script type="text/javascript">
function start() {
var eventSource = new EventSource("http://localhost:8000/test");
eventSource.onmessage = function(event) {
alert(event.data);
};
}
</script>
</body>
</html>