您的位置:首页 > 编程语言 > Java开发

java关于cookie存取用户名和密码

2015-08-26 14:47 483 查看
1、存储到cookie最好是一个对象存一次,就比如用户名和密码可以存为一个记录,这样方便读取

2、存取中文的时候记得编码问题,直接存取cookie会报错,具体见代码

jsp中的代码

<body>
<%
String username="";
String userpsd="";
Cookie [] cookies=request.getCookies();
if(cookies!=null){
for(int i=0;i<cookies.length;i++){
if(cookies[i].getName().equals("namepsd")){
//这里读的时候也记得转换编码,否则读出来会是乱码
//split()是截取String型的方法
//在jsp中使用这个方法需要导入java.net.*,在最上面写
username=URLDecoder.decode(cookies[i].getValue(), "UTF-8").split("-")[0];
userpsd=URLDecoder.decode(cookies[i].getValue(), "UTF-8").split("-")[1];
}
}
}
%>
<form action="CookiesServlet" method="post">
用户名:<input type="text" name="userName" value="<%=username%>"/><br />
密码:<input type="password" name="userPsd" value="<%=userpsd%>" /><br />
<input type="checkbox" name="userCk" value="ck" />记住用户名和密码<br />
<input type="submit" value="提交" />
</form>
</body>


servlet中的主要代码:

response.setContentType("text/html");
request.setCharacterEncoding("utf-8");
String username=request.getParameter("userName");
String userpsd=request.getParameter("userPsd");
String userck=request.getParameter("userCk");
if((username.equals("张"))&&(userpsd.equals("zhang"))){
if(userck!=null){
//这里存中文之前记得修改编码,要不然会报错
Cookie namepsd=new Cookie("namepsd", URLEncoder.encode(username+"-"+userpsd,"UTF-8"));
//设置cookie保存的时间
namepsd.setMaxAge(60);
//设置保存路径
namepsd.setPath("/");
//保存到cookie
response.addCookie(namepsd);
}
request.getRequestDispatcher("success.jsp").forward(request, response);
}else{
response.sendRedirect("fail.jsp");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: