The previous article said that in the early days of web development, users could only view static pages. With the development of the web, the web that can only display static pages has not been able to meet the needs of the public, so there are CGI and Java-written servlet programs.
The servlet can dynamically generate an HTML page based on the user's request and then send it to the browser.
Here's a simulation of the process:
- HttpServer2 class: Server class, responsible for starting the HTTP service.
- Servlet interface: Defines the servlet service interface.
- HelloServlet class: Implements the Servlet interface. When a user submits a request, HttpServer2 sends the request to HelloServlet processing. The dynamically generated page is returned to the user after processing.
- ServletRequest class: Encapsulates the user's request. Give HelloServlet to handle.
- Servletresponse class: Encapsulates the returned response. Returned by HelloServlet.
HttpServer2 class
The server class that is responsible for starting the HTTP service.
Importjava.io.*;Importjava.net.*; Public class HttpServer2 { Private Static Final intPort =8088;PrivateServerSocket ServerSocket =NULL; Public HttpServer2()throwsIOException {ServerSocket =NewServerSocket (port); System.out.println ("Httpserver startup ok ..."); } Public void Work()throwsIOException { while(true) {Try{Socket socket = serversocket.accept (); ServletRequest request =NewServletRequest (Socket.getinputstream ()); Servletresponse response =NewServletresponse (Socket.getoutputstream ()); System.out.println ("Receive request:\n"+ request.getrequest ()); String servletname = Request.getservletname (); ? ?//Dynamic servlet generationservlet servlet = (servlet) class.forname (servletname). newinstance (); ?//Invoke Servlet interfaceServlet.init (); Servlet.service (request, response); Servlet.destroy (); Socket.close (); }Catch(Exception e) {//TODO auto-generated catch blockE.printstacktrace (); } } } Public Static void Main(string[] args)throwsIOException, interruptedexception {HttpServer2 httpserver =NewHttpServer2 (); Httpserver.work (); }}
Servlet interface
Defines the Servlet service interface.
publicinterface Servlet { publicvoidinit(); publicvoidservice(ServletRequest req, ServletResponse res) throws Exception; publicvoiddestroy();}
HelloServlet class
Implements the servlet interface. When a user submits a request, HttpServer2 sends the request to HelloServlet processing. The dynamically generated page is returned to the user after processing is finished.
Public class helloservlet implements Servlet { @Override Public void Init() {//TODO auto-generated method stubSystem.out.println ("servlet Init"); }@Override Public void Service(ServletRequest req, servletresponse Res)throwsException {//TODO auto-generated method stubString ContentType = Req.getcontenttype (); String param = Req.getparam (); ?//Assemble HTTP response headersString Header = Res.assembleresponseheader (ContentType); ?//Assemble HTTP response bodyString BODY = res.assembleresponsebody (param); ?//Return responseRes.write (header + body); }@Override Public void Destroy() {//TODO auto-generated method stubSystem.out.println ("servlet destroy"); }}
ServletRequest class
Encapsulates the user's request. Handed over to helloservlet for processing.
ImportJava.io.IOException;ImportJava.io.InputStream; Public class servletrequest { PrivateString request;PrivateInputStream Socketin;PrivateString URI;PrivateString ContentType;PrivateString param; Public ServletRequest(InputStream Socketin)throwsIOException {//TODO auto-generated constructor stub This. Socketin = Socketin; This. Request = _getrequest (); This. URI = _geturi (); This. ContentType = _getcontenttype (); This. param = _getparam (); } PublicStringgetrequest() {returnRequest } PublicStringGetURI() {returnURI; } PublicStringgetContentType() {returnContentType; } PublicStringGetParam() {returnParam }PrivateString_getrequest()throwsIOException {intSize = Socketin.available ();byte[] Requestbuff =New byte[Size]; Socketin.read (Requestbuff);return NewString (Requestbuff); } ?//Get the class name to invoke the servlet PublicStringGetservletname(){returnUri.substring (Uri.indexof ("/") +1, Uri.indexof ("?")); }PrivateString_geturi() {String firstline = request.substring (0, Request.indexof ("\ r \ n")); string[] Parts = Firstline.split (" ");returnparts[1]; }PrivateString_getcontenttype() {/ * Determines the type of HTTP response body * / return "HTML"; }//Get request Parameters PrivateString_getparam() {String paramstring = uri.substring (Uri.indexof ("?") +1); string[] Parampairs = Paramstring.split ("=");returnparampairs[1]; }}
Servletresponse class
Encapsulates the returned response. Returned by HelloServlet.
ImportJava.io.IOException;ImportJava.io.OutputStream; Public class servletresponse { PrivateOutputStream OutputStream; Public Servletresponse(OutputStream OutputStream) {//TODO auto-generated constructor stub This. outputstream = OutputStream; } PublicStringAssembleresponseheader(String ContentType) {/ * Create HTTP response results * / the first line of the//HTTP responseString Responsefirstline ="http/1.1 ok\r\n";//HTTP response headerString Responseheader ="Content-type:"+ ContentType +"\r\n\r\n";returnResponsefirstline + Responseheader; } PublicStringAssembleresponsebody(String param) {String content ="<body>+ param +"; String title ="; String BODY ="+ Title + content +";returnBody } Public void Write(String Res)throwsIOException {outputstream.write (res.getbytes ()); }}
Test
Enter Http://localhost:8088/HelloServlet?username=tom in the Chrome browser.
That is, the user requested the parameter is Tom, to call HelloServlet. (In the actual servlet implementation, a URI-to-servlet mapping is implemented with a WEB.XM configuration file.)
?
The servlet parses out and assembles the HTML back into the browser. Display as Hello:tom
Java implementation of HTTP Server simulation with servlet technology