[原创]java WEB学习笔记29:Cookie Demo 之自动登录

本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明

本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用

内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系。

本人互联网技术爱好者,互联网技术发烧友

微博:伊直都在0221

QQ:951226918

-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------

1. 自动登录 的需求

  ① 不需要填写用户名和密码等信息,可以自动登录到系统

  ②  login.jsp  hello.jsp

  

login.jsp

 <%@ 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> <form action="index.jsp">
name:<input type="text" name="name"/>
<input type="submit" value="submit"/> </form> </body>
</html>

hello.jsp

 <%@ 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>自动登陆测试</title>
</head>
<body> <%
//1.若可以获取到请求参数 name, 则打印出欢迎信息。把登录信息存储到 Cookie 中,并设置 Cookie 的最大时效为 30S
String name = request.getParameter("name");
if(name != null && !name.trim().equals("")){ //创建并且发送cookie
Cookie cookie = new Cookie("loginName",name);
cookie.setMaxAge(30);
response.addCookie(cookie);
}else{
//2.从 Cookie 中读取用户信息,若存在则打印欢迎信息
Cookie[] cookies = request.getCookies();
if(cookies != null && cookies.length > 0){
for(Cookie cookie : cookies){
String cookieName = cookie.getName();
if("loginName".equals(cookieName)){
String value = cookie.getValue();
name = value; }
}
} }
if(name != null && !name.trim().equals("")){
out.print("欢迎登陆" + name);
}else{
//3.若既没有请求参数,也没有 Cookie,则重定向到 login.jsp
request.getRequestDispatcher("/app-1/login.jsp");
} %>
</body>
</html>
上一篇:第二百二十五节,jQuery EasyUI,PropertyGird(属性表格)组件


下一篇:为什么需要Bundler