首頁技術(shù)文章正文

怎樣在Cookie中存儲中文?

更新時間:2023-05-16 來源:黑馬程序員 瀏覽量:

IT培訓(xùn)班

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

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

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

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

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

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

@WebServlet("/aServlet")
public class AServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse sponse) throws ServletException, IOException {
        //發(fā)送Cookie
        String value = "張三";
        //對中文進(jìn)行URL編碼
        value = URLEncoder.encode(value, "UTF-8");
        System.out.println("存儲數(shù)據(jù):" + value);
        //將編碼后的值存入Cookie中
        Cookie cookie = new Cookie("username", value);
        //設(shè)置存活時間 ,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中獲取值,并對值進(jìn)行解碼。
@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中進(jìn)行使用。
分享到:

Java培訓(xùn)班課程javaee

Python培訓(xùn)機(jī)構(gòu)python大數(shù)據(jù)

web前端培訓(xùn)課程升級V8.5web

AI+設(shè)計培訓(xùn)課程ui

大數(shù)據(jù)培訓(xùn)課程cloud

軟件測試培訓(xùn)課程test

c

新媒體運(yùn)營培訓(xùn)netmarket

產(chǎn)品經(jīng)理培訓(xùn)課程pm

linux培訓(xùn)Linux

movies

智能機(jī)器人培訓(xùn)robot

電商視覺設(shè)計課程uids

AI

集成電路應(yīng)用開發(fā)(嵌入式)培訓(xùn)課程jdbc

在線咨詢 我要報名
和我們在線交談!