Last active
July 8, 2023 04:03
-
-
Save virasak/64720 to your computer and use it in GitHub Desktop.
Embedded Jetty
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
* The web app uses the normal java servlet classes plus Jetty | |
*/ | |
import java.io.IOException; | |
import java.io.PrintWriter; | |
import javax.servlet.ServletException; | |
import javax.servlet.http.HttpServlet; | |
import javax.servlet.http.HttpServletRequest; | |
import javax.servlet.http.HttpServletResponse; | |
import org.mortbay.jetty.Server; | |
import org.mortbay.jetty.servlet.Context; | |
import org.mortbay.jetty.servlet.ServletHolder; | |
/** | |
* A very simple web-app using Jetty | |
*/ | |
public class HelloJetty extends HttpServlet { | |
public static void main(String[] args) throws Exception { | |
// Create a Jetty server listening on port 8001 | |
Server server = new Server(8001); | |
// Create a catch-all web-app context | |
Context root = new Context(server,"/",Context.SESSIONS); | |
// Add a servlet - this will respond to http://localhost:8001/hello | |
HttpServlet servlet = new HelloJetty(); | |
String path = "/hello"; | |
root.addServlet(new ServletHolder(servlet), path); | |
// Start the server | |
server.start(); | |
// That's it - the server will stay running until stopped | |
// via server.stop() or the program exiting | |
} | |
/** | |
* Handle a web page request in the normal J2EE way - by over-riding | |
* methods in HttpServlet. | |
*/ | |
@Override | |
protected void doGet(HttpServletRequest req, HttpServletResponse resp) | |
throws ServletException, IOException { | |
// Set mime type to html | |
resp.setContentType("text/html"); | |
// Write a web page | |
PrintWriter writer = resp.getWriter(); | |
writer.append("<html><body><h1>Hello World!</h1></body></html>"); | |
writer.close(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment