JavaWeb-Cookie、Session及浅谈JSP

在这里插入图片描述

Cookie、Session

会话
  • 会话:用户打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可以称之为会话;
  • 有状态会话:
    1.可以在不同的方法调用间保持针对各个客户端的状态
    2.与客户端的联系必需被维持;通常开销较大
    3.有状态会话Bean(实体类)会保存客户端的状态
  • 无状态会话:
    1.在不同方法调用间不保留任何状态
    2.事务处理必须在一个方法中结束
    3.通常资源占用较少;可以被共享(因为它是无状态的)
    4.无状态不会"专门"保存客户端的状态
  • 一个网站,怎么证明你来过?
    客户端--------------服务端
    1.服务端给客户端一个 信件,客户端下次访问服务端带上信件就可以了:cookie
    2.服务器登记你来过了,下次你来的时候我来匹配你:session
保存会话的两种技术

Cookie:
------客户端技术(响应、请求)
Session:
------服务端技术,利用这个技术,可以保存用户的会话信息,我们可以把信息或者数据放在Session中!
场景常见:网站登录之后,下次就不用再登录了,第二次访问就直接上去了!

Cookie

在这里插入图片描述
1.从请求中获取Cookie数组(可以获取会话信息)
2.新建一个Cookie(保存你想保存的会话信息)
3.服务端响应给客户端Cookie

public class CookieDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        //从请求中获取Cookie数组
        javax.servlet.http.Cookie[] cookies = req.getCookies();
        PrintWriter out = resp.getWriter();
        //如果Cookie数组不为空,则遍历Cookie数组,并获取“time”的值
        if(cookies!=null){
            out.write("上次访问的时间是:");
            for (Cookie cookie : cookies) {
                if(cookie.getName().equals("time")){    //判断cookie的键是不是“time”
                    String value = cookie.getValue();   //获取cookie键是“time”对应的值
                    long l = Long.parseLong(value);
                    Date date = new Date(l);
                    out.write(date.toLocaleString());
                }
            }
        }else {
            out.write("欢迎你第一次来到本站");
        }
        long l = System.currentTimeMillis();
        //新建一个Cookie,保存用户的会话信息
        Cookie cookie = new Cookie("time", String.valueOf(l));
        //服务端响应给客户端一个Cookie
        resp.addCookie(cookie);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

}
cookie:一般会保存在本地的 用户目录下 appdata;

在这里插入图片描述

一个网站cookie是否存在上限!
  • 一个Cookie只能保存一个信息
  • 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie
  • Cookie大小有限制4kb
  • 300个cookie浏览器上限
删除cookie
  • 不设置有效期,关闭浏览器,自动失效
  • 设置有效时间为0
编码解码
URLEncoder.encode("大王叫我来巡山","utf-8")
URLDecoder.decode(cookie.getValue(),"utf-8")
Session

在这里插入图片描述

什么是Session
  • 服务器会给每一个用户(浏览器)创建一个Seesion对象
  • 一个Seesion独占一个浏览器,只要浏览器没有关闭,这个Session就存在
  • 用户登录之后,整个网站它都可以访问!–> 保存用户的信息;保存购物车的信息……
Session和Cookie的区别
  • Cookie是把用户的数据写给用户的浏览器,浏览器保存 (可以保存多个)
  • Session把用户的数据写到用户独占Session中,服务器端保存 (保存重要的信息,减少服务器资源的浪费)
  • Session对象由服务器端创建;
Session的使用场景
  • 保存一个登录用户的信息
  • 购物车信息
  • 在整个网站中经常会使用的数据,我们将它保存在Session中
使用Session的步骤

1.编写实体类继承HttpServlet类

public class SessionDemo extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException{
        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        session.setAttribute("student",new Student("张三",18,"男"));
        PrintWriter out = resp.getWriter();
        String id = session.getId();
        if(session.isNew()){
            out.write("Session创建成功了,它的ID是:"+id);
        }else {
            out.write("Session已创建");
            Student student =(Student) session.getAttribute("student");
            out.write(student.toString());
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }
}

2.在web.xml文件中添加Servlet映射

<servlet>
    <servlet-name>sessionDemo</servlet-name>
    <servlet-class>SessionDemo</servlet-class>      
</servlet>
<servlet-mapping>
    <servlet-name>sessionDemo</servlet-name>
    <url-pattern>/s1</url-pattern>   //映射地址
</servlet-mapping>
设置Session会话自动过期

在web.xml中设置

<!--设置Session默认的失效时间-->
<session-config>
    <!--15分钟后Session自动失效,以分钟为单位-->
    <session-timeout>15</session-timeout>
</session-config>
JSP
什么是JSP

Java Server Pages : Java服务器端页面,也和Servlet一样,用于动态Web技术!
最大的特点:

  • 写JSP就像在写HTML
  • 和HTML的区别:
    1.HTML只给用户提供静态的数据
    2.JSP页面中可以嵌入JAVA代码,为用户提供动态数据
JSP原理

JSP怎么运行的

  • 服务器内部工作
    在这里插入图片描述
    在tomacat文件夹中有一个work目录
    IDEA中使用Tomcat的会在IDEA的tomcat中生产一个work目录
    我电脑的地址:
C:\Users\DELL\.IntelliJIdea2018.2\system\tomcat\Unnamed_maven-01\work\Catalina\localhost\ROOT\org\apache\jsp

运行的JSP页面会转化成java文件
在这里插入图片描述
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!

JSP 本质上就是一个Servlet
//初始化
  public void _jspInit() {
      
  }
//销毁
  public void _jspDestroy() {
  }
//JSPService
  public void _jspService(.HttpServletRequest request,HttpServletResponse response){
  }

1.判断请求
2.内置一些对象

final javax.servlet.jsp.PageContext pageContext;  //页面上下文
javax.servlet.http.HttpSession session = null;    //session
final javax.servlet.ServletContext application;   //applicationContext
final javax.servlet.ServletConfig config;         //config
javax.servlet.jsp.JspWriter out = null;           //out
final java.lang.Object page = this;               //page:当前
HttpServletRequest request                        //请求
HttpServletResponse response                      //响应

3.输出页面前增加的代码

response.setContentType("text/html");       //设置响应的页面类型
pageContext = _jspxFactory.getPageContext(this, request, response,
                                          null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;

4.以上的这些个对象我们可以在JSP页面中直接使用!

在这里插入图片描述
在JSP页面中;
只要是 JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为:out.write("\r\n");
这样的格式,输出到前端!

JSP基础语法

1.JSP表达式

 <%--JSP表达式
  作用:用来将程序的输出,输出到客户端
  <%= 变量或者表达式%>
  --%>

  <%= new java.util.Date()%>

2.JSP脚本片段


  <%--jsp脚本片段--%>
  <%
    int sum = 0;
    for (int i = 1; i <=100 ; i++) {
      sum+=i;
    }
    out.println("<h1>Sum="+sum+"</h1>");
  %>

3.脚本片段的再实现

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    for (int i = 0; i < 5; i++) {
%>
    <p>大王叫我来巡山 <%=i%></p>   //<%=i%> --> JSP表达式
<%
    }
%>
</body>
</html>

4.JSP声明

<%!
    static {
      System.out.println("Loading Servlet!");
    }
    
    private int globalVar = 0;
    
    public void test(){
      System.out.println("进入了方法Test!");
    }
  %>

JSP声明:会被编译到JSP生成Java的类中!其他的,就会被生成到_jspService方法中!
在JSP,嵌入Java代码即可!
JSP的注释,不会在客户端显示,HTML的注释会在客户端显示!
5.JSP指令

<%@page args.... %>
<%@include file=""%>

<%--@include会将两个页面合二为一--%>

<%@include file="common/header.jsp"%>
<h1>网页主体</h1>

<%@include file="common/footer.jsp"%>

<hr>

<%--jSP标签
    jsp:include:拼接页面,本质还是三个
    --%>
<jsp:include page="/common/header.jsp"/>
<h1>网页主体</h1>
<jsp:include page="/common/footer.jsp"/>
九大内置对象
  • PageContext ----存东西
  • Request ----存东西
  • Response
  • Session ----存东西
  • Application 【SerlvetContext】 ----存东西
  • config 【SerlvetConfig】
  • out 【PrintWriter】
  • page
  • exception
pageContext.setAttribute("name1","长江一号"); //保存的数据只在一个页面中有效
request.setAttribute("name2","长江二号"); //保存的数据只在一次请求中有效,请求转发会携带这个数据
session.setAttribute("name3","长江三号"); //保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","长江四号");  //保存的数据只在服务器中有效,从打开服务器到关闭服务器

request:客户端向服务器发送请求,产生的数据,用户看完就没用了,比如:新闻,用户看完没用的!session:客户端向服务器发送请求,产生的数据,用户用完一会还有用,比如:购物车;
application:客户端向服务器发送请求,产生的数据,一个用户用完了,其他用户还可能使用,比如:聊天数据;

JSP标签、JSTL标签、EL表达式

1.JSTL标签的依赖

<!-- JSTL表达式的依赖 -->
<dependency>
    <groupId>javax.servlet.jsp.jstl</groupId>
    <artifactId>jstl-api</artifactId>
    <version>1.2</version>
</dependency>
<!-- standard标签库 -->
<dependency>
    <groupId>taglibs</groupId>
    <artifactId>standard</artifactId>
    <version>1.1.2</version>
</dependency>

2.EL表达式: ${ }

  • 获取数据
  • 执行运算
  • 获取web开发的常用对象
<%@ page import="java.util.Random" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java"%>
<html>
<head>
    <title>
        Title
    </title>
</head>
<body>
    <%
        pageContext.setAttribute("brand1","Sony");
        request.setAttribute("brand2","Anta");
        session.setAttribute("brand3","Asics");
        application.setAttribute("brand4","Bose");
    %>
    <%
        String brand1 =(String) pageContext.findAttribute("brand1");
        String brand2 =(String) pageContext.findAttribute("brand2");
        String brand3 =(String) pageContext.findAttribute("brand3");
        String brand4 =(String) pageContext.findAttribute("brand4");
        String brand5 =(String) pageContext.findAttribute("brand5");
    %>
    <%--这块用到了EL表达式--%>
    <h1>取出的值为:</h1>
    <h4>${brand1}</h4>
    <h4>${brand2}</h4>
    <h4>${brand3}</h4>
    <h4>${brand4}</h4>
    <h4>${brand5}</h4>
</body>
</html>

3.JSP标签

<jsp:forward page="/jsptag2.jsp">
    <jsp:param name="name" value="kuangshen"></jsp:param>
    <jsp:param name="age" value="12"></jsp:param>
</jsp:forward>

4.JSTL表达式
JSTL标签库的使用就是为了弥补HTML标签的不足;它自定义许多标签,可以供我们使用,标签的功能和Java代码一样!

格式化标签

SQL标签

XML标签

核心标签
在这里插入图片描述
JSTL标签库使用步骤:

  • 引入对应的 taglib
  • 使用其中的方法
  • 在Tomcat 也需要引入 jstl的包,否则会报错:JSTL解析错误
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <c:set var="score" value="89"/>
    <c:choose>
        <c:when test="${score>=90}">
            学习认真,成绩优秀
        </c:when>
        <c:when test="${score>=80}">
            学习较好,成绩一般
        </c:when>
        <c:when test="${score>=60}">
            学校一般,成绩普通
        </c:when>
        <c:when test="${score<60}">
            不好好学习,不及格
        </c:when>
    </c:choose>
</body>
</html>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值