JavaWeb——服务器与客户端存储

家人们好!我今天又带着热乎乎的知识来啦~

目录

一.session

1.session的概念.

2.session的理念.

3.session的大致讲解

二.Cookie

1.Cookie的概念.

2.Cookie的使用

3.关于Cookie的删除

4.Cookie的常用方法

三.seesion与Cookie的比较

四.案例分享

1.实现七天免登录

2.完成历史浏览记录


一.session

1.session的概念.

Session在网络中被称为会话。
    由于HTTP协议(超文本传输协议)是一种无状态协议,也就是当一个客户向服务器发出请求,服务器接收请求,并返回响应后,该连接就结束了,而服务器并不保存相关的信息。
为了弥补这一缺点,HTTP协议提供了Session.

 

2.session的理念.

通过Session可以在应用程序的WEB页面间进行跳转时,保存用户的状态,使整个用户会话一直存在下去,直到关闭浏览器。

但是,如果在一个会话中,客户端长时间不向服务端发出请求,Session对象就会自动消失。这个时间取决于服务器,例如,Tomcat服务器默认为30分钟。不过这个时间可以通过编写程序进行修改。

实际上,一次会话的过程也可以理解为一个打电话的过程。通话从拿起电话或手机拨号开始,一直到挂断电话结束,在这个过程中,可以与对方聊很多话题,甚至重复的话题。一个会话也是这样,可以重复访问相同的Web页

3.session的大致讲解

 Session就是会话(客户端的一次请求,服务端的一次响应)。
 Session用于跟踪客户的状态。
 Session指的是在一段时间内,单个客户与Web服务器的一连串相关的交互过程。
 在一个Session中,客户可能会多次请求访问同一个网页,也有可能请求访问各种不同的服  务器资源。

  Session对象的生命周期:创建 --> 使用 --> 消亡

  Session不会限制类型

  session是存在运行内盘里面的,服务器一关闭,session会话全没了

 

二.Cookie

1.Cookie的概念.

  Cookie的中文意思是“小甜饼”,然而在互联网上的意思与这就完全不同了。它和食品完全没  有关系。
    在互联网中,Cookie是小段的文本信息,在网络服务器上生成,并发送给浏览器。通过使用cookie可以标识用户身份,记录用户名和密码,跟踪重复用户等。浏览器将cookie以key/value的形式保存到客户机的某个指定目录中。
    通过cookie的getCookie()方法即可获取到所有cookie对象的集合;
    通过cookie对象的getName()方法可以获取到指定名称的cookie;
    通过getValue()方法即可获取到cookie对象的值。
    另外,将一个cookie对象发送到客户端,使用response对象的addCookie()方法。

 注意:在使用cookie时,应保证客户机上允许使用cookie。这可以通过在IE浏览器中选择“工具”/“Internet选项”命令,在打开对话框的“隐私”选项卡中进行设置

2.Cookie的使用

  5.1 通过page指令导入包(可省略)
  <%@ page import="javax.servlet.http.Cookie" %>

  5.2 创建
  Cookie newCookie=new Cookie("key",value);

  5.3 写入(将Cookie响应到客户端)
  response.addCookie(newCookie)

3.关于Cookie的删除

 Cookie是保存在客户端电脑上的文件,如果服务器可以直接通过代码来清除客户端上的文 件,那将是个非常可怕的事情,因为客户端已经变成“肉鸡”了。
  所以,客户端的Cookie不能由服务器代码来删,而是客户端自己删。

Cookie不能通过代码删,但可以通过代码设置它无效:即设置它的有效时间。

4.Cookie的常用方法

 

Cookie默认浏览器被打开的时候生效
Cookie是存在自己的电脑中的

Cookie的特性:如果不设置时间,那么如果浏览器关闭,Cookie会消失

三.seesion与Cookie的比较

 

四.案例分享

1.实现七天免登录

   登录界面

<%@ 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 name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css">
    <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: 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%>" id="uname" name="yh" type="text" class="form-control" placeholder="请输入您的用户名">
        </div>
        <div class="form-group">
            <input value="<%=mm%>" id="upwd" name="mm" type="password" class="form-control" placeholder="请输入您的密码">
        </div>
        <div class="btn-group">
            <button type="submit" class="btn btn-primary">登录</button>
            <button type="button" class="btn btn-danger" onclick='location=href="regiest.html"'>没有账号?</button>
        </div>
    </form>
    <script type="text/javascript">
    
    $("#Myform").submit(()=>{
    	if($("#uname").val().lenth==0){
    		alert("用户名不能为空");
    		return false;//返回的值为false,代表不提交
    	}
    	if($("#upwd").val().lenth==0){
    		alert("密码不能为空");
    		return false;//返回的值为false,代表不提交
    	}
    	return true;
    })
    
    </script>
</body></html>

   登录功能界面

<%@page import="oracle.jdbc.driver.OracleDriver"%>
<%@page import="java.sql.ResultSet"%>
<%@page import="java.sql.PreparedStatement"%>
<%@page import="java.sql.Connection"%>
<%@page import="java.sql.DriverManager"%>

<%@ 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");
//1.加载驱动
 Class.forName("oracle.jdbc.driver.OracleDriver");
//2.定义连接字符
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//3.获得连接
Connection con=DriverManager.getConnection(url, "scott", "tlt1516131462qmt");
//4.获取执行对象
PreparedStatement ps=con.prepareStatement("select * from web01_user where uname=? and upwd=?");
ps.setString(1,yh);
ps.setString(2,mm);
//5.获得结果集
ResultSet rs=ps.executeQuery();
//6.判断结果
if(rs.next()){
	//将用户名存入到服务器的session中
	//session.setAttribute("uname",yh);
	//request.getRequestDispatcher("index.jsp").forward(request, response);
	//Cookie的值在请求中自动带上
	//Cookie默认是在你当前浏览器打开的过程中生效
	Cookie cookie1=new Cookie("yh",yh);
	cookie1.setMaxAge(60*60*24*7);//设置存活时间,如果设置是-1,那么就只能在浏览器被打开的过程中生效
	//存7天 60*60*24*7 [七天免登录]
	
	Cookie cookie2=new Cookie("mm",mm);
	//存到前台  
	response.addCookie(cookie1);
	response.addCookie(cookie2);
	response.sendRedirect("index.jsp"); 
}else{
	response.sendRedirect("Login.jsp");
}
//7.关闭资源
if(con!=null&&!con.isClosed()){
	con.close();
}
if(ps!=null){
	ps.close();
}
if(rs!=null){
	rs.close();
}




%>

2.完成历史浏览记录

<%@page import="java.net.URLEncoder"%>
<%@page import="java.util.ArrayList"%>
<%@page import="java.util.List"%>
<%@page import="oracle.jdbc.driver.OracleDriver"%>
<%@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 name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="${pageContext.request.contextPath}/bootstrap-3.3.7-dist/css/bootstrap.css">
    <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: 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>

<body>
    <nav class="navbar navbar-default hidden-sm hidden-xs">
        <div class="container-fluid">
            <div class="navbar-header">
                <a class="navbar-brand" href="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
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","tlt1516131462qmt");
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(7)+1;//阅读一次就加1
}

//将阅读信息存到信息中
historyList.add(title+"@"+count);
//将历史记录重新放入session中
session.setAttribute("historyList", historyList);

//进行到这里,已经被阅读了
ps=con.prepareStatement("update t_news set news_clink=news_clink+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}/doDel.jsp?newId=<%=newId%>" type="button" class="btn btn-danger">删除</a>
            </div>
           
            <div class="btn-group">
                <a href="${pageContext.request.contextPath}/Update.jsp?newId=<%=newId%>"  type="button" 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 cl ass="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>
        

    <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 name="author" type="text" class="form-control" placeholder="用户名称" required>
        </div>
        <div class="form-group">
            <label for="">Email</label>
            <input name="content" type="text" class="form-control" placeholder="评论内容" required>
        </div>
        <button type="submit" class="btn btn-default">发布评论</button>
    </form>

    <div style="height: 50px;"></div>
</body></html>

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@page import="java.net.URLDecoder"%>
<%@page import="java.util.List"%>
<!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}/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");
    	}
    }
    System.out.print(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>


好啦,今天的代码就分享到这里啦~大家下期见!

永远迎着光走.

  • 6
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值