login.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!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">
-->
</head>
<body>
<form action="<%=basePath%>cookie/main.jsp" method="post">
用户名: <input type="text" name="username">
<input type="submit" value="提交">
</form>
</body>
</html>
main.jsp:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.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">
-->
</head>
<body>
<%String username=request.getParameter("username");
if(username!=null &&!username.trim().equals("")){
Cookie userCookie=new Cookie("username",username);
userCookie.setMaxAge(30);
response.addCookie(userCookie);
}else{
Cookie[] cookies=request.getCookies();
if(cookies!=null && cookies.length>0){
for(Cookie c:cookies){
if(c.getName().equals("username")){
username= c.getValue();
}
}
}
}
if(username !=null && !username.trim().equals("")){
System.out.print(1);
out.print("hello:"+username);
}else{
response.sendRedirect("login.jsp");
}
%>
</body>
</html>
测试:
如果不输入用户名的话,main.jsp里的逻辑判断会使页面重定向到登录页面:
输入用户名,进入main.jsp:
此时查看login.jsp页面的cookie
再次重新在login.jsp登录,但是不输入内容,查看main.jsp中从login.jsp传过来的请求头:
因为该cookie被设置为有效期30秒,所以30秒后,再重新登录的话,如果不输入内容,无法进入main.jsp.