By using
ServletContextHandler, we can map urls to servlets. For example, following
application map ‘loclahost:8080’ to WelcomeServlet, and ‘localhost:8080/hello’
to HelloServlet.
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class HelloServlet extends HttpServlet { private static final long serialVersionUID = 1L; public HelloServlet() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Hello from HelloServlet</h1>"); } }
import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends HttpServlet { private static final long serialVersionUID = 1L; public WelcomeServlet() { super(); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); response.setStatus(HttpServletResponse.SC_OK); response.getWriter().println("<h1>Welcome Jetty programming</h1>"); } }
import org.eclipse.jetty.server.Server; import org.eclipse.jetty.servlet.ServletContextHandler; public class TestServlet { public static void main(String[] args) throws Exception { Server server = new Server(8080); ServletContextHandler context = new ServletContextHandler( ServletContextHandler.SESSIONS); context.setContextPath("/"); context.addServlet(HelloServlet.class, "/hello"); context.addServlet(WelcomeServlet.class, "/"); server.setHandler(context); server.start(); server.join(); } }
Run
TestServlet, and hit the urls ‘http://localhost:8080’, ‘http://localhost:8080/hello’
you will get following output.
Output for
‘http://localhost:8080’
Output for ‘http://localhost:8080/hello’
No comments:
Post a Comment