目录
Cookie 禁用处理
默认情况下浏览器的 cookie 是被启用的,但是其实我们是可以手动的禁用 cookie 的,强烈不建议禁用 cookie。
Cookie 一旦被禁用掉绝大多数互联网的网站都无法登录,这个跟我们后续要讲解的 session 有关。那么我们如何通过程序来通过程序判断用户的浏览器上的 cookie 是否被禁用了呢,其实很简单,我们可以通过去刚刚添加的 cookie,如果没有取到,说明 cookie 被禁用。
以上操作完整源码
web.xml
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>RegistServlet</servlet-name>
<servlet-class>com.wyx.cookie.RegistServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistServlet</servlet-name>
<url-pattern>/servlet/RegistServlet</url-pattern>
</servlet-mapping>
</web-app>RegistServlet
package com.wyx.cookie;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegistServlet extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
doPost(req, resp);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException
{
// 创建cookie
Cookie cookie = new Cookie("userpass", "cookie test ...");
// 添加cookie
resp.addCookie(cookie);
String result = null;
// 获取刚刚存储的cookie
Cookie[] cookies = req.getCookies();
if (cookies != null)
{
for (Cookie ck : cookies)
{
String name = ck.getName();
if ("userpass".equals(name))
{
String value = ck.getValue();
result = value;
}
}
}
System.out.println(result);
resp.getWriter().print("success");
}
}工程文件下载
如有错误,欢迎指正!