今天学习的时候发现Cookie挺有意思的,就自己网上找点例子,自己敲点代码熟练下,现在就记录下来,分享一下。

什么是cookie??

Cookie 是一小段文本信息,伴随着用户请求和页面在 Web 服务器和浏览器之间传递。Cookie 包含每次用户访问站点时 Web 应用程序都可以读取的信息。因为HTTP协议是无状态的,对于一个浏览器发出的多次请求,WEB服务器无法区分 是不是来源于同一个浏览器。所以,需要额外的数据用于维护会话。 Cookie 正是这样的一段随HTTP请求一起被传递的额外数据。可见它是用于维持服务端会话状态的,通常由服务端写入,在后续请求中,供服务端读取。

实现代码:

配置文件web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 
    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_3_0.xsd">
  <display-name></display-name>    
  
  <servlet>
      <servlet-name>TestCookie</servlet-name>
      <servlet-class>com.cookie.TestCookie</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>TestCookie</servlet-name>
      <url-pattern>/testCookie</url-pattern>
  </servlet-mapping>
  
  <servlet>
      <servlet-name>GetCookie</servlet-name>
      <servlet-class>com.cookie.GetCookie</servlet-class>
  </servlet>
  <servlet-mapping>
      <servlet-name>GetCookie</servlet-name>
      <url-pattern>/getCookie</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

 

保存Cookie的servlet:TestCookie.java

package com.cookie;

import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;

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 TestCookie extends HttpServlet {
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        String username = req.getParameter("username");
        PrintWriter out = resp.getWriter();
        if(username!=""){
            Cookie cName = new Cookie("username",username ); 
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            Cookie cDate = new Cookie("lastVisited",format.format(new java.util.Date()));
            resp.addCookie(cName);
            resp.addCookie(cDate);
            out.println("Cookie 保存成功");
            out.println("<br><br>");
            out.println("<a href='getCookie'>读取Cookie内容</a>");
        }
            out.flush();
            out.close();
        
    
        /*req.getRequestDispatcher(null).forward(req, resp);*/
         
    }
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
         this.doPost(req, resp);
    }

}

读取Cookie的servlet:GetCookie.java

package com.cookie;

import java.io.IOException;
import java.io.PrintWriter;

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 GetCookie extends HttpServlet {
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
         this.doPost(req, resp);
    }
    
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter out = resp.getWriter();
        out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
        out.println("<HTML>");
        out.println("  <HEAD><TITLE>A Servlet</TITLE></HEAD>");
        out.println("  <BODY>");
        
        Cookie []cookies = req.getCookies();
        Cookie c = null;
        if(cookies!=null){
            for(int i=0;i<cookies.length;i++){
                c =  cookies[i];
                if(c.getName().equals("username")){
                    out.println("用户名:"+c.getValue());
                    out.println("<br>");
                };
                if(c.getName().equals("lastVisited")){
                    out.println("上次登录时间:"+c.getValue());
                    out.println("<br>");
                };
            }
        }else{
            out.println("No cookie Existing");
        }
        out.println("</body>");
        out.println("</html>");
        out.flush();
        out.close();
        
    }
    

}

首页index.jsp:

<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>
  
  <body>
    <form action="testCookie">
        用户名:<input type="text" name="username"/><br>
         <input type="submit" value="提交">
    </form>
  </body>
</html>

测试的结果贴图:

java获取网页url java获取网页源码并获取cookie_HTML

java获取网页url java获取网页源码并获取cookie_java_02

java获取网页url java获取网页源码并获取cookie_java获取网页url_03

最后成功!!!!!!

这只是一些测试代码,就还有很多的cookie操作没有写出来,未完待续!!!