天天看點

前端學習--009--cookie 技術的實戰學習

cookie技術實質:

cookie技術的本質就是儲存浏覽器端的資訊,當使用者再次檢視上次浏覽的資訊時,就可以直接檢視到。缺點就是資料安全性低。

類代碼:(建立項目,再建立包,然後建立類,最後敲代碼,并配置web.xml資訊-----部署并啟動伺服器)

package com.ly.servlet;

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;
public class CookieServlet extends HttpServlet {
  @Override
  protected void service(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    //設定請求編碼格式
    req.setCharacterEncoding("utf-8");
    //設定響應編碼格式
    resp.setContentType("text/html;charset=utf-8");
    //使用Cookie進行浏覽器端的資料存儲
        //建立Cookie對象
        Cookie c=new Cookie("mouse", "thinkpad");
        Cookie c2=new Cookie("key", "pzhu");
        //設定Cookie
        //設定Cookie的有效期
        c2.setMaxAge(3*24*3600);
        //設定有效路徑
        c2.setPath("/cookie/gc");
        //響應 Cookie資訊
        resp.addCookie(c);
        resp.addCookie(c2);
             //直接響應
        resp.getWriter().write("Cookie學習");
      
  }
}      

web.xml配置:

<?xml  version="1.0"  encoding="UTF-8"?>
<web-app  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"  id="WebApp_ID"
version="2.5">
<servlet>
<servlet-name>CookieServlet</servlet-name>
<servlet-class>com.ly.servlet.CookieServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CookieServlet</servlet-name>
<url-pattern>/cs</url-pattern>
</servlet-mapping>
</web-app>      

結果:

前端學習--009--cookie 技術的實戰學習

怎麼樣?主人,你忘記你的小妲己了嗎?··································