cookie获取和保存用户名与登陆状态及cookie获取值出现乱码的问题解决

     最近在使用cookie保存用户的登录信息的实验中,遇到了一些具体的问题,在此记录一下,也希望对大家有所帮助。上代码:

index.jsp(进行初始页面的数据获取与显示)

 <%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.net.URLDecoder" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>在此输入标题</title>
</head>
<body>
<%
	Cookie[] cookies = request.getCookies();
	String user = "";	//登录用户
	String date = "";	//注册的时间
	if (cookies != null) {
		for (int i = 0; i < cookies.length; i++) {	
			if (cookies[i].getName().equals("Cookie123")) {
				user =URLDecoder.decode(cookies[i].getValue().split("#")[0],"utf-8");//获取用户名
				date = cookies[i].getValue().split("#")[1];//获取注册时间
			}
		}
	}
	if ("".equals(user) && "".equals(date)) {         //没有注册,未填入username
%>
		游客您好,欢迎您初次注册!
		<form action="cookie.jsp" method="post">
			请输入姓名:<input name="user" type="text" value=""><br>
			<input type="submit" value="确定">
		</form>
<%
	} else {//已经注册
%>
		欢迎[<%=user %>]再次登录<br>
		您登录的时间是:<%=date %>
<%
	}
%>
</body>
</html>





 

 cookie.jsp(用于对cookie的编辑)

 <%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<%@ page import="java.net.URLEncoder,java.util.*,java.text.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>对cookie进行写入</title>
<script type="text/javascript">window.location.href="index.jsp"</script> 
<body>
<%
	request.setCharacterEncoding("utf-8");
	Date date = new Date();//实例化对象
	SimpleDateFormat m= new SimpleDateFormat("h:m:s");//时间格式
	
	String user=URLEncoder.encode(request.getParameter("user"),"utf-8");	//从“user"获取用户名
	Cookie cookie = new Cookie("Cookie123", user+"#"+m.format(date));
	System.out.println(m.format(date));
	cookie.setMaxAge(30);		//设置cookie有效期 ,成为持久cookie,可以免登录;也可以不设置,关闭网页时关闭会话,cookie刷新
	response.addCookie(cookie);	//保存cookie
%>
</body>
</html>

     其中,很多人会出现cookie获取中文乱码的情况,所以这里一定强调cookie的写入和获取的方式尤为重要,写入时:URLEncoder.encode(request.getParameter(),"utf-8"),其中一定要表明编码格式;读取时:URLDecoder.decode(cookies[i].getValue(),"utf-8")同理可循,切记也一定不可忘编码格式,这样就解决了cookie获取值出现乱码的问题了。

原创文章 2 获赞 2 访问量 105

猜你喜欢

转载自blog.csdn.net/bai737373/article/details/106173716
今日推荐