Cookies and Session are both intended to maintain user access status. On the one hand, it is to facilitate business implementation, and on the other hand, it is to simplify server programming and improve access performance. Cookies are technology of the client (that is, browser). After setting cookies, every time you visit the server, cookies will be brought in the request; Session is technology of the server, which stores user access information on the server.
Use cookies to deliver information. As the number of cookies increases and the number of visits increases, the bandwidth it consumes will become larger and larger; when using Session to save information, the biggest weakness is that it is not easy to share between multiple servers.
1 Cookies
In layman's terms, when a user accesses the server using HTTP, the server will return some key-value pair information to the client browser and add some restrictions to these data. When the user meets the restrictions, the next time the user accesses the server, he will bring the cookie key-value pair information set previously. When the user enters a URL, the browser looks for the cookies associated with the URL on the local hard drive. If the cookie exists, the browser sends the cookie to your site along with the page request.
Cookies are associated with websites, not with specific pages. Therefore, regardless of which page in the site the browser and server will exchange cookie information. When a user visits different sites, each site may send a cookie to the user's browser; the browser will store all cookies separately.
Cookie attribute item
There are currently 2 versions of cookies, Version 0 and Version 1. They have 2 types of response header identifiers, namely "Set-Cookie" and "Set-Cookie2".
Cookie 0 attribute value
Cookie 1 attribute value
Example of using cookies in Java
@Overridepublic void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {response.setContentType("text/html;charset=utf-8");PrintWriter out = response.getWriter();Cookie[] cookies = request.getCookies();String name = getCoodie(cookies, "name");if (name == null) {response.addCookie(new Cookie("name", "luoxn28"));}else {System.out.println(name);}out.println("hello world");}public static String getCoodie(Cookie[] cookies, String key) {if (cookies != null) {for (Cookie cookie : cookies) {if (cookie.getName().equals(key)) {return cookie.getValue();}}}return null;}Some precautions for using cookies (taking Java usage as an example)
• The name and value of the cookie created cannot be non-ASSIC characters. If it is Chinese, it can be encoded through RRLEncoder, otherwise a java.lang.IllegalArgumentException exception will be thrown.
•When multiple names and value values appear, they are actually in the same "Cookie" header.
•The value of Cookies can save punctuation marks other than ";". But Chinese characters cannot be saved. Garbage will appear when saving Chinese characters.
Some restrictions on cookies
A cookie is a field in the HTTP header. HTTP itself has no restrictions on this field, but cookies are eventually stored in the browser. Different browsers have some restrictions on the storage of cookies, as shown in the following table:
If you try to store more cookies, the oldest cookies will be discarded.
2 Session
Session solves the problem that when the number of cookies increases, the amount of data transmission between the client and the server is increased. When the same client interacts with the server, it does not need to pass back all the cookie values every time, but only an ID value is passed back. This ID is generated when the client accesses the server for the first time, and each client is unique. This ID is usually a cookie whose name is JSESSIONID.
How does Session work based on cookies? It can be based on URL Path Parameter; it can also be based on cookies. If the cookies logo in the Context container is not modified, it is also supported by default. When the browser does not support the cookie function, the browser will rewrite the user's SessionCookieName to the URL parameter requested by the user. Its delivery method is such as /path/Servlet;name=xxx;name2=xxx2?name3=xxx3. SessionCookieName If the session-config configuration item is configured in web.xml, the name attribute under the cookie-config is the value of this SessionCookieName. If the session-config configuration item is not configured, the default SessionCookieNamejiushi "JSESSIONID". Note that the cookies associated with the Session are no different from other cookies. If the client also supports cookies, Tomcat will still parse the Session ID in the cookie and overwrite the Session ID in the URL.
How Session works
With the Session ID, the server can create an HttpSession object. The first time you call the request.getSession() method. If there is no corresponding HttpSession object, a new object will be created and added to the sessions container of org.apache.catalina.Manager will be saved. Manage saves all session life cycles, the session expires and is recycled, the server is closed, and the session is serialized to disk. Note that a client corresponds to a Session object, which saves the Session value we created.
The StandardSession called by the request.getSession() method will always exist, even if the Session associated with this client has expired. If it expires, a new one will be created, but the previously set Session value will be lost.
3 Comparison of Cookies and Session Security
Cookies pass the saved data from the client to the server through HTTP header, and then from the server to the client. All data is saved in the client browser. These data can be accessed, and cookies can even be added and modified through plug-ins. The security of all cookies is relatively poor. In comparison, Session saves data on the server side, which is much more secure. It only requires a cookie to pass a cookie ID back, so Session is more suitable for saving user privacy and important data.
Distributed Session Framework
In large Internet applications, using cookies and sessions alone is not feasible, because using cookies can solve the distributed deployment problem of applications well. A large Internet application system has hundreds of machines, and many different application systems work together. Since cookies store data in the user's browser, every time the user visits, the data will be brought back to the server, which solves the problem of cookies inconsistency caused by the same user's requests being processed on different servers.
Since the application is a cluster, the session cannot be saved in the memory of each server. If each server has hundreds of thousands of access users, the server memory cannot be accommodated. Even if it can be accommodated, it cannot guarantee that the session will be synchronized to other servers. Therefore, sharing these sessions requires saving them in a special distributed cache, which can be read and written at any time. The performance must be good enough to meet the requirements, such as memcache/redis or Taobao's open source distributed framework Tair.
Repeated form submission question
There are many places in the website that have repeated submissions. In order to prevent repeated submissions of forms, it is necessary to identify each access request of the user, so that each access request is unique to the server. In order to identify each request of the user, a hidden form item can be added to the form field requested by the user, and its value is a unique token, such as:
<form id="form" method="post">...<input type=hidden name="token" value="xxx"/></form>
A unique token is generated when the user requests the form and sets it to the user's session. When the user submits, it checks whether the token is consistent with the token saved in the session. If it is consistent, it means that there is no repeated submission. At the same time, the token in the session is updated to a new token value; otherwise, the token submitted by the user is no longer the legal token of the current request, and the submission fails.
The above are the things about cookies and sessions in Java that the editor introduced to you. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support to Wulin.com website!