-
案例效果
有两个页面Login.jsp与Hello.jsp,若用户在登录界面属于用户名,则用户直接进入Hello.jsp页面,此后在三十秒之内,用户可以直接打开Hello.jsp.超过三十秒,用户打开hello.jsp会自动跳转到登录界面
-
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>
<form action="Hello.jsp" method="post">
<table>
<tr>
<td>用户名:</td>
<td><input type="text" name="username"/></td>
</tr>
<tr>
<td clospan="2"><input type="submit" value="submit"/></td>
</tr>
</table>
</form>
</body>
</html>
-
Hello.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> <% request.setCharacterEncoding("UTF-8"); String requestName=request.getParameter("username"); if(requestName != null && !(requestName.trim().equals(""))){ out.print("Hello: "+ requestName); Cookie cookie=new Cookie("username",requestName); cookie.setMaxAge(30); response.addCookie(cookie); }else{ String cookieValue=null; Cookie [] cookies=request.getCookies(); if( cookies!=null && cookies.length > 0){ for(Cookie cookie : cookies){ if( cookie.getName().equals("username")){ cookieValue = cookie.getValue(); out.print("Hello: "+ cookieValue); break; } } } if(cookieValue==null){ response.sendRedirect("Login.jsp"); } } %> </body> </html>