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

java之cookie保存登录信息下次登录时自动填充表单

2017-04-09 17:06 866 查看
现在发现写代码不是最难的,天下代码一通抄,看你会抄不会抄。。。

反而找问题才是最难的,因为不是所有的问题你都能找到,要么就是不符合自己的问题需求,

要么就是根本是错的。。。好了,吐槽完毕!

------------------------------------------------一道华丽的波浪线-------------------------------------------------------------------

今天花了一早上的时间学习了一下cookie的使用,就是搞不懂各个文件之间的逻辑关系,什么时候该创建cookie,在哪里创建?什么时候该调用cookie,在哪里调用?

原理:登录表单(假设是login.jsp,没有用html文件,因为要实现数据自动填充我们就需要java代码,用一个变量保存数据,因此要么用servlet(而且servlet需要嵌套html~麻烦),要么用jsp)需要提交给servlert文件(假设是loginservlet.java),那么就应该在servlet中创建cookie保存用户信息并返回给浏览器:

String uname = request.getParameter("username");
String key = request.getParameter("key");

HttpSession session = request.getSession();//此处是获取并存储sessio值,不用管
session.setAttribute("uname", uname);
session.setAttribute("key", key);

Cookie cookie = new Cookie("uname", uname);// 创建cookie
response.addCookie(cookie);//添加到浏览器
Cookie cookie2 = new Cookie("key", key);
response.addCookie(cookie2);

好了,现在浏览器里面存的有cookie了,下面我们要在登录界面去调用它,判断是否已经存储的有相关信息,有的话自动填充到表单的属性值value中(login.jsp的源代码):

<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%
String path = request.getContextPath();
String basePath = request
b893
.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

String username =null; //该变量就是下面表单中填充数据的值
String key = null;
Cookie[] cookies = request.getCookies(); //先从浏览器中取出cookie,没有就是空
//String[] cookievulue = null;
Map<String, String> cc = new HashMap<String, String>();
for(int i=0;i<cookies.length;i++){
String names = cookies[i].getName();
String values = cookies[i].getValue();
cc.put(names, values);
}
username = cc.get("uname");

//key = session.getAttribute("key").toString();
//session 可以直接用???

%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'Login.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<link href="CSS/login.css" rel="stylesheet" type="text/css"/> <!-- 调用css样式 -->
</head>

<body>
<form action="/demo_test/Loginservlet" method="post">
<div id="Navigate">
<div id="Gap"></div>
<div id="Uname">用户名:<input type="text" id="text_uname" name="username" value=<%=username%>></div>
<div id="Checknode">验证码:<img src="/demo_test/VlidateCode" id="image"/></div>
<div id="Key">口令:<input type="text" id="text_key" name="key"></div>
<div id="Submit"><input type="submit" value="提交"></div>
</div>

</form>
</body>
</html>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: