JavaWeb.07.服务器与客户端存储

一、为什么学习session会话(卡库)的操作?

就是为了解决多个页面数据不一致的问题(由于我们的数据全都在请求里面,我们每发起一次请求,数据就会不一样),所以我们为了解决这个问题,我们可以把数据存在后台的session(卡库)里面,从而每个页面都会有一个属于自己的卡号

二、session与cookie基本概念

session:会话(服务端存储)——》给后台用的

            前端如果带了卡号,后端直接使用这个卡号

            前端如果没有带卡号,后端生成一张新卡,重新把卡号给你

            劣势:session 中的数据是需要占用内存的,且服务器一启动session就没有了

cookie:小甜饼(客户端存储)——》给前台用的

            如果不设置时间,那么如果浏览器关闭,cookie会消失

            不要直接存储用户名和密码,因为从后台可以看到账号密码,因此需要MD5加密

            劣势:只能给字符串赋值

三、session与cookie的区别

session在后台就显示一个值:
在这里插入图片描述
cookie在后台会有多个值:
在这里插入图片描述

四、cookie实现七天免登陆

在做登录页面,保存在cookie内(存在自己的电脑上面)
登录doLogin.jsp页面

<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.DriverManager"%>
<%@page import="java.sql.Connection"%>
<%@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", "123");
	//获得执行对象
	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);
		
		
		//存前台【七天免登陆】——》保存在cookie(存在自己电脑上面)
		response.addCookie(cookie01);
		response.addCookie(cookie02);
 
		
		//localhost:8080/web04/news/index.jsp(项目的根目录)	 因为转发是在服务器里完成
		//request.getRequestDispatcher("/news/index.jsp").forward(request, response);
		response.sendRedirect("news/index.jsp");
	}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();
	}
%>

登录login.jsp页面

<%@ 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>
<%
	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="regiest.html"' 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>

五、 session完成历史记录

历史记录history.jsp页面

<%@page import="java.net.URLDecoder"%>
<%@page import="java.util.List"%>
<%@ 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">返回管理员首页<span class="glyphicon glyphicon-road"></span></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");
  		}
  	}	
    	//不是从数据库来的 从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>

首页index.jsp

<%@page import="java.nio.charset.StandardCharsets"%>
<%@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="zh">
 
<head>
    <meta charset="UTF-8">
    <title>bootstrap</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;
        }
 
        body,
        html {
            background: #7f8d90;
        }
 
        nav,
        .breadcrumb {
            border-radius: 0px !important;
            margin-bottom: 0px !important;
        }
 
        .breadcrumb {
            margin-bottom: 20px !important;
            background: #36485c;
            color: white;
        }
 
        li h4 {
            width: 300px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
        }
 
        .breadcrumb .active {
            color: yellow;
        }
    </style>
</head>
<%
	//怎么判断一个用户有没有登录
	Object username=session.getAttribute("username");
	if(username==null){
		response.sendRedirect("/web07/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="${pageContent.request.contentPath }/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="${pageContext.request.contextPath }/news/add.jsp">新闻发布</a></li>
                    <li class="divider"></li>
                    <li><a href="#">类别管理</a></li>
                </ul>
            </li>
        </ul>
        <ul class="nav navbar-nav navbar-right">
            <li><a><%=session.getAttribute("username") %></a></li>
            <li><a href="doExit.jsp">退出<span class="glyphicon glyphicon-off"></span></a></li>
        </ul>
    </div>
</nav>
 
<ol class="breadcrumb">
    <li>您当前的位置是</li>
    <li>新闻发布系统</li>
    <li class="active">首页</li>
</ol>
 
<form action="${pageContext.request.contextPath}/news/index.jsp" class="form-inline" style="margin: 0px auto 20px;" method="post">
    <div class="form-group" style="display: block;text-align: center;">
        <div class="input-group">
            <div class="input-group-addon">新闻标题</div>
            <input name="newName" class="form-control" placeholder="请在此输入搜索的关键字" type="text">
            <span class="input-group-btn">
                    <button class="btn btn-primary" type="submit">搜索🔍</button>
                </span>
        </div>
    </div>
</form>
 
<div class="container">
	<ul class="list-group">
	<%
	//关于method=“post”会乱码
	request.setCharacterEncoding("utf-8");
	//点击了表单之后 跳转的是当前这个页面 同时携带一个newName过来(查询的关键字)
	String newName=request.getParameter("newName");
	if(newName==null){
		newName="";//查询全部
	}
	
	//破碎重组【增高】(字符串变成字节数组,再把字节数组重新变成字符串)手动指定编码
//	new String(newName.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
	newName=new String(newName.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
	//加载驱动
		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_news02 where news_title like ?");
		//国-》select * from t_news02 where news_title like '%国%'
		ps.setString(1, "%"+newName+"%");
		
		
		//得到结果集
		ResultSet rs=ps.executeQuery();
		//结果集中有很多数据
		while(rs.next()){
			
	%>
	
    
        <li class="list-group-item">
            <h4 class="list-group-item-heading">
            <!--  newId=1-->
                <a href=
                "${pageContext.request.contextPath}/news/read.jsp?newId=<%=rs.getInt(1) %>" 
                data-placement="bottom" data-toggle="tooltip" href="" title="国家卫健委:昨日新增确诊病例29例,其中本土病例2例">
                    <%=rs.getString(2)%>
                </a>
            </h4>
            <p class="list-group-item-text text-right">
                <span class="glyphicon glyphicon-user"><code><%=rs.getString(4) %></code></span>
                <span class="glyphicon glyphicon-eye-open"><code><%=rs.getInt(7) %></code></span>
                <span class="glyphicon glyphicon-tag"><code><%=rs.getInt(8) %></code></span>
                <span class="glyphicon glyphicon-time"><code><%=rs.getString(5) %></code></span>
            </p>
        </li>
		<%
			}
		//资源的关闭
		if(con!=null&&!con.isClosed()){
			con.close();
		}
		if(ps!=null){
			ps.close();
		}
		if(rs!=null){
			rs.close();
		}
		%>
		
		
    </ul>
</div>
<div class="container text-center">
    <ul class="pagination" style="margin: 20px auto;">
        <li>
            <a href="#"><span>&laquo;</span></a>
        </li>
        <li><a href="#">1</a></li>
        <li><a href="#">2</a></li>
        <li><a href="#">3</a></li>
        <li><a href="#">4</a></li>
        <li><a href="#">5</a></li>
        <li>
            <a href="#"><span>&raquo;</span></a>
        </li>
    </ul>
</div>
<script>
    $(function () {
        $('[data-toggle="tooltip"]').tooltip({
            trigger: "hover"
        })
    })
</script>
</body>
</html>
 

阅读read.jsp页面

<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.Connection" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html lang="zh">
 
<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_NEWS02 where news_id=?");
    //占位符的设置
    ps.setInt(1,Integer.parseInt(newId));
    //得到结果集
    ResultSet rs = ps.executeQuery();
    //定义需要的值
    String title="";
    int count=0;
    String author="";
    String publisher="";
    String content="";
    //int marker=0;
    if(rs.next()){
        //可以取值
        title=rs.getString(2);
        publisher=rs.getString(5);
        author=rs.getString(4);
        content=rs.getString(6);
        count=rs.getInt(7)+1;//当前你是不是阅读了一次
    }
    //将阅读信息存到集合里
    historyList.add(title+"@"+count);
    //将历史记录集合重新放到session
    session.setAttribute("historyList", historyList);
    
    
    //已经被阅读了
    ps=con.prepareStatement("update t_news02 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">
        <!-- newId是index传过来的 -->
            <a href="${pageContext.request.contextPath}/news/doDel.jsp?newId=<%=newId%>" 
            class="btn btn-danger" type="button">删除</a>
        </div>
        <div class="btn-group">
        <!-- 将newId也传给修改界面 -->
            <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;">
    <div class="panel panel-default" style="margin-top: 20px;">
        <%
        	ps=con.prepareStatement("select * from t_comment02 where comment_from=?");
        ps.setInt(1, Integer.parseInt(newId));
        rs=ps.executeQuery();
        while(rs.next()){
        
        %>
        <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>
        <%
       		 }
        %>
    </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>

六、 session的清空与鉴权

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
	//session 的存储时间
	//session.setMaxInactiveInterval(60);
 
	//怎么删除session
	session.invalidate();
	
	//跳回登录页面
	response.sendRedirect("/web07/login.jsp");
%>
  • 4
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值