JSP object parsing

content

Nine built-in objects of jsp

jsp four domain objects

The difference between out output in jsp and response.getWriter output

out.print()和out.write() 

jsp common tags

static include

dynamic inclusion

Features of Dynamic Inclusion:

request forwarding

jsp practice

Exercise 1

print the nine-nine multiplication table

Exercise 2 

 Store student information and print

Request forwarding instructions

 Listener listener

ServletContextListenter listener

Steps for the ServletContextListener listener to listen to the ServletContext object


Nine built-in objects of jsp

The nine built-in objects of jsp refer to the nine objects provided internally by Tomcat after translating the jsp page into the Servlet source code, which are called built-in objects.

request                  request object

response                 response object

Context object for pageContext          jsp

session                  session object

application              ServletContext object

config                     ServletConfig object

exception                 exception object

out                          jsp output stream object

jsp four domain objects

 Domain objects are objects that can access data in the same way as Maps. The functions of the four domain objects are the same, but their access scope to the data is different

The four domain objects are:

domain object class access range
pageContext (Class PageContextImpl) Valid within the scope of the current jsp page
request (HttpServletRequest类) valid within one request
session (HttpSession类) Valid within a session (opens the browser to access the server until the browser is closed)
application (ServletContext class) Valid within the scope of the entire web project (as long as the web project does not stop, the data is there)

//Save data to each of the four fields

<%

        pageContext.setAttribute("key","pageContext");

        request.setAttribute("key","request");

        session.setAttribute("key","session");

        application.setAttribute("key","application");

%>

Whether the pageContext field has a value: <%=pageContext.getAttribute("key")%> <br>

Whether the request field has a value: <%=pageContext.getAttribute("key")%> <br>

Whether the session field has a value: <%=session.getAttribute("key")%> <br>

Whether the application field has a value: <%=application.getAttribute("key")%> <br>

 Create another jsp page:

 Other range tests:

 Their range is from small to large. When using, generally use the small range first, and then use the small range if the small range is not enough. (for memory optimization reasons)

Small: pageContext
request
session
large: application

The difference between out output in jsp and response.getWriter output

 We can find that no matter who outputs the result first, it is the first of the response.

Graphical analysis:

What will be done when all the code  in the jsp page is executed:

1. Execute the out.flush() operation, which will append the data of the out buffer to the end of the response buffer.

2. The refresh operation of the response will be performed, and the data will be written to the client.

verify: 

 Since the underlying source code uses out for output after jsp translation, in general, we use out for output in jsp pages. Avoid disrupting the order of page output.

out.print()和out.write() 

out.write() output string string no problem

out.print() can output any data (will be converted into a string and then call write output)

Conclusion: In jsp pages, you can use out.print() uniformly to output

jsp common tags

static include

Create an include directory under the web, and write main.jsp and footer.jsp in it

under footer.jsp

<html>
<head>

    <meta charset="utf-8"/>
    <title>Insert title here</title>
</head>
<body>
页脚信息

</body>
</html>

 under main.jsp

</head>
<body>
首页<br>
主体<br>
<%--
    include file="" 就是静态包含
    file属性指定你要包含的页面路径
    地址中的第一个斜杆 /   表示http://ip:port/工程路径/ 映射到idea为web
--%>
    <%@include file="/include/footer.jsp" %>
</body>
</html>

include file=" " is a static include

The file attribute specifies the path to the page you want to include

The first slash / in the address represents http://ip:port/project path/, which is mapped to the web directory in idea

  Modify footer.jsp content

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

<html>
<head>

    <meta charset="utf-8"/>
    <title>Insert title here</title>
</head>
<body>
页脚信息
修改后,主页显示
</body>
</html>

dynamic inclusion

Format:

<jsp:include page="/include/footer.jsp"></jsp:include>

Dynamic includes can also be the same as static includes

Features of Dynamic Inclusion:

1. Dynamic inclusion will also translate the included jsp pages into java code

2. Dynamically include the underlying code Use the following code to call the included jsp page to execute the output.

JspRuntimeLibrary.include(request,response,"/include/footer.jsp",out,false);

request forwarding

Format:

<jsp:forward page=" "></jsp:forward>
<!--page属性设置请求转发的路径-->

jsp practice

Exercise 1

print the nine-nine multiplication table

<html>
<head>
</head>
<body >

<h1 >九九乘法表</h1>

   <%
    for(int i=1;i<10;i++){
        for(int j=1;j<=i;j++){
    %>

        <%=j+"*"+i+"="+(i*j)%>

      <%
       }
        %>

    <br/>

   <%
    }
   %>

</body>
</html>

Exercise 2 

 Store student information and print

The student class under the pojo package

package pojo;

public class Student {
private String name;
private int  id;
private int age;

    public Student(String name, int id, int age) {
        this.name = name;
        this.id = id;
        this.age = age;
    }

    public Student() {
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" +
                "name='" + name + '\'' +
                ", id=" + id +
                ", age=" + age +
                '}';
    }
}

under text1.jsp

<%@ page import="java.util.List" %>
<%@ page import="pojo.Student" %>
<%@ page import="java.util.ArrayList" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>

<html>
<head>
   
    <meta charset="utf-8"/>
    <title>Insert title here</title>
<%--    设置样式<style></style>--%>
    <style>
        table{
            border: 1px black solid;
            width: 300px;
        }
        td,tr{
            border: 1px black solid;
            width: 300px;
        }
    </style>
</head>
<body>
<%
    List<Student> list=new ArrayList<>();
    for (int i=1;i<=10;i++){
      list.add(new Student("name"+i,i,10+i));
    }
%>
<table>
<%for (Student student:list){%>
<%--    tr是一行,td为一列--%>
<tr>
    <td><%=student.getName()%></td>
    <td><%=student.getId()%></td>
    <td><%=student.getAge()%></td>
</tr>

  <% } %>
</table>
</body>
</html>

Request forwarding instructions

flow chart:

 SearchStudentServlet类下

package com.Servlet;

import pojo.Student;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class SearchStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求参数
        //发sql语句查询学生信息
        //使用for循环生成查询到的数据做模拟
        List<Student> list=new ArrayList<>();
        for (int i=1;i<=10;i++){
            list.add(new Student("name"+i,i,10+i));
        }
        //保存查询到的数据到Request域中
        req.setAttribute("stuList", list);
        //请求转发到之外的showStudent.jsp中
        req.getRequestDispatcher("/showStudent.jsp").forward(req, resp);

    }
}

Below web.xml:

   <servlet>
       <servlet-name>SearchStudentServlet</servlet-name>
       <servlet-class>com.Servlet.SearchStudentServlet</servlet-class>
   </servlet>
    <servlet-mapping>
        <servlet-name>SearchStudentServlet</servlet-name>
        <url-pattern>/searchStudentServlet</url-pattern>
    </servlet-mapping>

showStudent.jsp下

<%@ page import="java.util.List" %>
<%@ page import="pojo.Student" %>
<%@ page import="java.util.ArrayList" %>
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" %>

<html>
<head>

    <meta charset="utf-8"/>
    <title>Insert title here</title>
<%--    设置样式<style></style>--%>
    <style>
        table{
            border: 1px black solid;
            width: 300px;
        }
        td,tr{
            border: 1px black solid;
            width: 300px;
        }
    </style>
</head>
<body>
<%
    List<Student> list= (List<Student>) request.getAttribute("stuList");

%>
<table>
<%for (Student student:list){%>
<%--    tr是一行,td为一列--%>
<tr>
    <td><%=student.getName()%></td>
    <td><%=student.getId()%></td>
    <td><%=student.getAge()%></td>
</tr>

  <% } %>
</table>
</body>
</html>

 operation result:

 Listener listener

 1. Listener Listener is one of the three major components of JavaWeb. The three major components of javaweb are servlet programs, filter filters, and Listener listeners.

2. Listener is the specification of javaEE, and the specification is the interface

3. The role of the listener is to monitor the changes of a certain transaction, and then through the callback function, feedback to the client or program to do some corresponding processing.

ServletContextListenter listener

ServletContextListener He can monitor the creation and destruction of ServletContext objects.

The ServletContext object is destroyed when the web project starts and when the web project stops.

Steps for the ServletContextListener listener to listen to the ServletContext object

1. Write a class to implement ServletContextListener

2. Two callback methods of the implementer

3. Go to web.xml to configure the listener

Create two methods of class and solid line

package com.Listener;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

public class MyServletContextListenerImpl implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
        System.out.println("Servlet对象被创建了");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
        System.out.println("Servlet对象被销毁了");

    }
}

Configuration in web.xml

<listener>
        <listener-class>com.Listener.MyServletContextListenerImpl</listener-class>
    </listener>

Guess you like

Origin blog.csdn.net/weixin_60719453/article/details/122892589