JSP

JSP

1. 定义
JSP全称Java Server Pages,是一种动态网页开发技术。它使用JSP标签在HTML网页中插入Java代码。标签通常以<%开头以%>结束。

JSP是一种Java servlet,主要用于实现Java web应用程序的用户界面部分。网页开发者们通过结合HTML代码、XHTML代码、XML元素以及嵌入JSP操作和命令来编写JSP。

服务器调用的是已经编译好的JSP文件,而不像CGI/Perl那样必须先载入解释器和目标脚本。

2. 原理

源码继承的servlet,所以本质还是servlet

先在pom.xml中导入org.apache.tomcat包

        <dependency>
            <groupId>org.apache.tomcat</groupId>
            <artifactId>tomcat-jasper</artifactId>
            <version>9.0.12</version>
        </dependency>

任意一个java文件输入HttpJSPBase按住ctrl+鼠标左键

,直接找不到定义的那些玩意直接偷图了

  • 内置的一些对象

  • 输出前的代码

3. 语法
<%%>	//代码片段
<%=%>	//表达式
<%!%>	//jsp声明
获取当前时间
<%--获取当前时间--%>
<%=new Date().toLocaleString()%>
4. 自定义500/404页面

404.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

<html>
<head>
    <title>404</title>
</head>
<body>
<img src="${pageContext.request.contextPath}/image/404.png" alt="404">
</body>
</html>
  • 500.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>500</title>
</head>
<body>
<img src="${pageContext.request.contextPath}/image/500.png" alt="500">
</body>
</html>

俩种配置方式

  1. 直接在jsp文件下配置
<%@ page errorPage="/error/500.jsp" %>

上面的没运行出来

  1. 在web.xml下配置
    <error-page>
        <error-code>404</error-code>
        <location>/error/404.jsp</location>
    </error-page>
    <error-page>
        <error-code>500</error-code>
        <location>/error/500.jsp</location>
    </error-page>
5. 自定义头/尾部
  • 将两个页面合为一个
  <%@ include file="common/head.jsp"%>
  <h2>原生内容</h2>
  <%@ include file="common/footer.jsp"%>
  • 拼接页面
  <jsp:include page="common/head.jsp"/>
  <h2>原生内容</h2>
  <jsp:include page="common/footer.jsp"/>
posted on 2023-01-09 23:49  lsyorha  阅读(30)  评论(0编辑  收藏  举报