Web-to-service simple principle example

Source: Internet
Author: User

That's the current understanding

Attach the source of the service side

Package Com.lsw.server;import java.io.*;import java.net.*;import java.util.hashmap;import java.util.Map;/* * About servers, In addition to the HttpServer1 class, a servlet interface is defined, which has an init () and a service () method, the Init () method is the initialization method, and when the HTTPServer1 class creates an instance of the interface's class, The init () method of the instance is called immediately by the Service () method: The user responds to the HTTP request, producing a specific HTTP response result. * The HTTPSERVER1 server invokes the service () method of a specific class of the Servlet interface in response to an HTTP request * The so-called Web server dynamically executes the program code. In this example, it means that httpServer1 dynamically loads the Servlet interface's implementation class at run time, creating his instance. Then call his related method. * HTTPServer1 uses the functionality of the dynamic load class of the Java language in its implementation *///dynamically executes public class HTTPServer1 {//caches the cache for Selvlet instances private static Map servletc        ache = new HashMap ();        public static void Main (string[] args) {int port;                ServerSocket ServerSocket;            try{port = integer.parseint (Args[0]);        SYSTEM.OUT.PRINTLN ("Default port is:" + port);            } catch (Exception e) {System.out.println ("Default port 8080");        Port = 8080;            } try{//create listener Port ServerSocket = new ServerSocket (port); System.out.printlN ("Server is listening on port:" + serversocket.getlocalport ()); while (true) {try{//waits for a client's link request final socket socket = Serversocket.acce                    PT (); SYSTEM.OUT.PRINTLN ("Established a new TCP connection with the customer, the address of the customer is:" + socket.getinetaddress () + "Port is:" + socket.                    Getport ());                Respond to Customer request service (socket);                } catch (Exception e) {e.printstacktrace ();        }}} catch (Exception e) {e.printstacktrace (); }} public static void service (socket socket) throws exception{//Read HTTP request information InputStream Socketin = Socket.getinputstream ();        Get input stream//Sleep 500 milliseconds, wait for HTTP request Thread.Sleep (500);        int size = socketin.available ();        byte[] buffer = new Byte[size];        Socketin.read (buffer);        String request = new string (buffer);   Print HTTP request data     SYSTEM.OUT.PRINTLN ("The data requested by the client is:" +request);        Parse HTTP request//Get HTTP request first line String firstlineofrequest = request.substring (0,request.indexof ("\ r \ n"));        System.out.println ("firstlineofrequest=" +firstlineofrequest);        Parse the first line of the HTTP request string[] parts = Firstlineofrequest.split ("");        Parse HTTP request this URI String URI = parts[1];        SYSTEM.OUT.PRINTLN ("Parsing HTTP request this uri=" + URI);        System.out.println ("value =" + uri.substring (0, 1). ToString ());        String flag = uri.substring (0, 1). ToString ();            if (Flag.equals ("/")) {System.out.println ("This request is a request initiated from the browser");        URI = uri.substring (1). ToString ();                } System.out.println ("Parse HTTP request this uri=" + URI); If the request calls the servlet, call the Servlet's service method dynamically if (Uri.indexof ("Httptest")! =-1) {//Get the name of the servlet stri            ng servletname = null; if (Uri.indexof ("?")! =-1) servletname = uri.substring (Uri.indexof ("httptest/") +8, Uri.indexof ("?"));            else Servletname = uri.substring (Uri.indexof ("httptest/") +8, Uri.length ());            Flag = "";            Flag = servletname.substring (0, 1). ToString ();            if (Flag.equals ("/")) {servletname = servletname.substring (1). ToString ();            }//Try to go back from the servlet cache to the Servlet object servlet servlet = (Servlet) servletcache.get (servletname); If the servlet is cached in this nonexistent Servlet object, create him and put him in the servlet cache if (servlet = = null) {servlet = (servlet) Class. Forname ("Com.lsw.server.")                +servletname). newinstance ();                Servlet.init ();            Servletcache.put (Servletname, servlet);                        }//Call the servlet's service () method Servlet.service (buffer, socket.getoutputstream ());            Sleep 1 seconds waiting to receive HTTP response results thread.sleep (1000);            Socket.close ();        return; }            }}

Interface Source Code

Package Com.lsw.server;import Java.io.outputstream;public Interface Servlet {public    void init () throws exception;< c2/>public void Service (byte[] requestbuffer,outputstream out) throws Exception;}

Implement class source code

Package Com.lsw.server;import Java.io.outputstream;public class HelloServlet implements Servlet {@Override public v    OID Init () throws Exception {System.out.println ("HelloServlet is inited"); } @Override public void service (byte[] Requestbuffer, outputstream out) throws Exception {String        Request = new String (requestbuffer);                Print HTTP request Data System.out.println ("The data requested by the client is:" +request);        Parse HTTP request//Get HTTP request first line String firstlineofrequest = request.substring (0,request.indexof ("\ r \ n"));        System.out.println ("firstlineofrequest=" +firstlineofrequest);        Parse the first line of the HTTP request string[] parts = Firstlineofrequest.split ("");        Get the request method in the HTTP request String method = Parts[0];        SYSTEM.OUT.PRINTLN ("Parsing HTTP request Mode Method=" + method);        Parse HTTP request this URI String URI = parts[1];        SYSTEM.OUT.PRINTLN ("Parsing HTTP request this uri=" + URI); System.out.println ("value =" + uri.substring (0, 1). ToString ());        String flag = uri.substring (0, 1). ToString ();            if (Flag.equals ("/")) {System.out.println ("This request is a request initiated from the browser");        URI = uri.substring (1). ToString ();                } System.out.println ("Parse HTTP request this uri=" + URI);        Get request parameter username String username = null;            If the request method is get, the request parameter immediately follows the URI of the first line of the HTTP request (Method.equalsignorecase ("get") && Uri.indexof ("username=")!=-1) { Assume uri= "Servlet/helloservlet?username=tom&password=1234 "//parameters=" Username=tom&password=1234 "String parameters = uri.substring (Uri.indexof ("? "), Uri.length ());            parts={"Username=tom", "password=1234"} parts = Parameters.split ("&");            parts={"username", "Tom"} parts = parts[0].split ("=");        Username = parts[1]; }//If the request method is post, the request parameter is in the body of the HTTP request if (Method.equalsignorecase ("POST")) {int locate = Reque            St.indexof ("\r\n\r\n");            Get response body String content = request.substring (Locate+4,request.length ()); if (Content.indexof ("username=")!=-1) {//Assume content= "Username=tom&password=1234 "//parts=" Username=tom&password=1234 "parts = Content.split (" & ");                Parts = parts[0].split ("=");            Username = parts[1]; }}//create HTTP response to send response//Send HTTP response First line "Out.write (" http/1.1 ok\r\n ". GetByte        s ());        Send HTTP response header out.write ("content-type:text/html\r\n\r\n". GetBytes ()); Send HTTP response body out.write ("<HTML><Head><title>HelloWorld</title></Head></Body>". GetBytes ()); Out.write (New String ("<H1>Hello: "+ username +"</H1></Body></Head></HTML>"). GetBytes ()); }}

Web-to-service simple principle example

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.