In embedded jetty, sometimes we want to run some servlets, we need to create a context, and then let our servlet run in these servletcontext.
Package hb.jetty;
Import java.io.IOException;
Import Javax.servlet.ServletConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Class Myservlet extends httpservlet{
@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp)
throws Servletexception, IOException {
System.out.println ("Doget myservlet");
}
@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
throws Servletexception, IOException {
System.out.println ("DoPost myservlet");
Super.dopost (req, resp);
}
@Override public
void init (ServletConfig servletconfig) throws Servletexception {
System.out.println (" Myservlet ");
}
}
Package hb.jetty;
Import java.io.IOException;
Import Javax.servlet.ServletConfig;
Import javax.servlet.ServletException;
Import Javax.servlet.http.HttpServlet;
Import Javax.servlet.http.HttpServletRequest;
Import Javax.servlet.http.HttpServletResponse;
Class MyServlet2 extends httpservlet{
@Override
protected void doget (HttpServletRequest req, HttpServletResponse resp)
throws Servletexception, IOException {
System.out.println ("Doget MyServlet2");
}
@Override
protected void DoPost (HttpServletRequest req, HttpServletResponse resp)
throws Servletexception, IOException {
System.out.println ("DoPost MyServlet2");
Super.dopost (req, resp);
}
@Override public
void init (ServletConfig servletconfig) throws Servletexception {
System.out.println (" MyServlet2 ");
}
}
Package hb.jetty;
Import Org.eclipse.jetty.server.Server;
Import Org.eclipse.jetty.servlet.ServletContextHandler;
Import Org.eclipse.jetty.servlet.ServletHolder;
public class Servletcontextserver {public
static void Main (string[] args) throws Exception {
//TODO Auto-generat Ed method stub
Server server = new server (8080);
Servletcontexthandler context = new Servletcontexthandler (servletcontexthandler.sessions);
Equivalent to the engineering directory, if it is myweb, then http://localhost:port/myweb/
context.setcontextpath ("/");
Server.sethandler (context);
Http://localhost:8080/servlet1
Context.addservlet (New Servletholder (New Myservlet ()), "/servlet1");
HTTP://LOCALHOST:8080/SERVLET1/2
Context.addservlet (New Servletholder (New MyServlet2 ()), "/SERVLET1/2");
Server.start ();
Server.join ();
}
}