巴拉巴

 找回密码
 立即注册

站内搜索

搜索
热搜: 活动 交友 discuz
查看: 54|回复: 1

怎样在Cookie中存储中文?

[复制链接]

6

主题

6

帖子

18

积分

新手上路

Rank: 1

积分
18
发表于 2023-5-17 15:35:51 | 显示全部楼层 |阅读模式
Cookie不能存储中文,但是如果有这方面的需求,这个时候该如何解决呢?
这个时候,我们可以使用之前学过的一个知识点叫URL编码,所以如果需要存储中文,就需要进行转码,具体的实现思路为:
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 { //发送Cookie String value = "张三"; //对中文进行URL编码 value = URLEncoder.encode(value, "UTF-8"); System.out.println("存储数据:" + value); //将编码后的值存入Cookie中 Cookie cookie = new Cookie("username", value); //设置存活时间 ,1周 7天 cookie.setMaxAge(60 * 60 * 24 * 7); //2. 发送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, HttpServletResponsesponse) throws ServletException, IOException { //获取Cookie //1. 获取Cookie数组 Cookie cookies = request.getCookies; //2. 遍历数组 for (Cookie cookie : cookies) { //3. 获取数据 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中进行使用。

来源:http://www.yidianzixun.com/article/0oTooxZD
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

1

主题

7

帖子

15

积分

新手上路

Rank: 1

积分
15
发表于 2025-5-11 14:11:19 | 显示全部楼层
好,很好,非常好!
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

  • 返回顶部