需求:实现cookie在首次打开浏览器情况下的自动填充。
register.jsp
<%@page import="java.net.URLDecoder"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>用户注册页面</title>
</head>
<body>
<%
String name = null;
String pwd = null;
Cookie[] cookies = request.getCookies();
if (cookies != null) {
for (int i = 0 ;i < cookies.length; i++) {
if (cookies[i].getName().equals("name")) {
String name_pwd = cookies[i].getValue();
name = name_pwd.split("-")[0];
name = URLDecoder.decode(name, "utf-8");
pwd = name_pwd.split("-")[1];
break;
}
}
}
%>
<form action="doRegister.jsp" method="get">
<p>姓名:<input type="text" name="name" <%if (name != null) {%>value=<%=name %> <%} %>/><p/>
<p>密码:<input type="password" name="password" <%if (pwd != null) {%>value=<%=pwd %> <%} %>/><p/>
<p>爱好:<input type="checkbox" name="interest" value="talking">聊天</input>
<input type="checkbox" name="interest" value="basketball">篮球</input>
<input type="checkbox" name="interest" value="swimming">游泳</input>
<input type="checkbox" name="interest" value="football">足球</input>
<p/>
<p><input type="submit" name="submitButton" value="提交"/><p/>
</form>
<%
String mess = (String)request.getAttribute("mess");
if (!(mess==null)) {
%>
<%=mess %>
<%} %>
</body>
</html>
doRegister.jsp
<%@page import="java.net.URLEncoder"%>
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
String name = request.getParameter("name");
String pwd = request.getParameter("password");
String[] interest = request.getParameterValues("interest");
%>
<%=name %>
<%=pwd %>
<%
for(int i = 0; i <interest.length; i++) {
out.print(interest[i]);
}
%>
<%
if (name.equals("张三")) {
request.setAttribute("mess", "登录失败");
request.getRequestDispatcher("register.jsp").forward(request, response);
} else {
session.setAttribute("msg", "登录成功");
session.setAttribute("name", name);
session.setAttribute("pwd", pwd);
String name_pwd = name+"-"+pwd;
name_pwd = URLEncoder.encode(name_pwd, "utf-8");
Cookie cookie = new Cookie("name", name_pwd);
cookie.setPath("/");
cookie.setMaxAge(100*60);
response.addCookie(cookie);
response.sendRedirect("success.jsp");
}
%>
</body>
</html>
结果分析:在关闭了浏览器的自动填充功能之后(不要关闭cookie功能),上面的代码就可以自动填充了。但是上面的代码只能实现一个用户的自动填充,新来用户的时候会把之前的用户覆盖掉。并且在第一次访问,即之前没有登录过的时候不会报错。
补:response只有addCookie,request只有getCookie。