Home > Web Front-end > JS Tutorial > body text

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

零下一度
Release: 2017-05-18 11:54:54
Original
5592 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!