Home Web Front-end JS Tutorial How to disable cookies and solve the problem of session and cookie destruction after closing the browser

How to disable cookies and solve the problem of session and cookie destruction after closing the browser

May 18, 2017 am 11:54 AM

Cookie and Session are generally considered to be two independent things. Session uses a solution that maintains state on the server side, while Cookie uses a solution that maintains state on the client side. But why can't I get the Session if I disable cookies? Because the Session uses the Session ID to determine the server Session corresponding to the current conversation, and the Session ID is passed through Cookie, disabling Cookie is equivalent to losing the Session ID, and thus the Session is lost.

How to disable cookies?

1. Start IE;
2. On the "Tools" menu, click "Internet Options" to open the "Internet Options" dialog box;
3. Click "Privacy" ” tab and move the slider up to a higher privacy level. If you move to the top, select "Block All Cookies". At this time, the system will block cookies from all websites, and websites cannot read existing cookies on your computer;
4. Click the "OK" button.

sessionid is stored in the cookie, the solution is as follows:
Session URL rewriting, to ensure that when the client disables or does not support COOKIE, it still You can use the Session

session mechanism. The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or may use a hash table) to save information.

When the program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier (called session id). If it does, it means that it has been created before. This client has created a session, and the server will retrieve the session according to the session id (if it cannot be retrieved, it will create a new one). If the client request does not include the session id, a session will be created for the client and a session with this will be generated. The session id associated with the session. The value of the session id should be a string that is neither repetitive nor easy to find patterns to counterfeit. This session id will be returned to the client in this response. Save on the end. The method of saving this session ID can use cookies, so that during the interaction process, the browser can automatically display this identification to the server according to the rules. Generally, the name of this cookie is similar to SEEESIONID. But cookies can be artificially disabled, and there must be other mechanisms to still pass the session id back to the server when cookies are disabled. A frequently used technique is called URL rewriting, which appends the session id directly to the end of the URL path. There is also a technique called form hidden fields. That is, the server will automatically modify the form and add a hidden field so that the session id can be passed back to the server when the form is submitted.

【Example of URL rewriting】

package session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class WelcomeServlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        request.getSession();

        String url1 = response.encodeURL("/Session/servlet/SessionDemo1");//禁用cookie才重写,注意禁用cookie后,访问要用127.0.0.1,不能用localhost
        String url2 = response.encodeURL("/Session/servlet/SessionDemo2");        //禁用cookie之后无法解决关闭浏览器能重新访问的问题。
        out.println("<a href=&#39;"+url1+"&#39;>购买  </a>");
        out.println("<a href=&#39;"+url2+"&#39;>结账</a>");
    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {
        doGet(request, response);
    }

}
Copy after login
package session;import java.io.IOException;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;//购买 index.jsp index.html//session基于cookiepublic class SessionDemo1 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {
        HttpSession session = request.getSession(); //Session创建
        //request.getSession(false);    //不创建session,只获取session  例如:显示购物车

        //解决浏览器关闭后cookie销毁的问题:
        String sessionid = session.getId();
        Cookie cookie = new Cookie("JSESSIONID",sessionid);
        cookie.setPath("/Session");
        cookie.setMaxAge(30*60);
        response.addCookie(cookie);

        session.setAttribute("name", "洗衣机");        //30分钟没使用之后(不管有无关闭浏览器),Session才销毁(默认,可控制时间)
        //配置方法:在web.xml文件中配置<session-config>里面配置一个<session-timeout>并且设置时间值
        //代码摧毁方法:session.invalidate();
    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {
        doGet(request, response);
    }

}
----------//解决浏览器关闭后session销毁的问题:String sessionid = session.getId();
Cookie cookie = new Cookie("JSESSIONID",sessionid);
cookie.setPath("/Session");
cookie.setMaxAge(30*60);
response.addCookie(cookie);

【解决浏览器关闭后session销毁的原因】:
sessionId是一个cookie,max-age默认为-1,即关闭浏览器后sessionId就会清空 
sessionId(cookie)清空后,自然就无法找到对应的session,所以session就失效了

【解决方法】:
设置上述代码,添加cookie的失效时间,        30分钟没使用之后(不管有无关闭浏览器),Session才销毁(默认,可控制时间)
        其他session失效时间配置方法:在web.xml文件中配置<session-config>里面配置一个<session-timeout>并且设置时间值
        代码摧毁方法:session.invalidate();

----------package session;import java.io.IOException;import java.io.PrintWriter;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.http.HttpSession;//结账public class SessionDemo2 extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();

        HttpSession session = request.getSession();
        String product = (String)session.getAttribute("name");
        out.write("你购买的商品是:"+product);

    }    public void doPost(HttpServletRequest request, HttpServletResponse response)            throws ServletException, IOException {
        doGet(request, response);
    }

}
Copy after login

URL address rewriting is a solution for clients that do not support cookies. The principle of URL address rewriting is to rewrite the user's Session ID information into the URL address. The server can parse the rewritten URL to obtain the Session ID. In this way, even if the client does not support cookies, Session can be used to record user status. The HttpServletResponse class provides encodeURL (String url) to implement URL address rewriting. This method will automatically determine whether the client supports cookies. If the client supports cookies, the URL will be output intact. If the client does not support cookies, the user Session id will be rewritten into the URL.

Note: TOMCAT determines whether the client browser supports cookies based on whether the request contains cookies. Although the client may support cookies, it will not carry any cookies in the first request. (Because there are no cookies to carry), the URL address after rewriting will still contain JSESSIONID. When accessing for the second time, the server has already written the cookie in the browser, so the URL address after rewriting will not contain JSESSIONID.

【Related recommendations】

1. Detailed explanation of Js cookie operation (setting, reading, deleting) examples

2. What are Cookies? What are cookies used for?

The above is the detailed content of How to disable cookies and solve the problem of session and cookie destruction after closing the browser. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1657
14
PHP Tutorial
1257
29
C# Tutorial
1230
24
How to disable and remove HP Wolf Security on Windows 11 How to disable and remove HP Wolf Security on Windows 11 Dec 14, 2023 pm 06:49 PM

HP devices usually come with security software pre-installed, and many people wonder how to disable HPWolfSecurity on Windows 11. The reason for this is that this software can cause certain problems and conflict with other applications, so today we will show you how to disable it. Is HPWolfSecurity bloatware? This is a legitimate application from HP, but it often comes pre-installed and causes performance issues and conflicts with other security software, which is why many people consider it bloatware. How to disable HPWolfSecurity on Windows 11? 1. Use the system tray icon to find HPWolfSecurity in the system tray

How to enable or disable taskbar thumbnail previews on Windows 11 How to enable or disable taskbar thumbnail previews on Windows 11 Sep 15, 2023 pm 03:57 PM

Taskbar thumbnails can be fun, but they can also be distracting or annoying. Considering how often you hover over this area, you may have inadvertently closed important windows a few times. Another disadvantage is that it uses more system resources, so if you've been looking for a way to be more resource efficient, we'll show you how to disable it. However, if your hardware specs can handle it and you like the preview, you can enable it. How to enable taskbar thumbnail preview in Windows 11? 1. Using the Settings app tap the key and click Settings. Windows click System and select About. Click Advanced system settings. Navigate to the Advanced tab and select Settings under Performance. Select "Visual Effects"

How to remove news and trending content from Windows 11 Search How to remove news and trending content from Windows 11 Search Oct 16, 2023 pm 08:13 PM

When you click the search field in Windows 11, the search interface automatically expands. It displays a list of recent programs on the left and web content on the right. Microsoft displays news and trending content there. Today's check promotes Bing's new DALL-E3 image generation feature, the "Chat Dragons with Bing" offer, more information about dragons, top news from the Web section, game recommendations, and the Trending Search section. The entire list of items is independent of your activity on your computer. While some users may appreciate the ability to view news, all of this is abundantly available elsewhere. Others may directly or indirectly classify it as promotion or even advertising. Microsoft uses interfaces to promote its own content,

How to enable or disable memory compression on Windows 11 How to enable or disable memory compression on Windows 11 Sep 19, 2023 pm 11:33 PM

With memory compression on Windows 11, your device will choke even with a limited amount of RAM. In this article, we will show you how to enable or disable memory compression on Windows 11. What is memory compression? Memory compression is a feature that compresses data before writing it to RAM, thus providing more storage space on it. Of course, more data stored in physical memory translates into faster system operation and better overall performance. This feature is enabled by default in Windows 11, but if it's somehow not active, you can disable or re-enable it. How to enable memory compression in Windows 11? Click the search bar, type powershell, and click

How to disable your laptop keyboard on Win11 and only use an external keyboard How to disable your laptop keyboard on Win11 and only use an external keyboard Jan 29, 2024 pm 08:48 PM

How to disable the laptop's built-in keyboard in win11 and only use the external one? Details: We need to use an external keyboard when using a win11 computer, but many users choose to disable the laptop's built-in keyboard and only use an external keyboard. So how do you do this? Users can directly click cmd under the search bar and then perform operations. Let this site give users a detailed introduction on how to disable the laptop's built-in keyboard in win11 and only use an external one. Detailed explanation on how to disable the laptop's built-in keyboard in Win 11 and only use an external keyboard. 1. Click the Start menu at the bottom of the computer or search. 3. Enter cmd and click on the right to run as administrator. 5. If you want to restart, you can return to this location and enter scconfigi804

Windows 11 User Guide: How to disable ad pop-ups Windows 11 User Guide: How to disable ad pop-ups Sep 22, 2023 pm 07:21 PM

Microsoft's Windows 11 operating system may periodically display suggestions as pop-ups on your computer using the notification system. The suggestions system, originally intended to provide users with tips and suggestions for improving their Windows 11 workflows, has almost completely transformed into an advertising system to promote Microsoft services and products. Suggestion pop-ups might advertise a Microsoft 365 subscription to users, suggest linking an Android phone to the device, or set up a backup solution. If these pop-ups annoy you, you can tweak your system to disable them entirely. The following guide provides recommendations on disabling pop-ups on devices running Microsoft’s Windows 11 operating system.

Edge browser js script disabling method Edge browser js script disabling method Jan 07, 2024 am 11:17 AM

With the new version of the edge browser, many friends are not used to it. For example, they don't know how to disable js scripts. Today I will bring you how to disable js scripts in edge browser. Let's learn together. edge browser js script: 1. Open the browser, click the three dots in the upper right corner, and select "Settings". 2. Click "Advanced" on the left taskbar. 3. Scroll down to find "Website Permissions" and click "Manage Permissions". 4. Find “JavaScript” in “Site Permissions”. 5. Turn off the switch behind it.

Where are cookies stored? Where are cookies stored? Dec 20, 2023 pm 03:07 PM

Cookies are usually stored in the cookie folder of the browser. Cookie files in the browser are usually stored in binary or SQLite format. If you open the cookie file directly, you may see some garbled or unreadable content, so it is best to use Use the cookie management interface provided by your browser to view and manage cookies.

See all articles