Java纯手打web服务器(二)

概要:这里对上一篇中的访问资源进行改进,将访问servlet和静态资源进行区分。 主要不同的地方是加入了两种分析器

servlet分析器
if (request.getUri().startsWith("/servlet/")) {
          ServletProcessor1 processor = new ServletProcessor1();
          processor.process(request, response);
        }
      内部代码:
public void process(Request request, Response response) {

    String uri = request.getUri();
    String servletName = uri.substring(uri.lastIndexOf("/") + 1);
    URLClassLoader loader = null;

    try {
      // 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);
      loader = new URLClassLoader(urls);
    }
    catch (IOException e) {
      System.out.println(e.toString() );
    }
    Class myClass = null;
    try {
      myClass = loader.loadClass(servletName);
    }
    catch (ClassNotFoundException e) {
      System.out.println(e.toString());
    }

    Servlet servlet = null;

    try {
      servlet = (Servlet) myClass.newInstance();
      servlet.service((ServletRequest) request, (ServletResponse) response);
    }
    catch (Exception e) {
      System.out.println(e.toString());
    }
    catch (Throwable e) {
      System.out.println(e.toString());
    }
  }
  • 首先实例类加载器,这里用到urlClassLoader,可以对jar包和class类文件进行加载,制定加载的类文件位置。
  • 加载类,并实例化,调用servlet相应的service方法,在service方法中对客户端进行消息返回:
public void service(ServletRequest request, ServletResponse response)
    throws ServletException, IOException {
    System.out.println("from service");
    PrintWriter out = response.getWriter();
    out.println("Hello. Roses are red.");
    out.print("Violets are blue.");
  }
静态化文件分析器
StaticResourceProcessor processor = new StaticResourceProcessor();
  processor.process(request, response);

process方法调用上一篇中response返回静态文件的方法sendStaticResource。

posted @ 2020-09-24 18:30  好奇成传奇  阅读(90)  评论(0编辑  收藏  举报