一、概述

1、概念

  • JSP :Java Server Pages 即:Java服务器端页面
  • 一个特殊的页面,其中既可以指定定义html标签,又可以定义java代码
  • 用于简化书写

2、原理

  • JSP本质上就是一个Servlet

在这里插入图片描述
3、JSP的执行过程

  • 翻译 : .jsp翻译成java文件(servlet)
  • 编译 : .java文件编译成.class
  • 运行 :执行.class的service方法

4、使用JSP定义Java代码的方式(JSP的脚本)

  1. <% 代码 %>:定义的java代码,在service方法中。service方法中可以定义什么,该脚本中就可以定义什么。
  2. <%! 代码 %>:定义的java代码,在jsp转换后的java类的成员位置。
  3. <%= 代码 %>:定义的java代码,会输出到页面上。输出语句中可以定义什么,该脚本中就可以定义什么。

5、注释

  1. html注释:
    <!-- -->:只能注释html代码片段
  2. jsp注释:推荐使用
    <%-- --%>:可以注释所有

二、JSP指令

1、作用
  • 用于配置JSP页面,导入资源文件
2、格式
  • <%@ 指令名称 属性名1=属性值1 属性名2=属性值2 ... %>
3、分类

3-1. page :配置JSP页面的

  • contentType:等同于response.setContentType()
    1. 设置响应体的mime类型以及字符集
    2. 设置当前jsp页面的编码(只能是高级的IDE才能生效,如果使用低级工具,则需要设置pageEncoding属性设置当前页面的字符集)
  • import:导包
  • errorPage:当前页面发生异常后,会自动跳转到指定的错误页面
  • isErrorPage:标识当前也是是否是错误页面。
    • true:是,可以使用内置对象exception
    • false:否。默认值。不可以使用内置对象exception

定义一个错误页面 errorpage.jsp

<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" errorPage="500.jsp" %><%--当页面异常后,跳转到500.jsp--%>
<html>
<head>
    <title>错误页面</title>
</head>
<body>
<%
    Date d = null;
    d.getTime();
%>
</body>
</html>

再定义一个错误跳转页面 500.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %><%--标识当前为错误页面--%>
<html>
<head>
    <title>服务器内部错误</title>
</head>
<body>
<%
    String msg = exception.getMessage();
%>
<%=msg%>
</body>
</html>

3-2. include : 页面包含的。导入页面的资源文件

  • <%@include file="top.jsp"%>

新建home.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%@include file="top.jsp"%><!--导入页面的资源文件-->
<hr>
<%--aaa--%>
<!--html注释-->
这是home.jsp
</body>
</html>

建top.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
这是top.jsp <br>
是导入页面的资源文件
</body>
</html>

浏览器查看
在这里插入图片描述
3-3. taglib : 导入资源

  • <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>其中prefix:前缀,自定义的

三、JSP的内置对象

1、在jsp页面中不需要获取和创建,可以直接使用的对象
2、jsp一共有9个内置对象。
在这里插入图片描述
新建 jsp-object.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <%
        pageContext.setAttribute("pageKey", "hello page..."); //page
        request.setAttribute("requestKey", "hello request..."); //HttpSerfvletREquest
        session.setAttribute("sessionKey", "hello session..."); //HttpSesion
        application.setAttribute("applicationKey", "hello application..."); //ServletContext
    %>

    <%=pageContext.getAttribute("pageKey")%><br>
    <%=request.getAttribute("requestKey")%><br>
    <%=session.getAttribute("sessionKey")%><br>
    <%=application.getAttribute("applicationKey")%><br>
</body>
</html>

浏览器访问
在这里插入图片描述
3、常用的3个:

  • request
  • response
  • out:字符输出流对象。可以将数据输出到页面上。和response.getWriter()类似

4、response.getWriter()和out.write()的区别:

  • 在tomcat服务器真正给客户端做出响应之前,会先找response缓冲区数据,再找out缓冲区数据。
  • response.getWriter()数据输出永远在out.write()之前

四、案例——记住上次访问的时间

分析
在服务器中的Servlet判断是否有一个名为lastTime的cookie

  1. 有:不是第一次访问
    1. 响应数据:欢迎回来,您上次访问时间为:2018年6月10日11:50:20
    2. 写回Cookie:lastTime=2018年6月10日11:50:01
  2. 没有:是第一次访问
    1. 响应数据:您好,欢迎您首次访问
    2. 写回Cookie:lastTime=2018年6月10日11:50:01

新建ServletCookieTest.java

package cn.lemon.cookie;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;

@WebServlet("/servletCookieTest")
public class ServletCookieTest extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置响应的消息体的数据格式以及编码
        response.setContentType("text/html;charset=utf-8");

        //1.获取所有Cookie
        Cookie[] cookies = request.getCookies();
        boolean flag = false;//没有cookie为lastTime
        //2.遍历cookie数组
        if (cookies != null && cookies.length > 0) {
            for (Cookie cookie : cookies) {
                //3.获取cookie的名称
                String name = cookie.getName();
                //4.判断名称是否是:lastTime
                if ("lastTime".equals(name)) {
                    //有该Cookie,不是第一次访问
                    flag = true;//有lastTime的cookie

                    //设置Cookie的value
                    //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                    Date date = new Date();
                    SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                    String str_date = sdf.format(date);
                    System.out.println("编码前:" + str_date);
                    //URL编码
                    str_date = URLEncoder.encode(str_date, "utf-8");
                    System.out.println("编码后:" + str_date);
                    cookie.setValue(str_date);
                    //设置cookie的存活时间
                    cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
                    response.addCookie(cookie);

                    //响应数据
                    //获取Cookie的value,时间
                    String value = cookie.getValue();
                    System.out.println("解码前:" + value);
                    //URL解码:
                    value = URLDecoder.decode(value, "utf-8");
                    System.out.println("解码后:" + value);
                    response.getWriter().write("<h1>欢迎回来,您上次访问时间为:" + value + "</h1>");
                    break;
                }
            }
        }

        if (cookies == null || cookies.length == 0 || flag == false) {
            //没有,第一次访问

            //设置Cookie的value
            //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
            String str_date = sdf.format(date);
            System.out.println("编码前:" + str_date);
            //URL编码
            str_date = URLEncoder.encode(str_date, "utf-8");
            System.out.println("编码后:" + str_date);

            Cookie cookie = new Cookie("lastTime", str_date);
            //设置cookie的存活时间
            cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
            response.addCookie(cookie);
            response.getWriter().write("<h1>您好,欢迎您首次访问</h1>");
        }
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}

上面的代码是用 Servlet 写的,如果使用小脚本来写的话
新建 login.jsp

<%@ page import="java.util.Date" %>
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.net.URLEncoder" %>
<%@ page import="java.net.URLDecoder" %><%--
  Created by IntelliJ IDEA.
  User: Lemon
  Date: 2019/8/12
  Time: 16:59
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>记录访问时间</title>
</head>
<body>
<%
    //1.获取所有Cookie
    Cookie[] cookies = request.getCookies();
    boolean flag = false;//没有cookie为lastTime
    //2.遍历cookie数组
    if (cookies != null && cookies.length > 0) {
        for (Cookie cookie : cookies) {
            //3.获取cookie的名称
            String name = cookie.getName();
            //4.判断名称是否是:lastTime
            if ("lastTime".equals(name)) {
                //有该Cookie,不是第一次访问
                flag = true;//有lastTime的cookie

                //设置Cookie的value
                //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
                Date date = new Date();
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                String str_date = sdf.format(date);
                System.out.println("编码前:" + str_date);
                //URL编码
                str_date = URLEncoder.encode(str_date, "utf-8");
                System.out.println("编码后:" + str_date);
                cookie.setValue(str_date);
                //设置cookie的存活时间
                cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
                response.addCookie(cookie);

                //响应数据
                //获取Cookie的value,时间
                String value = cookie.getValue();
                System.out.println("解码前:" + value);
                //URL解码:
                value = URLDecoder.decode(value, "utf-8");
                System.out.println("解码后:" + value);
%>
<h1>
    欢迎回来,您上次访问时间为: <%= value%>
</h1>
<%
                break;
            }
        }
    }

    if (cookies == null || cookies.length == 0 || flag == false) {
        //没有,第一次访问

        //设置Cookie的value
        //获取当前时间的字符串,重新设置Cookie的值,重新发送cookie
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
        String str_date = sdf.format(date);
        System.out.println("编码前:" + str_date);
        //URL编码
        str_date = URLEncoder.encode(str_date, "utf-8");
        System.out.println("编码后:" + str_date);

        Cookie cookie = new Cookie("lastTime", str_date);
        //设置cookie的存活时间
        cookie.setMaxAge(60 * 60 * 24 * 30);//一个月
        response.addCookie(cookie);
%>
<h1>
    您好,欢迎您首次访问
</h1>
<%
    }
%>
</body>
</html>
Logo

CSDN联合极客时间,共同打造面向开发者的精品内容学习社区,助力成长!

更多推荐