当前位置: 首页 > news >正文

JSP简介

目录

JSP

JSP脚本片段

面试题:JSP和Servlet的区别

JSP表达式

JSP声明片段

JSP的指令标识

page指令中的属性:

includ指令:

JSP标签

1.内置标签

2.JSTL标签,需要导入JSTL标签库

3.自定义标签

使用JSP的小练习

在web.xml中设置的错误页面

EL表达式

EL表达式的内置作用域对象

EL表达式的缺陷:


JSP

JSP脚本片段

用于在JSP页面写java代码(可以当成一个类来写)

<%
    int num = 0;
    num++;
    //在控制台打印输出
    System.out.println(num);
    //向页面打印输出
    out.print(num);
%>

注意事项:

  • JSP脚本片段中只能出现java代码,不能出现HTML元素。在访问JSP时,JSP引擎会编译JSP页面中的脚本片段(可能会导致有些卡顿,若数据过多,会很卡)。

  • JSP脚本片段中的java代码必须严格遵守java的规则

  • 一个JSP页面是可以有多个脚本片段的

  • 多个脚本片段中的代码可以相互访问

淘汰原因

  • 必须有java环境

  • 必须有Tomcat环境

  • 需要解析编译,再渲染页面(会卡顿)

面试题:JSP和Servlet的区别

  • JSP本质上就是一个Servlet类

  • JSP更侧重与视图的展示,Servlet更侧重于逻辑处理

  • 先有的Servlet,后有的JSP

JSP表达式

<%= num %>

JSP声明片段

<%! 
    int x = 10;
    //声明静态代码块
    static{
        
    }
    //声明方法
    public void fun(){
        
    }
%>

JSP的指令标识

<%-- 导入包(自动导入,使用import) --%>
<%@ page import="java.util.List" %>
<%@ page import="java.util.ArrayList" %>
<%
    <%--需要导入包 --%>
    List list = new ArrayList();
%>
​
<%--
    JSP的指令标识
    <%@ 指令名 属性1="值1" 属性2="值2" ......%>
    page指令:定义整个JSP页面的相关属性
    include指令:引入其他的JSP页面,先把两个页面结合,再去编译成servlet
    taglib指令:引入页面上需要用到的标签库
--%>

page指令中的属性:

errorPage属性:错误页面

出现错误时会跳转到该页面,地址栏并不会改变

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/31
  Time: 10:45
  To change this template use File | Settings | File Templates.
--%>
<%-- errorPage:错误页面,出现错误时会跳转到该页面,地址栏并不会改变 --%>
<%@ page errorPage="error.jsp" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<%
    int i = 10 / 0;
%>
<h1>JSP02 Page!!!</h1>
</body>
</html>
​

isErrorPage属性:是否为错误页面

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/31
  Time: 10:51
  To change this template use File | Settings | File Templates.
--%>
<%-- isErrorPage:是否为错误页面,只有为是时才可以调用exception --%>
<%@ page isErrorPage="true" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <h1>Error Page!!!</h1>
    <%=
        <%-- 将错误打印在页面上 --%>
        exception.getMessage()
    %>
</body>
</html>

includ指令:

<%-- hello.jsp文件中的内容,其余略 --%>
<h1>hello Page!!!</h1>
​
<%-- jsp02.jsp文件 --%>
<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/31
  Time: 10:45
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@include file="hello.jsp"%>
<html>
<head>
    <title>Title</title>
</head>
<body>
<h1>JSP02 Page!!!</h1>
</body>
</html>
​
会打印出
hello Page!!!
JSP02 Page!!!

JSP标签

1.内置标签

  • jsp:include——引入指定的页面

<%-- hello.jsp文件中的内容,其余略 --%>
<h1>hello Page!!!</h1>
​
<%-- jsp03.jsp文件中的内容,其余略 --%>
<h1>JSP03 Page!!!</h1>
<jsp:include page="hello.jsp"></jsp:include>
输出;
hello Page!!!
JSP02 Page!!!
  • jsp:forward:转发页面

当访问该页面时转发到其余页面,地址栏不会改变

<jsp:forward page="hello.jsp"></jsp:forward>
  • jsp:param:传参数

可与forward标签配合使用,转发的同时传递一些参数

<jsp:forward page="hello.jsp">
    <%-- 可以使用request.getAttribute() --%>
    <jsp:param name="num1" value="10"/>
</jsp:forward>

面试题:jsp:include标签和include指令的区别

include标签:先把要引入的页面编译,再合并

include指令:先把要引入的页面合并,再编译

2.JSTL标签,需要导入JSTL标签库

3.自定义标签

使用JSP的小练习

import com.jsoft.entity.Student;
​
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
​
@WebServlet(name = "LoginJspServlet", value = "/loginjsp.do")
public class LoginJspServlet extends HttpServlet {
​
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
​
        String username = request.getParameter("username");
        String password = request.getParameter("password");
​
        PrintWriter out = response.getWriter();
​
        List<Student> students = new ArrayList<>(5);
        students.add(new Student(1001,"aaa",25,"Man"));
        students.add(new Student(1002,"bbb",26,"Man"));
        students.add(new Student(1003,"ccc",28,"Man"));
        students.add(new Student(1004,"ddd",27,"Man"));
        students.add(new Student(1005,"eee",24,"Man"));
​
        if(Objects.equals(username,"admin") && Objects.equals(password,"123456")){
            // 将集合传入
            request.setAttribute("students",students);
            request.getRequestDispatcher("jsp/welcome.jsp").forward(request,response);
        }else {
            out.write("username or password wrong");
        }
    }
}
​
<%@ page import="com.jsoft.entity.Student" %>
<%@ page import="java.util.List" %><%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/31
  Time: 13:37
  To change this template use File | Settings | File Templates.
--%>
<%@ page pageEncoding="utf-8" contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
welcome:<%= request.getAttribute("username")%>
<%
    // 使用request.getAttribute("students")获取students集合
    List<Student> students = (List<Student>) request.getAttribute("students");
    // 遍历集合并显示在页面上,table表格展示
    // 1.在JSP脚本片段中只能写java   2.在body中只能写html
%>
<table border="1" cellpadding="10" cellspacing="0">
    <tr>
        <th>ID</th>
        <th>NAME</th>
        <th>AGE</th>
        <th>GENDER</th>
    </tr>
    <%
        // 遍历students集合,并将信息输入到表格之中
        for (Student student : students) {
    %>
​
        <tr>
            <td><%= student.getId()%></td>
            <td><%= student.getName()%></td>
            <td><%= student.getAge()%></td>
            <td><%= student.getGender()%></td>
        </tr>
    <%
        }
    %>
​
</table>
</body>
</html>
 
/*
    对象          类
    pageContext--PageContext
    request------HttpServletRequest
    session------HttpSession
    application--ServletContext
*/
<% 
    pageContext.setAttribute("pageContext","pageContext");
    request.setAttribute("request","request");
    session.setAttribute("session","session");
    application.setAttribute("application","application");
%>
<%-- 获取值 --%>
pageContext:<%= pageContext.getAttribute("pageContext")%>
request:<%= request.getAttribute("request")%>
session:<%= session.getAttribute("session")%>
application:<%= application.getAttribute("application")%>

在web.xml中设置的错误页面

不论哪里出了该类型的错误,都会跳转到该页面

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">

    <!-- 页面中所有出现404错误的都会跳转到404.html中 -->
    <error-page>
        <error-code>404</error-code>
        <location>/404.html</location>
    </error-page>
    
    <!-- 页面中所有出现空指针错误的都会跳转到npe.html中 -->
    <error-page>
        <exception-type>java.lang.NullPointerException</exception-type>
        <location>/npe.html</location>
    </error-page>
</web-app>

EL表达式

EL表达式的内置作用域对象

EL表达式的内置作用域对象(由小到大)

  1. pageContext

  2. requestScope

  3. sessionScope

  4. applicationScope

   <%
        request.setAttribute("name","zhangsan");
        session.setAttribute("name","lisi");
        pageContext.setAttribute("age",30);
    %>
​
<%-- ${sessionScope.name}可获取属性为name的值,还可处理null,若为空,则文本框中不会显示 --%>
<input type="text" value="${sessionScope.name}">
​
<%-- 若为表明是哪一个内置对象的属性,则会先从范围小的内置对象找起 --%>
<%-- 输出zhangsan --%>
${name}

EL表达式的缺陷:

  1. 只能读,不能写

  2. 不支持流程控制语句

<%--
  Created by IntelliJ IDEA.
  User: Administrator
  Date: 2022/8/31
  Time: 16:01
  To change this template use File | Settings | File Templates.
--%>
<%@ 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 scope="session" var="name" value="zhangsan"></c:set>
    <c:set scope="session" var="age" value="20"></c:set>
    
    <%--  取出session中的name的值  --%>
    ${sessionScope.name}
​
    <hr>
    <%-- 判断 --%>
    <c:if test="${sessionScope.age >= 18}">可以观看!</c:if>
    <c:if test="${sessionScope.age < 18}">禁止观看!</c:if>
​
    <hr>
    <%-- 类似于switch...case --%>
    <c:choose>
        <c:when test="${sessionScope.age eq 18}">
            你已经年满18岁,可以签署劳动合同了!
        </c:when>
        <c:when test="${sessionScope.age lt 18}">
            你好没有满18岁!
        </c:when>
        <c:otherwise>
            你已经是大人了!!!
        </c:otherwise>
    </c:choose>
    <hr>
    
    <%-- begin="1"从多少开始 end="10"到哪里结束 step="2"一次增加多少 var="i"变量名 varStatus="stat"变量的状态,一般情况均为索引(index) --%>
    
    <c:forEach begin="1" end="10" step="2" var="i" varStatus="stat">
        <%-- 判断是否为第一个,值为true和false --%>
        ${i} ----- ${stat.first} <br>
    </c:forEach>
</body>
</html>

相关文章:

  • 湖仓一体电商项目(八):业务实现之编写写入ODS层业务代码
  • 基于深度学习的多人步态识别系统(YOLOV5+DeepSort+GaitSet+Segmentation)
  • 计算机网络——组成、分类、性能指标、分层结构
  • 【小程序】组件化开发的基本使用(二)
  • 【IVI】15.1.6 系统稳定性优化篇(LMKD 六)Vmpressure监视器初始化及其工作原理
  • 分享程序员面试的7个技巧
  • 市政管理学考试复习资料
  • c语言数据结构 二叉树(三)
  • 汉明码原理
  • 黑马瑞吉外卖之菜品信息的修改
  • 【Vue 基础知识】v-for的使用和注意事项
  • LeetCode Cookbook 数组习题(8)
  • Java新手小白入门篇 SpringBoot项目的构建
  • 第十一届中国创新创业大赛浙江赛区暨第九届浙江省“火炬杯”创新创业大赛-新一代信息技术行业总决赛
  • kuangbin专题六 最小生成树(2022.9.3)
  • $translatePartialLoader加载失败及解决方式
  • ➹使用webpack配置多页面应用(MPA)
  • fetch 从初识到应用
  • JavaScript实现分页效果
  • Linux学习笔记6-使用fdisk进行磁盘管理
  • macOS 中 shell 创建文件夹及文件并 VS Code 打开
  • miaov-React 最佳入门
  • python3 使用 asyncio 代替线程
  • spring boot下thymeleaf全局静态变量配置
  • 基于Vue2全家桶的移动端AppDEMO实现
  • 记一次和乔布斯合作最难忘的经历
  • 离散点最小(凸)包围边界查找
  • 深入浅出Node.js
  • 实习面试笔记
  • 手写双向链表LinkedList的几个常用功能
  • 腾讯视频格式如何转换成mp4 将下载的qlv文件转换成mp4的方法
  • python最赚钱的4个方向,你最心动的是哪个?
  • 阿里云重庆大学大数据训练营落地分享
  • 回归生活:清理微信公众号
  • ​ 轻量应用服务器:亚马逊云科技打造全球领先的云计算解决方案
  • ​Distil-Whisper:比Whisper快6倍,体积小50%的语音识别模型
  • ​Java并发新构件之Exchanger
  • $GOPATH/go.mod exists but should not goland
  • (6)设计一个TimeMap
  • (C++)八皇后问题
  • (ctrl.obj) : error LNK2038: 检测到“RuntimeLibrary”的不匹配项: 值“MDd_DynamicDebug”不匹配值“
  • (react踩过的坑)Antd Select(设置了labelInValue)在FormItem中initialValue的问题
  • (SpringBoot)第二章:Spring创建和使用
  • (第一天)包装对象、作用域、创建对象
  • (二)fiber的基本认识
  • (二)windows配置JDK环境
  • (附程序)AD采集中的10种经典软件滤波程序优缺点分析
  • (附源码)python旅游推荐系统 毕业设计 250623
  • (更新)A股上市公司华证ESG评级得分稳健性校验ESG得分年均值中位数(2009-2023年.12)
  • (论文阅读22/100)Learning a Deep Compact Image Representation for Visual Tracking
  • (五)IO流之ByteArrayInput/OutputStream
  • (一) storm的集群安装与配置
  • (一)搭建springboot+vue前后端分离项目--前端vue搭建
  • (转)甲方乙方——赵民谈找工作
  • ***检测工具之RKHunter AIDE