实例:使用Cookie实现记住用户名
实例代码如下:
a、login.jsp(客户端,负责输入信息)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!//注意是全局变量符
String uname;
%>
<%
Cookie[] cookies=request.getCookies();
for(Cookie cookie:cookies){
if(cookie.getName().equals("uname")){
uname=cookie.getValue();
}
}
%>
<form action="check.jsp" method="post"> <!-- 输出表达式 -->
用户名:<input type="text" name="uname" value="<%=uname==null?"":uname%>"><br/>
密码:<input type="password" name="upwd"><br/>
<input type="submit" value="登录"><br/>
</form>
</body>
</html>
b、check.jsp(服务端,负责返回带值Cookie)
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<%
request.setCharacterEncoding("UTF-8");
String uname=request.getParameter("uname");
String upwd=request.getParameter("upwd");
//客户端向服务端发出请求,服务端把信息放在Cookie里返回
//将用户名加入到Cookie中
//Cookie一般用英文或数字,中文需要编码解码处理
Cookie cookie=new Cookie("uname",uname);
response.addCookie(cookie);
//服务端在重定向时响应客户端,同时将Cookie发回客户端
response.sendRedirect("login.jsp");
%>
</body>
</html>