Java Web实战详细教程(二十)Cookie实战

        因为HTTP协议本身是无状态的,想用通过网络协议本身来记录该请求来源于哪个浏览器便不可能。如下图所示,浏览器1和浏览器2分别发的请求,对服务器而言,通过HTTP请求本身根本无从分别。
在这里插入图片描述
        如果服务器没有办法分别请求来源于哪个浏览器,那就无法分别请求之间的关联性,也就是没有办法记录浏览器与服务器之间的会话。
        所谓会话(Session),通俗的讲就是用户打开浏览器访问某个网站,在网站上点击多个链接、按钮,访问服务器的多个资源,直到关闭浏览器为止,整个过程就称为一个会话。
        既然HTTP协议本身没有实现状态记录,那就需要服务器和浏览器协作,记录会话。
        实现的原理就是Cookie和Session技术,其中Session会话依赖于Cookie技术的实现。本篇文章会讲解Cookie,下篇文章讲解Session。
        Cookie本意是小饼干的意思,音译为曲奇,指的是小段信息。服务器生成Cookie,Cookie是键值对形式的字符串,Cookie会响应到浏览器所在的客户端的硬盘或内存中。并且可以设置Cookie在客户端存在的时间,如一个月或60秒。以后每次发起请求访问该网站,就会将该网站所保存在客户端的所有Cookie一并发送到服务器。
        如下图所示,Cookie的使用,需要在服务器端代码中至少有以下两段程序功能:
1.生成Cookie、设置时效、响应回浏览器
2.通过request对象获得浏览器发送来的所有Cookie,选择出所需的,进行处理。
在这里插入图片描述
        下面,我们通过在贯穿项目中通过一个功能来进行Cookie实战。功能如下图所示,当登录成功后,浏览器的登录页面会自动记录上次登陆的账号,时效是一分钟。
在这里插入图片描述
        UserController类的doLogin方法是负责登录功能,在登录成功时,生成Cookie,键值对信息是“username”和用户所填写的登录名,设置时效为60秒,并相应到浏览器。

//登录成功
if (u != null) {
    
    
	Cookie cookie = new Cookie("username", username);
	cookie.setMaxAge(60);
	response.addCookie(cookie);
	response.sendRedirect("stu");
}

        这样doLogin方法执行完,就会把cookie发送到浏览器对应客户端硬盘中保存60秒。然后在服务器端的showLogin方法中,添加一段获取键值为“username”的cookie:
//获得Cookies

String username="";
Cookie[] cookies = request.getCookies();
 if(cookies!=null){
    
    
  for(Cookie cookie:cookies){
    
    
	if("username".equals(cookie.getName())){
    
    
		username=cookie.getValue();
	}
  }
 }
 request.setAttribute("username", username);
request.getRequestDispatcher("WEB-INF/login.jsp").forward(request, response);

        在login.jsp页面中,只需要在request作用域中获得username的值,然后在账号文本框的value属性中显示即可。
完整的login.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
	pageEncoding="utf-8"%>
<%@ page import="java.util.*,entity.*"%>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title here</title>
<link rel="stylesheet"
	href="https://cdn.staticfile.org/twitter-bootstrap/3.3.7/css/bootstrap.min.css">

<style>
#main {
      
      
	width: 600px;
	margin: 120px auto;
}

#mes {
      
      
	color: red;
	text-align: center;
	margin-bottom: 20px;
}
</style>

<script src="https://cdn.staticfile.org/jquery/1.10.2/jquery.min.js"></script>
<script>
	$(document).ready(function() {
      
      

		$("[name='username']").keyup(function() {
      
      

			$("#mes").text("");

		})
	})
</script>

</head>
<body>

	<div id="main">
		<div id="mes">
			<%
				String mes = (String) request.getAttribute("mes");
				if (mes == null) {
					mes = "";

				}
				out.print(mes);
				String username=(String)request.getAttribute("username");
			%>
		
		</div>
		<form class="form-horizontal" action="user">
			<input type="hidden" name="type" value="doLogin" />
			<div class="form-group">
				<label class="col-sm-2 control-label">账号</label>
				<div class="col-sm-10">
					<input type="text" class="form-control" placeholder="请输入账号"
						name="username" value="<%=username %>">
				</div>
			</div>
			<div class="form-group">
				<label class="col-sm-2 control-label">密码</label>
				<div class="col-sm-10">
					<input type="password" class="form-control" placeholder="请输入密码"
						name="password">
				</div>
			</div>

			<div class="form-group">
				<div class="col-sm-offset-2 col-sm-10">
					<button type="submit" class="btn btn-primary">登录</button>
				</div>
			</div>
		</form>

	</div>
</body>
</html>

おすすめ

転載: blog.csdn.net/GodBlessYouAndMe/article/details/121897978
おすすめ