A tip that can help you check if cookies is available.

xiaoxiao2021-03-05  23

Don't always think that the user's browser can accept cookies. There is a tip that can help you check if cookies is available.

BY Budi Kurniawan

Although all the browsers I know all support cookie settings, but users can consciously turn it off, or unconsciously turn it off. When you use cookies in your servlets / jsp page, you can't guarantee if the user's browser can accept cookies - you need to check it first. There is a small skill that checks if the cookie of the user's browser is effective.

This trick is very simple. You send an HTTP response from the servlet or JSP to the user's browser, forcibly enable the browser to return. In the first response, you send a cookie. When the browser returns the second time, check the cookie issued last time. If the cookie exists, explain the browser's cookie functionality. Otherwise, the user's browser is too old, does not support cookie, or the browser's cookie function is turned off.

The JSP page checks if the cookie is valid with the following code. If it is effective, the return string of the page is "cookie is on". If it is invalid, it is "cookie is off":

<%

IF (Request.getParameter ("Flag") == NULL) {

// the first request

Cookie cookie = new cookie ("cookiesetting",

"on");

Response.addcookie (cookie);

String NextURL = Request.getRequesturi ()

"? Flag = 1";

// force the browser to refresh

Out.println ("

Content = 0; URL = " NEXTURL ");

}

Else {

// the second request

Cookie [] cookies = Request.getCookies ();

Boolean cookiefound = false;

IF (cookies! = NULL) {

INT length = cookies.length;

For (INT i = 0; i

Cookie cookie = cookies [i];

IF

(cookie.getname (). Equals ("cookiesetting" &&

Cookie.getValue (). Equals ("on")) {

CookiefOnd = true;

Break;

}

}

}

IF (cookiefound) {

Out.println ("cookie is on.");

}

Else {

Out.println ("cookie is off.");

}

}

%>

转载请注明原文地址:https://www.9cbs.com/read-36007.html

New Post(0)