目录
一、什么是会话?
一个会话就是浏览器与服务器之间的一次通话,包含浏览器与服务器之间的多次请求、响应过程
Session
概念
Session在网络中被称为会话(服务端存储 session中的数据占运行内存)。
由于HTTP协议(超文本传输协议)是一种无状态协议,也就是当一个客户向服务器发出请求,服务器接收请求,并返回响应后,该连接就结束了,而服务器并不保存相关的信息。
为了弥补这一缺点,HTTP协议提供了Session。通过Session可以在应用程序的WEB页面间进行跳转时,保存用户的状态,使整个用户会话一直存在下去,直到关闭浏览器。
session对象常用方法
类型 | 方法名称 | 说 明 |
void | setAttribute(String key,Object value) | 以key/value的形式保存对象值 |
Object | getAttribute(String key) | 通过key获取对象值 |
int | getMaxInactiveInterval() | 获取session的有效非活动时间,以秒为单位 |
String | getId() | 获取session对象的编号 |
void | invalidate() | 设置session对象失效 |
注意:getAttribute()方法返回的是Object对象,如果将获取的信息赋值给String类型的变量,则需要进行强制类型转换或调用其toString()方法,例如,下面的两行代码都是正确的。
String user = (String)session.getAttribute("username");
String user1 = session.getAttribute("username").toString();
一个session对应一个窗口,那么通过超链接打开的窗口是否也是新的session呢?
每个session对象都与浏览器一一对应 重新开启一个浏览器,相当于重新创建一个 session对象重新开启一个IE窗口,直接访问系统首页面
通过超链接打开的新窗口,新窗口的session与其父窗口的session相同
Session对象的判断
在登录后的JSP页面文件中,通过Session来做是否已登录的判断:
String username=session.getAttribute("username");
if(username==null){
response.sendRedirect("login.jsp");
}
二、Cookie
Cookie是什么?
Cookie是存储在客户机的文本文件,他们保存了大量的轨迹信息(客户端存储 不要存储用户名和密码 如果要存建议加密)
Cookie的中文意思是“小甜饼”,然而在互联网上的意思与这就完全不同了。它和食品完全没有关系。
在互联网中,Cookie是小段的文本信息,在网络服务器上生成,并发送给浏览器。通过使用cookie可以标识用户身份,记录用户名和密码,跟踪重复用户等。浏览器将cookie以key/value的形式保存到客户机的某个指定目录中。
Cookie的查看
如果不设置时间,当浏览器关闭时,cookie会消失,前端数据都共享一个Cookie,不会生成新的Cookie。所以,当前端的cookie中有卡号时,后端就直接使用这个卡号;当前端因为关闭再打开而丢失了卡号时,后端就会生成一个新的卡号使用。只有在进行数据操作时,才会生成卡号,以避免卡号浪费
先在网页上右键点击检查,之后再选中应用:
Cookie的使用
通过page指令导入包(可省略)
<%@ page import="javax.servlet.http.Cookie" %>创建
Cookie newCookie=new Cookie("数据名",数据值);写入(将Cookie响应到客户端)
response.addCookie(newCookie)提示:
a. 在创建Cookie后,如未设置Cookie有效期,则该Cookie只保存在浏览上,当浏览重启 后,之前设置的Cookie就不在了,如这时用getCookies()方法取就是null,因此会报 NullPointerException异常。
临时Cookie----保存在浏览器上的Cookie。它随着浏览器的关闭而消失。
要想Cookie真正保存在客户端上,就必须设置Cookie的保存时间。
b. Internet临时文件设置,如勾上,则会清掉cookie。
Cookie常用方法
类型 | 方法名称 | 说 明 |
void | setMaxAge(int expiry) | 设置Cookie的有效期,以秒为单位 |
void | setValue(String value) | 在Cookie创建后,对Cookie进行赋值 |
String | getName() | 获取Cookie的名称 |
String | getValue() | 获取Cookie的值 |
String | getMaxAge() | 获取Cookie的有效时间,以秒为单位 |
通过cookie的getCookie()方法即可获取到所有cookie对象的集合;
通过cookie对象的getName()方法可以获取到指定名称的cookie;
通过getValue()方法即可获取到cookie对象的值。
另外,将一个cookie对象发送到客户端,使用response对象的addCookie()方法。
关于Cookie的删除
Cookie不能通过代码删,但可以通过代码设置它无效:即设置它的有效时间。
<%
Cookie[] cooks=request.getCookies()
if(cooks!=null){
for(Cookie c:cooks){
if(c.getName().equals("uname")){
c.setMaxAge(0); //设置Cookie有效期0秒
response.addCookie(c);
}
}
}
response.sendRedirect("/login.jsp");
%>
Session和Cookie的优缺点
Session存储
优点:解决了每次发送不同的新请求导致的数据不一致的问题;当浏览器关闭时,服务器的存储不会丢失;session中存储类型不限,可以是数组,字符串,集合,数字等等;
缺点:session中的数据是需要占用运行内存的,容易卡死;当web项目服务器关闭时,sessio中的数据就会被清空;
Cookie存储
优点:cookie可以跨越同域名下的多个网页使用;也可以实现跨页面全局变量;同一个网站中所有页面共享一套cookie,可以设置有效期限;cookie机制将信息存储于用户硬盘,因此可以作为跨页面全局变量;
缺点:cookie可能被禁用;cookie与浏览器相关,不能互相访问;cookie可能被用户删除;当浏览器关闭时,前端Cookie的存储会丢失,安全性不够高;Cookie只能存储字符串类型的数据;cookie存储空间很小(只有4KB左右);cookie操作麻烦,没有方便的API
注:数据库存储比cookie,session存储都慢
针对Cookie存储安全性不够高,可以使用DM5加密:
关于cookie乱码
放进入之前进行编码
String username1 = URLEncoder.encode(username, "utf-8");
取值的时候进行解码
String username1 = URLDecoder.decode(cookies[i].getValue(),"utf-8");
三,七天免登录功能
设置七天免登录 用户进入登录界面用户名和密码自动显示
处理登录的代码;
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="oracle.jdbc.driver.OracleDriver"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%
request.setCharacterEncoding("utf-8");
String yh=request.getParameter("yh");
String mm=request.getParameter("mm");
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//定义连接字符串
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//获得连接
Connection con=DriverManager.getConnection(url,"scott","123123");
//获得执行对象
PreparedStatement ps=con.prepareStatement("select * from tb_user where user_name=? and user_pwd=?");
ps.setString(1, yh);
ps.setString(2,mm);
//获得结果集
ResultSet rs=ps.executeQuery();
//判断结果
if(rs.next()){
//调用用户存入到服务器的session中
session.setAttribute("username", yh);
//cookie每次发送请求会被自动带上
//cookie默认是在你当前服务器打开的过程中生效的
Cookie cookie1=new Cookie("yh",yh);
//设置存活时间 s
//-1是在你当前浏览器打开的过程中生效
Cookie cookie2=new Cookie("mm",mm);
cookie1.setMaxAge(60*60*24*7);//设置用户名的时间
cookie2.setMaxAge(60*60*24*7);//设置密码时间
//存到前台
response.addCookie(cookie1);
response.addCookie(cookie2);
response.sendRedirect("news/index.jsp");
// request.getRequestDispatcher("/news/index.jsp").forward(request,response);
}else{
//重定向 客户端
/**
(localhost:8080/web04/)跳转的时候:
a.jsp 跳转到当前(同级)路径下的a.jsp (localhost:8080/web04/a.jsp)
../a.jsp 跳转到上一级路径下的a.jsp (localhost:8080/a.jsp)
/a.jsp 根目录的a.jsp(localhost:8080/a.jsp)
**/
response.sendRedirect("login.jsp");
}
//资源关闭
if(con!=null&&!con.isClosed()){
con.close();
}
if(ps!=null){
ps.close();
}
if(rs!=null){
rs.close();
}
%>
登录界面的代码:
如果客户端没有cookie 那么会报空值错误 所以在进行判断的时候要先非空判断
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link href="/web04/bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet">
<script src="/web04/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
<script src="/web04/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<style>
* {
outline: none !important;
}
html,
body {
background: #1abe9c;
}
form {
width: 300px;
background: #ebeff2;
box-shadow: 0px 0px 50px rgba(0, 0, 0, .5);
border-radius: 5px;
padding: 20px;
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%);
}
.btn-group {
width: 100%;
}
.btn-group button {
width: 50%;
}
</style>
</head>
<body>
<%
//如果客户端没有cookie 那么会报空值错误
String yh="";
String mm="";
if(request.getCookies()!=null)
for(Cookie cookie:request.getCookies()){
if(cookie.getName().equals("yh")){
yh=cookie.getValue();
}
if(cookie.getName().equals("mm")){
mm=cookie.getValue();
}
}
%>
<form action="doLogin.jsp" method="post" id="myForm">
<h3 class="text-center">欢迎使用⭐币新闻管理</h3>
<div class="form-group">
<input value="<%=yh%>" class="form-control" id="username" name="yh" placeholder="请输入您的邮箱" type="text">
</div>
<div class="form-group">
<input value="<%=mm%>" class="form-control" id="password" name="mm" placeholder="请输入您的密码" type="password">
</div>
<div class="btn-group">
<button class="btn btn-primary" type="submit">登录</button>
<button class="btn btn-danger" onclick='location=href="${pageContext.request.contextPath}/register.jsp"' type="button">没有账号?</button>
</div>
</form>
<script>
$("#myForm").submit(()=>{
if($("#username").val().length==0){
alert("用户名不能为null")
return false //不提交的
}
if($("#password").val().length==0){
alert("密码不能为null")
return false //不提交的
}
return true
})
</script>
</body>
</html>
当新闻被点击进入到阅读界面之后 此新闻会在历史记录的界面中出现
阅读界面代码
<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.List"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html lang="">
<head>
<meta charset="UTF-8">
<title>bootstrap</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="/web04/bootstrap-3.3.7-dist/css/bootstrap.css">
<script src="/web04/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
<script src="/web04/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
<style>
* {
outline: none !important;
}
body,
html {
background: #7f8d90;
}
nav,
.breadcrumb {
border-radius: 0px !important;
margin-bottom: 0px !important;
}
.breadcrumb {
margin-bottom: 20px !important;
background: #36485c;
color: white;
}
input,
select,
textarea,
.panel-heading {
border: none !important;
border-radius: 0px !important;
}
.breadcrumb .active {
color: yellow;
}
</style>
</head>
<% Object username=session.getAttribute("username");
if(username==null){
response.sendRedirect("/web04/login.jsp");
}
%>
<body>
<nav class="navbar navbar-default hidden-sm hidden-xs">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" href="${pageContext.request.contextPath}/news/index.html" style="font-size: 25px;">⭐</a>
</div>
<ul class="nav navbar-nav">
<li class="dropdown">
<a class="dropdown-toggle" data-toggle="dropdown">
新闻管理
<span class="caret"></span>
</a>
<ul class="dropdown-menu">
<li><a href="/web04/news/add.jsp">新闻发布</a></li>
<li class="divider"></li>
<li><a href="/web04/news/show.jsp">类别管理</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a><%=session.getAttribute("username")%></a></li>
<li><a href="${pageContext.request.contextPath}/news/history.jsp">历史记录</a></li>
<li><a href="${pageContext.request.contextPath}/login.jsp">退出<span class="glyphicon glyphicon-off"></span></a></li> </ul>
</div>
</nav>
<ol class="breadcrumb">
<li>您当前的位置是</li>
<li>新闻发布系统</li>
<li class="active">新闻阅读</li>
</ol>
<%
//去session拿里历史列表
Object obj=session.getAttribute("historyList");
List<String>historyList=new ArrayList<>();
if(obj!=null){//有历史列表
historyList=(List<String>)obj;
}
//获得新闻的id
String newId=request.getParameter("newId");
//拿到cookie
String ls="";
for(Cookie cookie:request.getCookies()){
if(cookie.getName().equals("historyList")){
ls=cookie.getValue();
}
}
ls+=newId+",";
response.addCookie(new Cookie("historyList",URLEncoder.encode(ls, "utf-8")));
//根据id去数据库做查询操作
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//定义连接字符串
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//获得连接
Connection con=DriverManager.getConnection(url,"scott","123123");
//获得执行对象(查询所有的新闻数据)
PreparedStatement ps=con.prepareStatement("select * from t_news where news_id=?");
ps.setInt(1, Integer.parseInt(newId));
//得到结果集
ResultSet rs=ps.executeQuery();
//定义需要的值
String title="";
int count=0;
String author="";
String publisher="";
String content="";
if(rs.next()){
//进行赋值
title=rs.getString(2);
publisher=rs.getString(5);
author=rs.getString(4);
content=rs.getString(6);
count=rs.getInt(8)+1;//当前自己阅读了一次
}
//将阅读信息存到集合中
historyList.add(title+"@"+count);
//将历史记录集合重新放到session
session.setAttribute("historyList", historyList);
//已经被阅读了
ps=con.prepareStatement("update t_news set news_count=news_count+1 where news_id=?");
ps.setInt(1, Integer.parseInt(newId));
ps.executeUpdate();//不需要判断
%>
<div class="container" style="background: rgba(239, 231, 231, 0.9);border-radius:10px;">
<h1><%=title %></h1>
<h3 class="text-right">
<small>
<span class="glyphicon glyphicon-user"><span class="label label-default"><%=author %></span></span>
<span class="glyphicon glyphicon-eye-open"><span class="label label-default"><%=count %></span></span>
<span class="glyphicon glyphicon-time"><span class="label label-info"><%=publisher %></span></span>
</small>
</h3>
<samp><%=content %></samp>
<div class="btn-group btn-group-justified" style="margin-bottom: 20px;">
<div class="btn-group">
<a href="${pageContext.request.contextPath}/news/doDel.jsp?newId=<%=newId %>" class="btn btn-danger">删除</a>
</div>
<div class="btn-group">
<a href="${pageContext.request.contextPath}/news/upd.jsp?newId=<%=newId %>" class="btn btn-info">修改</a>
</div>
</div>
</div>
<div class="container" style="background: rgba(239, 231, 231, 0.9);border-radius:10px;margin-top: 10px;">
<%
ps=con.prepareStatement("select * from t_comment where comment_from=?");
ps.setInt(1, Integer.parseInt(newId));
rs=ps.executeQuery();
while(rs.next()){
%>
<div class="panel panel-default" style="margin-top: 20px;" >
<div class="panel-heading">
<span class="glyphicon glyphicon-user" ><span class="label label-success"><%=rs.getString(4) %></span></span>
<p style="margin-top: 10px;text-indent: 2em;">
<samp><%=rs.getString(5) %></samp>
</p>
<p class="text-right">
<span class="glyphicon glyphicon-time"><span class="label label-info"><%=rs.getString(3) %></span></span>
</p>
<a href="${pageContext.request.contextPath}/news/doDelPl.jsp?newId=<%=newId %>&&id=<%=rs.getInt(1) %>" class="btn btn-danger">删除</a> </div>
</div>
<%
}
%>
<form action="doAddpl.jsp" class="container" style="background: rgba(239, 231, 231, 0.9);border-radius:10px;margin-top: 10px;padding: 30px;">
<input type="hidden" name="newId" value="<%=newId%>">
<div class="form-group">
<label for="">Name</label>
<input type="text" class="form-control" name="author" placeholder="用户名称" required>
</div>
<div class="form-group">
<label for="">content</label>
<input type="text" class="form-control" name="content" placeholder="评论内容" required>
</div>
<button type="submit" class="btn btn-default">发布评论</button>
</form>
<div style="height: 50px;"></div>
</body></html>
浏览的历史记录的界面
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>Document</title>
<meta content="width=device-width, initial-scale=1" name="viewport">
<link href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css" rel="stylesheet">
<script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/jquery-3.5.1.js"></script>
<script src="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/js/bootstrap.js"></script>
</head>
<body>
<nav class="navbar navbar-default hidden-sm hidden-xs">
<div class="container-fluid">
<div class="navbar-header">
<a class="navbar-brand" style="font-size: 25px;">当前是您的浏览记录</a>
</div>
<ul class="nav navbar-nav navbar-right" style="margin-right: 20px;">
<li><a href="${pageContext.request.contextPath}/news/index.jsp">返回首页</a></li>
</ul>
</div>
</nav>
<div class="container">
<ul class="list-group">
<%
//从cookie中取历史记录
String ls="";
for (Cookie cookie : request.getCookies()) {
if(cookie.getName().equals("historyList")){
ls= URLDecoder.decode(cookie.getValue(),"utf-8"); ;
}
}
System.out.println(ls);
//不是从数据库来的 从session中拿到的
Object obj = session.getAttribute("historyList");
if(obj!=null){
List<String> historyList=(List<String>)obj;
for (int i=historyList.size()-1;i>=0;i--) {
//倒着来
String[] ss=historyList.get(i).split("@");
%>
<li class="list-group-item">
<span class="badge"><%=ss[1]%></span>
<%=ss[0]%>
</li>
<%
}
}
%>
</ul>
</div>
</body>
</html>
今天的分享就到这里结束啦!!✌
以上就是Java Web 服务器与客户端储存的一些内容!!📖
感 谢 阅 读☺ ☺ ☺ ☺