What is a servlet?
A servlet is a mediator between Web client and server interaction. Web pages to upload data, to get information, these require the servlet to receive the request, and then fetch the data from the server.
The servlet used in Java is HttpServlet, which has two common methods, doget (HttpServletRequest request, httpservletresponse response), DoPost (...) Handles the browser's get and post requests separately.
In general, we implement both methods, which is enough to handle common browser operations.
Two of these classes are particularly important:
1, HttpServletRequest This class records the browser request information, including the data sent, the Cookie, the Session, the header and so on can call the corresponding get method to obtain.
2, HttpServletResponse This class records the data that the server sends to the browser. including cookies, answer data, headers, etc. can be set by invoking the corresponding set method.
It can be said that this two class is the key to the server communication with the browser (client).
So what is a cookie and what is a session?
As is known to all, the HTTP protocol is stateless, but many of the requirements in the real world require us to preserve the state of an HTTP connection, such as a shopping cart. In this case, there are two solutions:
1, client, cookie. A cookie is a text field. By the health value pair, the expiration time, the domain name, the path name four parts compose.
The server segment invokes the cookie class to create a new cookie and then calls Response.addcookie (cookie) to send to the client.
After the client receives it and saves it, within the valid time valid path, each subsequent request adds a cookie field, so the server side knows the client's previous state.
The cookie class has a series of methods to set cookie information. Call Request.getcookies () when you get the cookie.
2, server side, session. Session is also a text field. Saved on the server side. Each time the server calls Request.getsession (True) (the access JSP automatically creates the session), the session is created, and a SessionID is created automatically to identify the client.
This sessionid does not need to be sent manually to the client, the server will be sent automatically (usually via a cookie). Java processing session mainly relies on the HttpSession class.
We can use it to set various properties for the session to save the client information. The client only needs one save SessionID, and the other information is saved on the server side.
The client takes SessionID on each request, so that a stateless HTTP connection becomes stateful.
The session will expire when it reaches the effective time, and we can manually call the invalidate () method to invalidate it.
Introduction to Java servlet