Servlet and HTTP Introduction Learning

http introduction: http is a set of specifications, a standard protocol for network data interaction, different languages, different data to achieve reasonable data interaction (for example, browser and server data interaction), you have to follow the protocol he prescribed, so that a standard (everyone knows) data interaction will be formed.

http interaction process:

1. A connection channel is established between client and server.

2. The client sends the request to the server.

3. The server responds to the client after processing the request.

4. The connection channel between client and server is closed. HTTP 1.1 will wait for a while and shut down if no request comes in.

Characteristic:

1. Data structure: It describes data structure in the form of key-value pairs.

2. Connectionless: A request is answered once, and the data interaction ends when the request is answered (the client and server are disconnected). After the request processing is completed in http 1.1, the client and server will not disconnect immediately, but will disconnect after waiting for a certain time. If there is a request coming during the waiting period, the waiting time will start again (extended).

3. Statelessness: When the first request is processed, the second request is sent, but even if the two requests use the same data, there is no relationship in http, so the second request still needs to repeat the first process. HTTP has no memory function, so even if the two requests are identical, their requests still need to send all the request data. This is statelessness.

4.http is based on TCP protocol to send data. The so-called TCP roughly means that data requests and data responses are made after the two ends are connected. UDP: Connections and requests are sent together and will not wait until the connection is smooth, so UDP protocol does not guarantee that data will be sent to the other end, but it is faster than TCP.

http request format:

1. Request Header Content: Request Mode (get, post...) Request Address (https://i.cnblogs.com/EditPosts.aspx?opt=1) http Protocol (1.0/1.1)

2. Request line, message header: This specification requires additional information for the server, general browsers will automatically encapsulate, such as: parsable data format, Cookie data needed by the client.

3. Empty Line

4. Request data

In actual requests, browsers display the contents of the above request format separately for easy viewing. For example, get requests bring the request data behind the request address.

http response format:

1. Response line: http version status code status message

2. Response Header: Message Header: Additional data between server and browser, such as message type of this response, etc.

3. Empty Line

4. Response Entities: Data for specific responses.

Additional explanation:

1. Message header: information in message header and information in request header response header. These information mainly explain the attributes of data interaction: for example, the format of this data: xml/json.. These data are processed automatically by server and browser without the concern of developers. Developers just add the data they need: Cookie, for example. These common configurations have been processed in the server, and browser vendors have also processed browsers, so programmers only need to care about request and response data.

So much for the overview of http above, here is Servlet:

The process of client requesting from browser: front-end web page source code - > browser request encapsulation (mainly message header and version information) - > server processing - > get post -> allocated to the corresponding interface logic of back-end according to different requests

Servlet's request flow: Web page request - > Servlet - > after the server receives the request, it finds the corresponding Servlet - > and then encapsulates the request information and the information to be responded into a request response object and passes it into the Service method of the responding Servlet object to call this method.

Okay, so much said, start coding:

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
     <!--To configure Servlet  -->
         <!--To configure servlet Class path  -->
         <servlet>
             <servlet-name>my</servlet-name>
             <servlet-class>cn.mr.li.MyServlet</servlet-class>
         </servlet>
         <!--Configuration access mode  -->
         <servlet-mapping>
             <servlet-name>my</servlet-name>
             <url-pattern>/my</url-pattern>
         </servlet-mapping>
</web-app>

servlet:

1.request scope: One request data scope is limited to the logical scope of this request, but data sharing, one request and one response can be achieved between multiple servlets by request forwarding.

2.Cookie: Client-side data storage technology, which is used to automatically carry requests, as to what to take, which paths to request, life cycle and so on, are set by the server. The response object then notifies the client to perform specific operations.

3. Redirecting: response.sendRedirfect(uri) can only prevent repeated refresh requests, but it cannot share data. It is not safe to put all data in a Cookie, and it is impossible to verify that the current Cookie is the same person.

4.session scope: The same object requests multiple data sharing.

5. Session Context Scope: Different objects request multiple data sharing.

6. The global variables in the web.xml file under the Tomcat server will be the data range shared by all servers.

package cn.mr.li;

import java.io.IOException;

import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class MyServlet extends HttpServlet{

    private static final long serialVersionUID = 8834328433966095720L;

    @Override
    public void service(HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
        //Coding from iso8859-1 Encoding and then converting utf-8,uname String is the variable name of the request
        String uname = new String(request.getParameter("uname").getBytes("iso8859-1"), "utf-8");
        //Newly build Cookie: take Cookie Put it in the client's header
        Cookie cookie = new Cookie("id", uname);
        //this Cookie The maximum life cycle, set the client will be stored in his own hard disk, life cycle will be deleted once it arrives, the default expiration period is the session, once the session closed, it will expire.
        cookie.setMaxAge(24 * 3600);
        //Add to the response Cookie,In this way, the client will be notified that the next request will bring the stored data.
        response.addCookie(cookie);
        //Set which paths and directories to access before you can take them with you cookie
        cookie.setPath("/Links after Port Number");
        
        /** Request Forwarding One Access Backend Logic Runs Multiple Servlet s, remember to add return*/
        //to Requset Add custom attributes
        request.setAttribute("key", "value:Given the parameters of the next process, this value is generated by the process. Here we can put one. Object Object");
        //Demonstration request forwarding,It means Ben. Servlet Having dealt with this Servlet Managed business will automatically move to the next Servlet Processing flow(Atomicity),
        //But if the client's web page is refreshed, it starts a request again, and if the money transfer business forwards the request, it's over.,He will transfer because the page refresh request will be transferred again, so it still depends on the specific business.
        request.getRequestDispatcher("Other sevlet Alias url-pattern Label").forward(request, response);
        
        /** Redirects multiple access to the headend notification front end, where the front end automatically accesses multiple servlets. 
         * But if there is an attribute in the request that is worth requesting. setAttribute, it cannot be brought in the next request because it is a different requse object, but session can solve it.*/
        //Because once the user requests to forward the page, it will be unsafe to refresh the page and run the process repeatedly, so there is a redirection.
        //Equivalent to this time Servlet After the processing business is completed, the client is notified directly to visit the next one. Servlet At this point, the client will automatically access the next Servlet
        response.sendRedirect("Pass directly to the next visit uri");
        
        /** Session A request object on the server, a complete object, such as: a User accessed the server: the server will use the User information of this User
         * If the query is put into Session, the next time the user requests a Servlet, he or she can even pass very few parameters.  */
        //Establish Session This method will follow Requset Of Cookie Take out his own SessionId,If not or not, a new one will be created Session object
        //And will SessionId Re placed Cookie Default SessionId Life cycle 30 minutes, once disconnected will be destroyed
        HttpSession session = request.getSession();//this session Is the object of the request sessionid Take it out.
        //to session Object assignment attribute value
        session.setAttribute("key", "Object type");
        //Set up session Life Cycle,Time unit:second
        session.setMaxInactiveInterval(123);
        //Coercive session Be overdue
        session.invalidate();
        
        /** ServletContext Object: The data of this object is shared by the whole server, that is to say, the data stored in this object can be obtained on the whole server, provided that the object can be obtained.  */
        ServletContext sc1 = this.getServletContext();//Mode 1
        sc1 = this.getServletConfig().getServletContext();//Mode 2
        sc1 = request.getServletContext();//Mode 3
        //Same assignment
        sc1.setAttribute("key", "Objcet");
        //Get global configuration web.xml
        sc1.getInitParameter("hahhahah");
        //Get all of the global configurations key name
        sc1.getInitParameterNames();
        
        /**ServletConfig Read the configuration of a Servlet specifically, and all key s will not need to be hard-coded after a second method*/
        ServletConfig config = this.getServletConfig();
        //read Servlet Exclusive variable name
        String value = config.getInitParameter("key");//web.xml init-param Label
        
        
        //Print text to browsers
        response.getWriter().write("hello world!!!");
    }
//    @Override
//    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.getWriter().write("do get!!!");
//    }
//    
//    @Override
//    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.getWriter().write("do post!!!");
//    }
//    
//    @Override
//    protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//        resp.getWriter().write("do put!!!");
//    }
}

Incidentally, the principle of jsp:jsp is that all the code in the html file is read into the Servlet and printed to the console by the output statement. The java code in the html file will read, execute the response logic and then print to the browser at its own location.

Tags: Java Session xml JavaEE

Posted on Wed, 08 May 2019 06:00:39 -0700 by daveh33