[Study notes] jsp

One, jsp

1.1 Concept

The full name of jsp is java server pages. java server page

1.2 Role

Mainly replace Servlet to return html page data.
Because the servlet is very cumbersome to send back html pages, the development and maintenance costs are high.

Servlet returns page data

public class Servlet1 extends HttpServlet {
    
    
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
        resp.setContentType("text/html; charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        writer.write("<!DOCTYPE html>\r\n");
        writer.write(" <html lang=\"en\">\r\n");
        writer.write(" <head>\r\n");
        writer.write(" <meta charset=\"UTF-8\">\r\n");
        writer.write(" <title>Title</title>\r\n");
        writer.write(" </head>\r\n");
        writer.write(" <body>\r\n");
        writer.write(" 这是 html 页面数据 \r\n");
        writer.write(" </body>\r\n");
        writer.write("</html>\r\n");
        writer.write("\r\n");
    }
}

jsp return page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    回传数据
</body>
</html>

Accessing the jsp page is the same as accessing the html page, and the jsp page is also placed in the Web directory.

1.3 The essence of jsp

The essence of a jsp page is a servlet program .

When we first visited the jsp page. The Tomcat server will help us translate the jsp page into a java source file. And compile it into a .class bytecode program.
Insert picture description here

Add the path: \work\Catalina\localhost\servletStudy\org\apache\jsp

Insert picture description here
Insert picture description here

Insert picture description here

We traced the original code and found that the HttpJspBase class. It directly inherits the HttpServlet class. In other words. The java class translated by jsp inherits the HttpServlet class indirectly. In other words, what is translated is a Servlet program.

The underlying implementation is also through the output stream. Send the html page data back to the client.

Two, the three grammars of jsp

2.1 The page command at the head

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

Insert picture description here
import attribute
Insert picture description here

Buffer automatic refresh is set to false, if the content exceeds the set buffer buffer value, an error will be reported.
Insert picture description here
Insert picture description here

errorPage indicates the path to automatically jump to after an error. This path usually starts with a slash. It indicates that the request address is http://ip:port/project path/web directory mapped to the code

Insert picture description here

2.2 Commonly used scripts

2.2.1 Declaration script

Declare the format of the script

<%! 声明 java 代码 %>

Function: You can define attributes and methods for the java classes translated by jsp, even static code blocks, internal classes, etc.

jsp statement

    <%--1、 声明类属性--%>
    <%!
      private Integer id;
      private String name;
      private static Map<String,Object> map;
    %>
    <%--2、 声明 static 静态代码块--%>
    <%!
      static {
    
    
        map = new HashMap<String,Object>();
        map.put("key1", "value1");
        map.put("key2", "value2");
        map.put("key3", "value3");
      }
    %>
    <%--3、 声明类方法--%>
    <%!
      public int abc(){
    
    
        return 12;
      }
    %>
    <%--4、 声明内部类--%>
    <%!
      public static class A {
    
    
        private Integer id = 12;
        private String abc = "abc";
      }
    %>

Translation servlet program
Insert picture description here

2.2.2 Expression script

format

<%=表达式%>

Function: Output data on the jsp page.

Features:

  1. All expression scripts will be translated into the _jspService() method
  2. The expression script will be translated into out.print() and output to the page
  3. Since the content of expression script translation is in the _jspService() method, all objects in the _jspService() method can be used directly.
  4. The expression in the expression script cannot end with a semicolon.

jsp code

    <%--
      整型 
      浮点型
      字符串
      获取对象
    --%>
    <%=12%>
    <%=12.12%>
    <%="我是字符串"%>
    <%=request.getParameter("username")%>

Translate to Servlet program
Insert picture description here

2.2.3 Code script

format

<% java语句 %>

effect

You can write the functions we need in the jsp page (the java statement is written).

Features

  1. After the code script is translated, it is in the _jspService method
  2. Since the code script is translated into the _jspService() method, all existing objects in the _jspService() method can be used directly.
  3. You can also combine multiple code script blocks to complete a complete java statement.
  4. Code scripts can also be combined with expression scripts to output data on jsp pages

jsp code

  <%
      int i=3;
      if(i==3){
    
    
          for(int t=0;t<2;t++){
    
    
    %>
            <%="这是"+t+"个"%><br/>
    <%
          }
    %>
    <h1>标题</h1>
    <%
      }
    %>

operation result

Insert picture description here

2.3 Three kinds of comments

2.3.1 html comment

<!-- 这是 html 注释 -->

The html comments will be translated into the java source code. In the _jspService method, output to the client as out.writer.

2.3.2 java annotation

<%
// 单行 java 注释
/* 多行 java 注释 */
%>

The java comments will be translated into the java source code.

2.3.3 jsp comment

<%-- 这是 jsp 注释 --%>

Jsp comments can be annotated, all the code in the jsp page.

Three, nine built-in objects in jsp

The built-in objects in jsp refer to the nine internal objects provided by Tomcat after translating jsp pages into Servlet source code, which are called built-in objects. Can be used directly in jsp code

Insert picture description here

Four, four domain objects

Insert picture description here
Domain objects are objects that can access data like Maps. The functions of the four domain objects are the same. The difference is their range of data access.

Although all four domain objects can access data. They are prioritized in use.
When the four domains are used, the order of priority is their descending order.
pageContext ====>>> request ====>>> session ====>>> application

    <%
        pageContext.setAttribute("key","value");
    %>
    <%=pageContext.getAttribute("key")%>

Five, the difference between the out output of jsp and the output of response.getWriter()

Response represents the response, we are often used to set the content returned to the client (output)

out is also used for user output
Insert picture description here

After JSP translation, the underlying source code is output using out, so in general. We use out uniformly in the jsp page for output. Avoid disturbing the order of output content on the page.

  • out.write() No problem with output string
  • There is no problem with out.print() outputting any data (write output called after all converted into a string),
    so all out.print output can be used.

Six, commonly used labels

6.1 Static inclusion

In a jsp page, introduce another jsp page (the page can be responsible for a module) to facilitate modular management.


Code demo
main page

    <body>
         主页面显示内容<br/>
        <%@include file="a.jsp"%>
  </body>

Introduced page

<body>
    被引入的页面(加广告)
</body>

display effect
Insert picture description here


<%@ include file=""%> is static include

The file attribute specifies the path of the jsp page you want to include
. The first slash / in the address is represented as http://ip:port/project path/ mapped to the web directory of the code

Insert picture description here
Features of static inclusion:
1. Static inclusion will not translate the included jsp page. (That is, a.jsp is not translated into a java program)
2. Static inclusion is actually copying the code of the included jsp page to the included location to execute the output. (Pictured)

6.2 Dynamic inclusion

Code

    <body>
         主页面显示内容<br/>
        <jsp:include page="a.jsp"></jsp:include>
	</body>

Features

  1. Dynamic inclusion will also translate the included jsp page into java code
  2. The dynamic inclusion of the underlying code uses the following code to call the included jsp page to execute the output.
    JspRuntimeLibrary.include(request, response, “/include/footer.jsp”, out, false);
  3. Dynamic inclusion, you can pass parameters

Low-level implementation
Insert picture description here
Insert picture description here

Pass parameters

    <body>
         主页面显示内容<br/>
        <jsp:include page="a.jsp">
            <jsp:param name="username" value="root"></jsp:param> <%--该参数可以被 被包含的jsp页面 获取--%>
            <jsp:param name="password" value="123"></jsp:param> 
        </jsp:include>
    </body>

6.3 jsp label-forwarding

<%--
<jsp:forward page=""></jsp:forward> 是请求转发标签, 它的功能就是请求转发
page 属性设置请求转发的路径
--%>
<jsp:forward page="/a.jsp"></jsp:forward>

Seven, Listener

1. Listener is one of the three major components of JavaWeb. The three major components of JavaWeb are: Servlet program, Filter, Listener.

2. Listener is the specification of JavaEE, which is the interface

3. The role of the monitor is to monitor the changes of something. Then through the callback function, feedback to the customer (program) to do some corresponding processing.

7.1 ServletContextListener listener

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

The ServletContext object is created when the web project is started, and destroyed when the web project is stopped.

After the creation and destruction are monitored, the method feedback of the ServletContextListener listener will be called respectively.

public interface ServletContextListener extends EventListener {
    
    
/**
* 在 ServletContext 对象创建之后马上调用,做初始化
*/
public void contextInitialized(ServletContextEvent sce);
/**
* 在 ServletContext 对象销毁之后调用
*/
public void contextDestroyed(ServletContextEvent sce);
}

Steps for usage

  1. Write a class to implement the ServletContextListener interface
  2. Implement two callback methods
  3. Configure the listener in web.xml

Implement the interface


public class MyListener implements ServletContextListener {
    
    
    @Override
    public void contextInitialized(ServletContextEvent servletContextEvent) {
    
    
        System.out.println("servletContext 对象被创建了(web工程开始)");
    }

    @Override
    public void contextDestroyed(ServletContextEvent servletContextEvent) {
    
    
        System.out.println("servletContext 对象被销毁了(web工程结束)");
    }
}

Configure the listener

    <listener>
        <listener-class>com.study.service.MyListener</listener-class>
    </listener>

Insert picture description here

Guess you like

Origin blog.csdn.net/DREAM_yao/article/details/114129309