亚洲福利网站,国产精品久久国产三级国电话系列 ,欧美久久久久久,蜜桃av在线

IT培訓-高端面授IT培訓機構
云和教育:云和數(shù)據(jù)集團高端IT職業(yè)教育品牌
  • 國家級
    全民數(shù)字素養(yǎng)與技能培訓基地
  • 河南省
    第一批產(chǎn)教融合型企業(yè)建設培育單位
  • 鄭州市
    數(shù)字技能人才(碼農(nóng))培養(yǎng)評價聯(lián)盟
當前位置:
首頁IT問答正文

怎樣在Cookie中存儲中文?

  • 發(fā)布時間:
    2023-05-17
  • 版權所有:
    云和教育
  • 分享:

Cookie不能存儲中文,但是如果有這方面的需求,這個時候該如何解決呢?

這個時候,我們可以使用之前學過的一個知識點叫URL編碼,所以如果需要存儲中文,就需要進行轉(zhuǎn)碼,具體的實現(xiàn)思路為:

1.在AServlet中對中文進行URL編碼,采用URLEncoder.encode(),將編碼后的值存入Cookie中

2.在BServlet中獲取Cookie中的值,獲取的值為URL編碼后的值

3.將獲取的值在進行URL解碼,采用URLDecoder.decode(),就可以獲取到對應的中文值

(1)在AServlet中對中文進行URL編碼

@WebServlet("/aServlet")
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse sponse) throws ServletException, IOException {
        //發(fā)送Cookie
        String value = "張三";
        //對中文進行URL編碼
        value = URLEncoder.encode(value, "UTF-8");
        System.out.println("存儲數(shù)據(jù):" + value);
        //將編碼后的值存入Cookie中
        Cookie cookie = new Cookie("username", value);
        //設置存活時間 ,1周 7天
        cookie.setMaxAge(60 * 60 * 24 * 7);
        //2. 發(fā)送Cookie,response
        response.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse 
ponse) throws ServletException, IOException {
        this.doGet(request, response);
    }
}

(2)在BServlet中獲取值,并對值進行解碼。

@WebServlet("/bServlet")
public class BServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse
sponse) throws ServletException, IOException {
      //獲取Cookie
      //1. 獲取Cookie數(shù)組
      Cookie[] cookies = request.getCookies();
      //2. 遍歷數(shù)組
      for (Cookie cookie : cookies) {
          //3. 獲取數(shù)據(jù)
          String name = cookie.getName();
          if("username".equals(name)){
              String value = cookie.getValue();//獲取的是URL編碼后的值
%BC%A0%E4%B8%89
              //URL解碼
              value = URLDecoder.decode(value,"UTF-8");
              System.out.println(name+":"+value);//value解碼后為 張三
              break;

          }
      }

  }
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
       this.doGet(request, response);
  }

}

至此,我們就可以將中文存入Cookie中進行使用。

主站蜘蛛池模板: 南投市| 山西省| 蓬溪县| 吴堡县| 肇东市| 德清县| 济阳县| 宁南县| 个旧市| 固始县| 崇仁县| 古蔺县| 北流市| 长春市| 紫阳县| 东平县| 新巴尔虎左旗| 开阳县| 南京市| 宁波市| 隆子县| 象山县| 南皮县| 五峰| 诏安县| 龙山县| 上饶市| 新绛县| 汽车| 城固县| 安宁市| 从化市| 九江市| 尤溪县| 峨边| 新河县| 天津市| 尚义县| 惠水县| 玛沁县| 玉屏|