Deep Anatomy tomcat-Chapter II: A Simple servlet container (1)

Source: Internet
Author: User

Content: In the previous chapter on the basis of the servlet processing, the focus is ServletProcessor1 this class, the use of URLs, URLClassLoader (can see the document) and the Java reflection mechanism.

Webroot

public class HttpServer1 {private static final String Shutdown_command = "/shutdown";p rivate boolean SHUTDOWN = False;publ IC void await () {ServerSocket ServerSocket = null;int Port = 8080;try {serversocket = new ServerSocket (port, 1, Inetaddres S.getbyname ("127.0.0.1"));} catch (IOException e) {e.printstacktrace (); System.exit (1);} while (!shutdown) {Socket socket = null;inputstream input = Null;outputstream output = null;try {socket = SERVERSOCKET.ACC EPT (); input = Socket.getinputstream (); output = Socket.getoutputstream (); Request Request = new request (input); Request.parse (); Response Response = new Response (output), response.setrequest (Request), if (Request.geturi (). StartsWith ("/servlet/")) {ServletProcessor1 processor = new ServletProcessor1 ();p rocessor.process (request, response);} else {Staticresourceprocessor processor = new Staticresourceprocessor ();p rocessor.process (request, response);} Socket.close (); shutdown = Request.geturi (). Equals (Shutdown_command); catch (Exception e) {E.printstacKtrace (); System.exit (1);}} public static void Main (string[] args) {HttpServer1 server = new HttpServer1 (); System.out.println ("Start"); Server.await ();}}

public class Request implements Servletrequest{private InputStream input;private String uri;public Request (inputstream InputStream) {this.input = InputStream;} Public String GetURI () {return this.uri;} private string Parseuri (string requeststring) {int index1, index2;index1 = Requeststring.indexof ("); if (index1! =-1) {I Ndex2 = Requeststring.indexof (", index1 + 1), if (Index2 > Index1) return requeststring.substring (index1 + 1, index2);} return null;} public void Parse () {StringBuffer request = new StringBuffer (2048); int i;byte bytes[] = new Byte[2048];try {i = Input.read (bytes);} catch (IOException e) {e.printstacktrace (); i =-1;} for (int j = 0; J < i; j + +) Request.append ((char) bytes[j]); System.out.print (Request.tostring ()); URI = Parseuri (request.tostring ());} @Overridepublic Asynccontext Getasynccontext () {return null;} @Overridepublic Object getattribute (String arg0) {return null;} @Overridepublic enumeration<string> Getattributenames () {return null;} @Overridepublic String GETcharacterencoding () {return null;} @Overridepublic int Getcontentlength () {return 0;} @Overridepublic long Getcontentlengthlong () {return 0;} @Overridepublic String getContentType () {return null;} @Overridepublic Dispatchertype Getdispatchertype () {return null;} @Overridepublic ServletInputStream getInputStream () throws IOException {return null;} @Overridepublic String getlocaladdr () {return null;} @Overridepublic String Getlocalname () {return null;} @Overridepublic int Getlocalport () {return 0;} @Overridepublic Locale GetLocale () {return null;} @Overridepublic enumeration<locale> Getlocales () {return null;} @Overridepublic string GetParameter (String arg0) {return null;} @Overridepublic map<string, string[]> Getparametermap () {return null;} @Overridepublic enumeration<string> Getparameternames () {return null;} @Overridepublic string[] Getparametervalues (String arg0) {return null;} @Overridepublic String Getprotocol () {return null;} @Overridepublic BufferedReader Getreader () throws IOexception {return null;} @Overridepublic string Getrealpath (String arg0) {return null;} @Overridepublic String getremoteaddr () {return null;} @Overridepublic String Getremotehost () {return null;} @Overridepublic int Getremoteport () {return 0;} @Overridepublic requestdispatcher getrequestdispatcher (String arg0) {return null;} @Overridepublic String Getscheme () {return null;} @Overridepublic String getServerName () {return null;} @Overridepublic int Getserverport () {return 0;} @Overridepublic ServletContext Getservletcontext () {return null;} @Overridepublic Boolean isasyncstarted () {return false;} @Overridepublic Boolean isasyncsupported () {return false;} @Overridepublic Boolean issecure () {return false;} @Overridepublic void RemoveAttribute (String arg0) {} @Overridepublic void SetAttribute (String arg0, Object arg1) {}@ overridepublic void setcharacterencoding (String arg0) throws unsupportedencodingexception {} @Overridepublic Asynccontext Startasync () throws illegalstateexception {return null;} @OverridePublic Asynccontext Startasync (ServletRequest arg0, Servletresponse arg1) throws illegalstateexception {return null;}} 
public class Response implements Servletresponse {private static final int buffer_size = 1024;private Request request;priv Ate outputstream output;private printwriter writer;public Response (outputstream output) {this.output = output;} public void Setrequest (Request request) {this.request = Request;} public void Sendstaticresource () throws IOException {byte bytes[] = new Byte[buffer_size]; FileInputStream fis = null;try {File File = new file (Constants.web_root, Request.geturi ()); FIS = new FileInputStream (file) ; int ch = fis.read (bytes, 0, Buffer_size), while (ch =-1) {output.write (bytes, 0, ch); ch = fis.read (bytes, 0, Buffer_size );}} catch (FileNotFoundException e) {String errormessage = "http/1.1 404 File Not found\r\n" + "content-type:t ext/html\r\n "+" content-length:23\r\n "+" \ r \ n "+" 
public class Constants {public  static final String web_root =    system.getproperty ("User.dir") + file.separator< c2/>+ "Webroot";}

public class Staticresourceprocessor {public void process (Request request, Response Response) {try { Response.sendstaticresource ();} catch (IOException e) {e.printstacktrace ();}}}

public class ServletProcessor1 {public void process (Request request, Response Response) {String uri = Request.geturi (); String servletname = uri.substring (Uri.lastindexof ("/") + 1); URLClassLoader loader = null;try {URL urls[] = new URL[1]; URLStreamHandler streamhandler = null;    File ClassPath = new file (constants.web_root);    String repository = (new URL ("file", NULL, Classpath.getcanonicalpath () + file.separator)). ToString ();    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 ());}}}


Deep Anatomy tomcat-Chapter II: A Simple servlet container (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.