Chapter2 explains how simple servlet containers work. This chapter comes with two servlet container applications that can service requests for static resources as well as very simple servlets. In particular, you will learn how you can create request and response objects and pass them to the requested servlet’s service method. There is also a servlet that can be run inside the servlet containers and that you can invoke from a web browser.
publicclassHttpServer1{ publicstaticvoidmain(String[] args){ HttpServer1 server = new HttpServer1(); server.await(); }
publicvoidawait(){ ServerSocket serverSocket = null; int port = 8080; serverSocket = new ServerSocket(port, 1, InetAddress.getByName("127.0.0.1"));
// Loop waiting for a request while (!shutdown) { Socket socket = serverSocket.accept(); InputStream input = socket.getInputStream(); OutputStream output = socket.getOutputStream();
// create Request object and parse Request request = new Request(input); request.parse();
// create Response object Response response = new Response(output); response.setRequest(request);
// check if this is a request for a servlet or a static resource // a request for a servlet begins with "/servlet/" if (request.getUri().startsWith("/servlet/")) { ServletProcessor1 processor = new ServletProcessor1(); processor.process(request, response); } else { StaticResourceProcessor processor = new StaticResourceProcessor(); processor.process(request, response); }
// Close the socket socket.close(); //check if the previous URI is a shutdown command shutdown = request.getUri().equals(SHUTDOWN_COMMAND); } } }
// create a URLClassLoader URL[] urls = new URL[1]; URLStreamHandler streamHandler = null; File classPath = new File(Constants.WEB_ROOT);
// the forming of repository is taken from the createClassLoader // method in org.apache.catalina.startup.ClassLoaderFactory String repository = (new URL("file", null, classPath.getCanonicalPath() + File.separator)).toString();
// the code for forming the URL is taken from the addRepository // method in org.apache.catalina.loader.StandardClassLoader class. urls[0] = new URL(null, repository, streamHandler); URLClassLoader loader = new URLClassLoader(urls);