JavaWeb之JSP

作者: Ping开源 | 来源:发表于2021-02-24 18:57 被阅读0次

    八、JSP

    目录:什么是JSP、JSP原理、JSP基础语法、JSP指令、9大内置对象、JSP标签 JSTL标签 EL表达式

    1.什么是JSP

    Java Server Pages:Java服务器端页面,也和Servlet一样,用于动态Web技术。
    最大的特点:写JSP就像在写HTML。
    区别:①HTML只给用户提供静态的数据。
    ②JSP页面中可以嵌入Java代码,为用户提供动态数据。

    2.JSP原理

    思考:JSP到底怎么执行的?
    代码层面没有任何问题。
    服务器内部工作:Tomcat中有一个work目录,IDEA中使用Tomcat的会在IDEA的Tomcat中产生一个work目录。
    浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet。
    JSP最终也会被转换成为一个Java类。
    JSP本质上就是一个Servlet。

    //初始化
    public void _jspInit() {
    }
    //销毁
    public void _jspDestroy() {
    }
    //JSPService
    public void _jspService(final javax.servlet.http.HttpServletRequest request,final javax.servlet.httpHttpServletResponse response) throws java.io.IOException,javax.servlet.ServletException
    

    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;
    

    以上的这些对象可以在JSP页面中直接使用。


    JSP原理

    在JSP页面中,只要是Java代码就会原封不动地输出。如果是HTML代码就会被转换为out write(" ");这样地格式,输出到前端。

    3.JSP基础语法

    编写JSP前pom.xml的配置,放在<dependencies>中。

    <dependencies>
      <!--Servlet依赖-->
      <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>javax.servlet-api</artifactId>
        <version>4.0.1</version>
      </dependency>
      <!--JSP依赖-->
      <dependency>
        <groupId>javax.servlet.jsp</groupId>
        <artifactId>jsp-api</artifactId>
        <version>2.2.1-b01</version>
      </dependency>
      <!--JSTL表达式的依赖-->
      <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
      <dependency>
        <groupId>javax.servlet.jsp.jstl</groupId>
        <artifactId>jstl-api</artifactId>
        <version>1.2</version>
      </dependency>
      <!--standard标签库-->
      <!-- https://mvnrepository.com/artifact/taglibs/standard -->
      <dependency>
        <groupId>taglibs</groupId>
        <artifactId>standard</artifactId>
        <version>1.1.2</version>
      </dependency>
    </dependencies>
    

    任何语言都有自己的语言,Java中也有。JSP作为Java技术的一种应用,它拥有一些自己的扩充的语法,Java所有语法都支持。
    1)JSP表达式
    语法:<%= %>

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

    作用:用来将程序输出到客户端。
    2)JSP脚本片段

    <%
      int sum = 0;
      for (int i = 1; i <=100 ; i++) {
        sum+=i;
      }
      out.println("<h1>sum="+sum+"</h1>");
    %>
    

    脚本片段再实现

    <%
      int x = 10;
      out.println(x);
    %>
    <p>这是一个JSP文档</p>
    <%
      int y = 20;
      out.println(y);
    %>
    <hr>
    <%--在代码嵌入HTML元素--%>
    <%
      for (int i = 0; i < 5; i++) {
    %>
    <h1>Hello World</h1>
    <%
      }
    %>
    

    3)JSP声明

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

    会被编译到JSP生成Java的类中,其它的就会被生成到_jspService方法中。
    在JSP中,嵌入Java代码即可。
    JSP的注释不会在客户端显示,HTML就会。
    总结:①<% %>:片段
    ②<%= %>:表达式输出一个值
    ③<%! %>:定义全局的方法
    ④<%-- --%>:注释

    4.JSP指令

    1)page
    语法

    <%@ page args…%>
    

    以定制错误页面为例
    ①在错误页面中编写如下代码,但一般不会用。

    <%--显示的声明这是一个错误页面--%>
    <%@ page isErrorPage="true" %>
    

    ②在页面中引入错误页面。

    <%@ page errorPage="error/error.jsp" %>
    

    ③在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>
    

    注意:修改了xml就必须重启Tomcat。
    2)include
    语法

    <%@include file=" "%>
    

    一般用来提取公共页面。

    <%@include file="common/header.jsp" %>
    <%--JSP标签--%>
    <jsp:include page="/common/header.jsp" />
    

    注意:page指当前Web下的页面,需要加上Web路径。
    区别:@include会将两个页面合二为一,而jsp:include是拼接页面,本质还是两个。
    注意:@include中的两个页面均不能使用相同的变量名。

    5.9大内置对象

    • PageContext 存东西
    • Request 存东西
    • Response
    • Session 存东西
    • Application 【SerlvetContext】 存东西
    • Config 【SerlvetConfig】
    • Out
    • Page
    • Exception
    <%
      pageContext.setAttribute("name1","Ping1");//保存的数据只在一个页面中有效
      request.setAttribute("name2","Ping2");//保存的数据只在一次请求中有效,请求转发会携带这个数据
      session.setAttribute("name3","Ping3");//保存的数据只在一次会话中有效,从打开浏览器到关闭浏览器
      application.setAttribute("name4","Ping4");//保存的数据只在服务器中有效,从打开浏览器到关闭浏览器
    %>
    <%
      //从pageContext取出
      //从底层到高层(作用域):page——>request——>session——>application
      String name1 = (String) pageContext.findAttribute("name1");
      String name2 = (String) pageContext.findAttribute("name2");
      String name3 = (String) pageContext.findAttribute("name3");
      String name4 = (String) pageContext.findAttribute("name4");
      String name5 = (String) pageContext.findAttribute("name5");
    %>
    <%
      //使用EL表达式输出 ${ }
      <h1>取出的值为:</h1>
      <h3>${name1}</h3>
      <h3>${name2}</h3>
      <h3>${name3}</h3>
      <h3>${name4}</h3>
      <h3><%=name5%></h3>
      <h3>${name5}</h3>
    %>
    

    注意:当取值不存在时,${ }不输出,而<%= %>输出结果为null。
    双亲委派机制的工作过程
    ①类加载器收到类加载的请求。
    ②把这个请求委托给父加载器去完成,一直向上委托,直到启动类加载器。
    ③启动器加载器检查能不能加载(使用findClass()方法),能就加载(结束)。否则,抛出异常,通知子加载器进行加载。
    ④重复③。
    跳转页面的两种方式

    pageContext.forward("/index.jsp");
    request.getRequestDispatcher("/index.jsp").forward(request,response);
    

    总结:①request:客户端向服务器发送请求,产生的数据用户看完就没用了。
    ②session:客户端向服务器发送请求,产生的数据用户用完之后还有用。
    ③application:客户端向服务器发送请求,产生的数据一个用户用完后,其它用户还可以使用。

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

    使用JSTL需要导入的jar包

    <!--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>
    

    1)EL表达式 ${ }
    作用:①获取数据
    ②执行运算。
    ③获取Web开发的常用对象。
    2)JSP标签

    <%--jsp:include--%>
    <jsp:forward page="http://localhost:8080/jsptag.jsp?name=ping&age=20">
      <jsp:param name="name" value="kuangshen"></jsp:param>
      <jsp:param name="age" value="12"></jsp:param>
    </jsp:forward>
    

    使用?和&来拼接传递的数据。
    3)JSTL表达式
    JSTL标签库的使用就是为了弥补HTML标签的不足。它自定义许多标签可供使用,标签的功能和Java代码一样。
    ①格式化标签
    ②SQL标签
    ③XML标签
    ④核心标签(重点)

    重点核心标签

    JSTL标签库使用步骤
    Ⅰ引入对应的taglib。

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    

    Ⅱ使用其中的方法。
    Ⅲ在Tomcat 也需要引入jstl的包,否则会报错:JSTL解析错误。
    核心标签的例子
    Ⅰc:if

    <form action="coreif.jsp" method="get">
      <%--EL表达式获取表单中的数据 ${param.参数名}--%>
      <input type="text" name="username" value="${param.username}">
      <input type="submit" value="登录">
    </form>
    <%--判断如果提交的用户名是管理员,则登录成功--%>
    <c:if test="${param.username=='admin'}" var="isAdmin">
      <c:out value="管理员欢迎您!"/>
    </c:if>
    <%--自闭合标签--%>
    <c:out value="${isAdmin}"/>
    

    Ⅱc:choose c:when

    <%--定义一个变量score,值为85--%>
    <c:set var="score" value="85"/>
    <c:choose>
      <c:when test="${score>=90}">
        你的成绩为优秀
      </c:when>
      <c:when test="${score>=80}">
        你的成绩为良好
      </c:when>
      <c:when test="${score>=70}">
        你的成绩为中等
      </c:when>
      <c:when test="${score>=60}">
        你的成绩为及格
      </c:when>
      <c:when test="${score<60}">
        你的成绩为不及格
      </c:when>
    </c:choose>
    

    Ⅲc:forEach

    <%
        ArrayList<String> people = new ArrayList<>();
        people.add(0,"张三");
        people.add(1,"李四");
        people.add(2,"王五");
        people.add(3,"赵六");
        request.setAttribute("list",people);
    %>
    <%--var:每一次遍历出来的变量,items:要遍历的对象,begin: 起始位置,end:截止位置,step:步长--%>
    <c:forEach var="people" items="${list}" begin="1" end="3" step="1" >
      <c:out value="${people}"/>
    </c:forEach>
    

    相关文章

      网友评论

        本文标题:JavaWeb之JSP

        本文链接:https://www.haomeiwen.com/subject/dofczktx.html