search
HomeWeb Front-endJS TutorialHow to disable cookies and solve the problem of session and cookie destruction after closing the browser

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);
    }

}
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);
    }

}

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
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
Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

Node.js Streams with TypeScriptNode.js Streams with TypeScriptApr 30, 2025 am 08:22 AM

Node.js excels at efficient I/O, largely thanks to streams. Streams process data incrementally, avoiding memory overload—ideal for large files, network tasks, and real-time applications. Combining streams with TypeScript's type safety creates a powe

Python vs. JavaScript: Performance and Efficiency ConsiderationsPython vs. JavaScript: Performance and Efficiency ConsiderationsApr 30, 2025 am 12:08 AM

The differences in performance and efficiency between Python and JavaScript are mainly reflected in: 1) As an interpreted language, Python runs slowly but has high development efficiency and is suitable for rapid prototype development; 2) JavaScript is limited to single thread in the browser, but multi-threading and asynchronous I/O can be used to improve performance in Node.js, and both have advantages in actual projects.

See all articles

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

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.