五月天青色头像情侣网名,国产亚洲av片在线观看18女人,黑人巨茎大战俄罗斯美女,扒下她的小内裤打屁股

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

怎樣在Cookie中存儲(chǔ)中文?

2023-05-17 10:23 作者:云和數(shù)據(jù)何老師  | 我要投稿


Cookie不能存儲(chǔ)中文,但是如果有這方面的需求,這個(gè)時(shí)候該如何解決呢?

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

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

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

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

(1)在AServlet中對(duì)中文進(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 = "張三"; ? ? ? ?//對(duì)中文進(jìn)行URL編碼 ? ? ? ?value = URLEncoder.encode(value, "UTF-8"); ? ? ? ?System.out.println("存儲(chǔ)數(shù)據(jù):" + value); ? ? ? ?//將編碼后的值存入Cookie中 ? ? ? ?Cookie cookie = new Cookie("username", value); ? ? ? ?//設(shè)置存活時(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中獲取值,并對(duì)值進(jìn)行解碼。

@WebServlet("/bServlet")public class BServlet extends HttpServlet { ? ?@Override ? ?protected void doGet(HttpServletRequest request, HttpServletResponsesponse) 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, HttpServletResponseresponse) throws ServletException, IOException { ? ? ? this.doGet(request, response); ?}}

至此,我們就可以將中文存入Cookie中進(jìn)行使用。


怎樣在Cookie中存儲(chǔ)中文?的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國(guó)家法律
宁南县| 高邮市| 全州县| 兖州市| 深州市| 阳谷县| 砚山县| 黔西| 新民市| 南昌县| 广饶县| 金溪县| 龙州县| 资兴市| 庆云县| 汉中市| 南江县| 固始县| 星子县| 迁安市| 麻栗坡县| 南岸区| 上栗县| 双桥区| 闸北区| 威宁| 汾阳市| 同心县| 松滋市| 白山市| 周至县| 曲阜市| 思南县| 绥化市| 深水埗区| 太康县| 军事| 宝丰县| 玛沁县| 南城县| 海宁市|