目录
1.session是在服务器端保存用户信息,Cookie是在客户端保存用户信息
2.session中保存的是对象,Cookie保存的是字符串
3.session随会话结束而关闭,Cookie可以长期保存在客户端
4.Cookie通常用于保存不重要的用户信息,重要的信息使用session保存
效果:利用session来完成阅读新闻后在历史阅读界面可以找到刚刚阅读过的那条新闻。
一,什么是会话:
一个会话就是浏览器与服务器之间的一次通话,包含浏览器与服务器之间的多次请求、响应过程
二,JSP内置对象session
session的概念:
Session在网络中被称为会话(服务端存储 session中的数据占运行内存)。
由于HTTP协议(超文本传输协议)是一种无状态协议,也就是当一个客户向服务器发出请求,服务器接收请求,并返回响应后,该连接就结束了,而服务器并不保存相关的信息。
为了弥补这一缺点,HTTP协议提供了Session。通过Session可以在应用程序的WEB页面间进行跳转时,保存用户的状态,使整个用户会话一直存在下去,直到关闭浏览器。
session对象用来存储有关用户会话的所有信息
session对象常用方法:
session与窗口的关系
每个session对象都与浏览器一一对应 重新开启一个浏览器,相当于重新创建一个session对象重新开启一个IE窗口,直接访问系统首页面
通过超链接打开的新窗口,新窗口的session与其父窗口的session相同
三,Cookie
1.什么是cookie
Cookie是Web服务器保存在客户端的一系列文本信息
2.生活中的cookie
浏览购物网站查看不同商品时,系统会自动记录已经浏览过的商品
3.Cookie的作用
对特定对象的追踪 统计网页浏览次数 简化登录
4.cookie的缺点:
容易信息泄露
5.cookie的语法
导入包:
import="javax.servlet.http.Cookie"
创建cookie:
parameter:用于代表cookie的名称(key)
value:用于表示当前key名称所对应的值
Cookie newCookie=new Cookie("parameter", "value");
写入cookie
response.addCookie(newCookie)
6.设置Cookie属性的常用方法
四,session和cookie的比较:
1.session是在服务器端保存用户信息,Cookie是在客户端保存用户信息
2.session中保存的是对象,Cookie保存的是字符串
3.session随会话结束而关闭,Cookie可以长期保存在客户端
4.Cookie通常用于保存不重要的用户信息,重要的信息使用session保存
五,session和cookie在JSP中的应用(示例)
1.利用cookie实现7天免登录
效果:就是利用cookie做出七天内只要登陆过账号就可以在下一次登录时直接将密码和账号显示在输入框中(密码加密)
代码:
dologin.jsp界面(登陆处理界面)
<%@page import="oracle.jdbc.driver.OracleDriver" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.nio.charset.StandardCharsets" %>
<%@ page import="java.util.Arrays" %>
<%@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");
try {
//加载驱动
Class.forName("oracle.jdbc.driver.OracleDriver");
//定义连接字符串
String url = "jdbc:oracle:thin:@localhost:1521:orcl";
//获得连接
Connection con = DriverManager.getConnection(url, "scott", "tiger");
//获得执行对象
PreparedStatement ps = con.prepareStatement("select * from t_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 cookie01=new Cookie("yh",yh);
//设置存活时间 s
// -1 是在你当前浏览器打开的过程中生生效
cookie01.setMaxAge(60*60*24*7);
Cookie cookie02=new Cookie("mm",mm);
cookie02.setMaxAge(60*60*24*7);
//存到前台 【七天免登录】
response.addCookie(cookie01);
response.addCookie(cookie02);
// localhost:8080/当前项目/news/index.jsp
// request.getRequestDispatcher("/news/index.jsp").forward(request, response);
response.sendRedirect("news/index.jsp");
} else {
//重定向 客户端
response.sendRedirect("login.jsp");
}
//资源关闭
if (!con.isClosed()) {
con.close();
}
ps.close();
rs.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
login.jsp界面(登陆界面)
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" %>
<!DOCTYPE html>
<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>
<style>
* {
outline: none !important;
}
html,
body {
background: #1abe9c;
}
form {
width: 300px;
background: #ebeff2;
box-shadow: 0 0 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>
<%
String yh="";
String mm="";
//如果客户端没有cookie 那么会报空值异常
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();
}
}
%>
<body>
<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="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>
2.利用session完成历史记录
效果:利用session来完成阅读新闻后在历史阅读界面可以找到刚刚阅读过的那条新闻。
代码:
read.jsp界面(新闻阅读界面)
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<head>
<meta charset="UTF-8">
<title>bootstrap</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>
<style>
* {
outline: none !important;
}
body,
html {
background: #7f8d90;
}
nav,
.breadcrumb {
border-radius: 0 !important;
margin-bottom: 0 !important;
}
.breadcrumb {
margin-bottom: 20px !important;
background: #36485c;
color: white;
}
input,
select,
textarea,
.panel-heading {
border: none !important;
border-radius: 0 !important;
}
.breadcrumb .active {
color: yellow;
}
</style>
</head>
<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.jsp"
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="#">新闻发布</a></li>
<li class="divider"></li>
<li><a href="#">类别管理</a></li>
</ul>
</li>
</ul>
<ul class="nav navbar-nav navbar-right">
<li><a>245@qq.com</a></li>
<li><a href="#">退出<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 【historyList】
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", "123");
//查询所有的新闻数据
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" type="button">删除</a>
</div>
<div class="btn-group">
<a href="${pageContext.request.contextPath}/news/upd.jsp?newId=<%=newId%>" class="btn btn-info" type="button">修改</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>
<div class="btn-group">
<a class="btn btn-info" type="button">删除</a>
</div>
</div>
</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">Name</label>
<input id="name" class="form-control" name="author" placeholder="用户名称" required type="text">
</div>
<div class="form-group">
<label for="email">Email</label>
<input id="email" class="form-control" name="content" placeholder="评论内容" required type="text">
</div>
<button class="btn btn-default" type="submit">发布评论</button>
</form>
<div style="height: 50px;"></div>
</body>
</html>
history.jsp界面(历史阅读记录显示界面)
<%@ page import="java.util.List" %>
<%@ page import="java.net.URLDecoder" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<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>
今天给大家分享的JavaWeb小知识就到这里啦,精彩下期继续哦。