[jsp] [multi word and multi picture] [learning notes] Java Web Learning Trip in winter vacation 1.4

Posted by tomtomdotcom on Sun, 13 Feb 2022 13:34:47 +0100

Today, all the train tickets have been bought. I feel closer and closer to Xiagong 🤗, Yada 😭😭😭😭😭

1. jsp first entry

1.1. What is jsp

1. The full replacement of jsp is java server pages, which is the server page of Java
2. The main function of jsp is to return the data of html page instead of Servlet program
3. Because it is very complicated for Servlet program to return html page data. Development and maintenance costs are extremely high

The following figure shows the same html with hello content.

servlet write hello

jsp write hello

1.2. How to access jsp

jsp pages and html pages - like, are stored in the web directory. Accessing is the same as accessing html pages.
For example, there are the following files in the web Directory:

web directory

a. The HTML page access address is = = = = = > > > > > > http://ip:port/ Project path / a.html
b. The JSP page access address is = = = = = > > > > > > > > http://ip:port/ Project path / b.jsp

1.3 what is the essence of jsp

It's essentially a servlet

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

prove

According to Catalina_ Find work\Catalina\localhost in base, and it will be found that tomcat will be automatically generated for the first time. Our project_ jsp

We go all the way to JSP. When we visit b.jsp through the browser for the first time, it will be generated automatically java and class file

🔍 We open the java source file ✋ It is not difficult to find that the contents are:


Then you'll find out 🤓

org.apache.jasper.runtime.HttpJspBase This class inherits HttpServlet This class


In other words, the java class translated by jsp indirectly inherits the HttpServlet class. So, in other words, what is translated is a Servlet program

2. Three syntax of jsp

2.1. page instruction

<%@ page attribute %>
attributeeffect
languageIndicates what language file jsp is after translation. Only java is supported for the time being
contentTypeIndicates what the data type returned by jsp is. It is also the source code response Setcontenttype() parameter value
pageEncodingThe character set that represents the current jsp page file itself
importLike java code, it is used to import packages and classes 🤤
autoFlushSet whether to automatically refresh the buffer after the current out output stream buffer is full. The default is true
bufferSets the size of the out buffer. The default is 8kb
errorPageSet the error page path that will automatically jump to when the current jsp page is running
isErrorPageSet whether the current jsp page is an error page. The default is false. If true, you can get exception information
sessionSet whether the HttpSession object will be created when accessing the current jsp page. The default is true
extendsSet the default inheritance of java translated from jsp

2.1.1,language

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

Indicates what language file jsp is after translation. Only java is supported for the time being

Let's try C + + instead 😁

2.1.2,contentType

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

Indicates what the data type returned by jsp is. It is also the source code response Setcontenttype() parameter value

2.1.3,pageEncoding

<%@ page pageEncoding="GBK" %>

The character set that represents the current jsp page file itself


Under the unified character set, let's change back to UTF-8

2.1.4,import

<%@ page import="java.util.*" %>		<%-- Guide Package --%>	
<%@ page import="java.util.Map" %>		<%-- Guide class --%>

Like java code, it is used to import packages and classes 🤤

2.1.5. autoFlush and buffer

<%@ page          
		autoFlush="true"
        buffer="8kb" %>

It is used for out output stream

autoFlush: set whether to automatically refresh the buffer after the current out output stream buffer is full. The default is true
Buffer: sets the size of the out buffer. The default is 8kb (this 8kb is a suitable value obtained through many experiments)

Let's turn off the automatic refresh cache, reduce the buffer value, and then make more content in the jsp to see the effect

<%@ page contentType="text/html;charset=UTF-8"
         autoFlush="false"
         buffer="1kb"
         language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    b.jsp page
    <div>flzj</div>		<%--  We let this div Quantity: 100 --%>
</body>
</html>

We can see that the buffer overflowed

2.1.6,errorPage

<%@ page errorPage="route" %>

Set the error page path that will automatically jump to when the current jsp page is running
We deliberately write a 12 / 0 error here in b.jsp, Ow 😁

<%@ page contentType="text/html;charset=UTF-8"
        errorPage="/errro500.jsp"
         language="java" %>
<!--
errorPage Indicates the path to automatically jump after an error
 This path usually begins with a slash,Not to/It also means that the request address is
		http://ip:port / Project path/
		Mapped to code webapp catalogue
-->
<html>
<head>
    <title>Title</title>
</head>
<body>
    b.jsp page
    <%
        int a = 12 / 0;
    %>
</body>
</html>

Then we write errro 500 jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Wrong!</title>
</head>
<body>
    You visited b.jsp Program error occurred!!! We are vigorously maintaining...
</body>
</html>

At this point, when we visit b.jsp, we will jump to errro500.jsp jsp

2.1.7,isErrorPage

<%@ page isErrorPage="false" %>

Set whether the current jsp page is an error page. The default is false. If true, you can get exception information

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

This line will not appear in the source code until isErrorPage is set to true

2.1.8,session

<%@ page session  ="true" %>

Set whether the HttpSession object will be created when accessing the current jsp page. The default is true
If set to false, this line of code will not appear in the following figure

2.1.9,extends

<%@ page extends ="Detailed path of class" %>

Set the default inheritance of java translated from jsp. Here we change to inherit HttpServlet

<%@ page contentType="text/html;charset=UTF-8"
         extends="javax.servlet.http.HttpServlet"
         language="java" %>

The effect is ideal (sure, generally don't change it randomly)

2.2 scripts commonly used in jsp

Scripts written outside or inside HTML tags can be used

2.2.1 declaration script

Format: <%! Declare java code% >

Function: you can define attributes, methods and even static code blocks for java classes translated from jsp. Internal classes, etc.

Declare class properties

<%!
    private Integer age;
    private String name;
    private static Map<String,Object> map;
%>

Declare static code blocks

<%!
    static{
        map = new HashMap<String,Object>();
        map.put("k1","v1");
        map.put("k2","v2");
        map.put("k3","v3");
    }
%>

Declare class methods

<%!
    public void helloTest(){
    	System.out.println("HELLO!");
    }
%>

Declare inner class

<%!
    private static class a{
        private int age = 10;
        String name = "flzjsTest";
    }
%>

After writing these, we run tomcat and enter b.jsp. At this time, we'll see what changes will happen to b.java

<%@ page import="java.util.Map" %>
<%@ page import="java.util.HashMap" %>
<%@ page contentType="text/html;charset=UTF-8"
    language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <%!
    	// Declare class properties
    	private Integer age;
        private String name;
        private static Map<String,Object> map;
        //Declare static code blocks
        static{
            map = new HashMap<String,Object>();
            map.put("k1","v1");
            map.put("k2","v2");
            map.put("k3","v3");
        }
        //Declare class methods
        public void helloTest(){
            System.out.println("HELLO!");
        }
        //Declare inner class
        private static class a{
            private int age = 10;
            String name = "flzjsTest";
        }
        %>
    </body>
</html>

before

after

2.2.2 expression script

Format: <% = expression% >
Function: output data on jsp page

Let's hurry up and get ready to run away

<%--
1.Output integer
2.Floating point output
3.Output string
4.Output object
--%>
    <%= 12 %> <br/>
    <%= 12.12%> <br/>
    <%= "hahaha"%> <br/>
    <%= map%>   <br/>
    <%= request.getParameter("username")%>


Characteristics of expression script
1. All expressions in pjsservice () will be translated into the script

2. Expression scripts are translated into out Print () output to the page

3. Because the content of expression script translation is_ In the jspService() method, so_ All objects in the jspService() method can be used directly.

For example, in the following figure, request, response, pageContext, session... Are available


Here we use the request object inside

<%= request.getParameter("username")%>

4. An expression in an expression script cannot end with a semicolon.

Or it will 😱😱😱, Translate into source code

2.2.3 code script

Format: <% java code% >
Function: we can write our own functions in jsp

<%--
1,if sentence
2,for Circular statement
3,After translation java In the file_jspService The code in the method can be written
--%>
    <%
        int a = 10;
        if(a == 10) System.out.println("a Equal to 10");
        else System.out.println("a Not equal to 10");
    %>
    <%
        for(int i = 0 ; i < 10 ; i++)
            System.out.println(i);
    %>
    <%
        System.out.println(request.getParameter("username"));
    %>

characteristic

1. After the code script is translated_ In the jspService () method

2. Code script due to translation to_ jspService() method, so in_ All existing objects in the jspService() method can be used directly

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-vwzqu3y2-164474569037) (D: \ Java \ JavaWeb \ picture \ JSP \ the code script is also in the _jspservicemethod. png)]

3. You can also combine multiple code script blocks to complete a completed java statement

You can even write a for loop like this

    <%
        for(int i = 0 ; i < 10 ; i++){
    %>
    <%
            System.out.println(i);
        }
    %>

[the external chain picture transfer fails. The source station may have anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-ii9yfhxu-164474569037) (D: \ Java \ JavaWeb \ picture \ JSP \ code script feature 3.png)]

4. Code scripts can also be combined with expression scripts. In the jsp page Output data on

You can output 0 ~ 9 like this

    <%
        for(int i = 0 ; i < 10 ; i++){
    %>
    <%= i  %> <br/>
    <%
        }
  	%>

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-3djtnodq-164474569037) (D: \ Java \ JavaWeb \ picture \ JSP \ code script feature 4.png)]

2.3. Three annotations of jsp

2.3.1. html comments

<!-- This is html notes -->

html comments are translated into java source code. In_ jspService method, with out The writer outputs to the client.

2.3.2 java annotation

<%
    // This is a java single line comment
    /*
    *   This is a java multiline comment
    * */
%>

java comments are translated into java source code

2.3.3. jsp comments

<%--
    <!-- This is html notes -->
    <%
        // This is a java single line comment
        /*
         *   This is a java multiline comment
         * */
    %>
--%>

jsp comments can be noted out, and all the code in the jsp page., Therefore, the natural java source code does not appear, so the browser will not appear

3. jsp nine built-in objects

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.

objectexplain
requestRequest object
responseResponse object
pageContextjsp context object
sessionSession object
applicationServletContext object
configServletConfig object
outjsp output stream object
pageObject pointing to the current jsp
exceptionException object (requires isErrorPage = "true")

4. jsp four domain objects

Domain objectterm of validity
pageContext(PageContextmpl class)Valid within the current jsp page range
request(HttpServletRequest class)Valid within one request
session(HttpSession class)Valid within a session scope (open the browser to access the server until the browser is closed)
application(ServletContext class)The whole web project scope is valid (as long as the web project does not stop, the data is)

A domain object is an object that can access data like a Map. The functions of the four domain objects are the same. The difference is their access range to data.

Although all four domain objects can access data. They have priority in use. When the four domains are used, the order of priority is from small to large:
pageContext ===>>> request ====>>>session ====>>> application

Effect demonstration

Let's start with a scope1 jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Here is scope1 page</title>
</head>
<body>
    <h1>Here is scope1 page</h1>
    <%
        pageContext.setAttribute("key","pageContext");
        request.setAttribute("key","request");
        session.setAttribute("key","session");
        application.setAttribute("key","application");
    %>
    pageContext The value of is: <%= pageContext.getAttribute("key")%> <br/>
    request The value of is: <%= request.getAttribute("key")%> <br/>
    session The value of is: <%= session.getAttribute("key")%> <br/>
    application The value of is: <%= application.getAttribute("key")%> <br/>
</body>
</html>

here, 👴 Suddenly found 👴 Pagecontext SetAttribute () doesn't work. We need to import JSP ourselves jar. .

Now, we need to add jump to scope 2 after the above code JSP and write scope2 JSP starts testing

<%
	//Jump to scope2 jsp
	request.getRequestDispatcher("/scope2.jsp").forward(request,response);
%>
<html>
<head>
    <title>This is scope2.jsp</title>
</head>
<body>
    <h1>This is from scope1 Bouncing scope2</h1>
    pageContext The value of is: <%= pageContext.getAttribute("key")%> <br/>
    request The value of is: <%= request.getAttribute("key")%> <br/>
    session The value of is: <%= session.getAttribute("key")%> <br/>
    application The value of is: <%= application.getAttribute("key")%> <br/>
</body>
</html>

At this time, we visit scope1 JSP will find that the value of the pagecontext field has disappeared

Now, let's go directly to scope2 The values of JSP and request fields also disappear

Now let's reopen the browser and visit scope2 JSP, we will find that the value of the session field also disappears

Then, we restart the server, or redeploy the server, and then access scope 2 JSP, you will find that the value of the application field also disappears

5. jsp output

We usually use, out output and response Getwriter output

Here, you must wonder why out writes first and then outputs

It was out The flush () operation will write the data of the out buffer to the end of the response buffer, as shown in the following figure

At this time, some people will not believe it. Oh, let's go out Try the flush () method

conclusion

1. Use out Write() to output

(because the translated source code is also output with out, the output with response.getWriter may be out of order)

2,out.write() can only be used to output strings or characters. You can try write print().

(out.write() will forcibly convert the passed in parameter to char []. Out in the source code The print () method converts the content into a string and then calls out Write() method output)

6. Common tags of jsp

6.1 static inclusion

format

<%@ include file = "/" %> 

The file attribute specifies the jsp path you want to include

The first diagonal bar in the path indicates http://ip:port/ Engineering path/

graphic

Static inclusion means that you can update a piece of content flexibly. For example, in the figure below, you can update the footer flexibly

code implementation

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>This is a web page</title>
</head>
<body>
    Header information<br/>
    topic information<br/>
    <%@ include file="/include/foot.jsp"%>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Here is the bottom information</title>
</head>
<body>
    Bottom information<br/>
</body>
</html>

characteristic

1. Static inclusion will not translate the included jsp page
2. Static inclusion is actually the inclusion of jsp Copy the code of the page to the included location to execute the output

6.2 dynamic inclusion

format

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

The page attribute specifies the path of the jsp page you want to include

Like static inclusion, dynamic inclusion can also execute and output the included content to the included location

code implementation

It is similar to the static inclusion above 😁😁😁

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>This is a web page</title>
</head>
<body>
    Header information<br/>
    Subject information<br/>
    <jsp:include page="/include/footer.jsp"></jsp:include>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Here is the bottom information</title>
</head>
<body>
    Bottom information<br/>
</body>
</html>

graphic

characteristic

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

2. Dynamically include the underlying code, and use 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 and parameter transfer

Write this in main

<jsp:include page="/include/footer.jsp">
    <jsp:param name="username" value="abc"/>
    <jsp:param name="password" value="123456"/>
</jsp:include>

footer writes this to receive

<%= request.getParameter("username")%>
<%= request.getParameter("password")%>

6.3. Request forwarding

From scope1 JSP jump to scope2 jsp

<jsp:forward page="/scope2.jsp"></jsp:forward>

jsp exercise

multiplication table

The code is extremely unreadable

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>multiplication table</title>
    <style type="text/css">
        table{
            width: 650px;
        }
    </style>
</head>
    <h1>multiplication table</h1>
    <table align="center">
    <%for(int i = 1 ; i <= 9 ; i++){%>
        <tr>
        <%for(int j = 1 ; j <= i ; j++){ %>
            <td> <%= j + "x" + i  + "=" + (j * i) %> </td>
        <% } %>
        </tr>
    <% } %>
    </table>
<body>

</body>
</html>

Enter student information into the form

Student class

public class Student {
    private Integer id;
    private String name;
    private Integer age;
    private String phone;
}
//Construction, get and set omitted 

jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Enter student information into the form</title>
    <style>
        table{
            border:  1px black solid;
            width: 600px;

        }
        td,th{
            border: 1px blue solid;
        }
    </style>
</head>
<body>
    <%
        List<Student> studentList = new ArrayList<Student>();
        for(int i = 1 ; i <= 10 ; i++){
            studentList.add(new Student(i,"student" + i,i,"phone" + i));
        }
    %>
    <table>
        <tr>
            <td>number</td>
            <td>full name</td>
            <td>Age</td>
            <td>mobile phone</td>
        </tr>
    <% for(Student s : studentList){ %>
            <tr>
                <td><%= s.getId() %></td>
                <td><%= s.getName() %></td>
                <td><%= s.getAge() %></td>
                <td><%= s.getPhone() %></td>
            </tr>
    <% } %>
    </table>
</body>
</html>

Request forwarding practice

1. 2 already learned, this is not the point, we need to finish 3

SearchStudentServlet

public class SearchStudentServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        List<Student> studentList = new ArrayList<Student>();
        for(int i = 1 ; i <= 10 ; i++){
            studentList.add(new Student(i,"student" + i,i,"phone" + i));
        }
        request.setAttribute("stuList",studentList);
        request.getRequestDispatcher("/test/showStudent.jsp").forward(request,response);
    }
}

showStudent.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Student information is displayed here</title>
    <style>
        table{
            border:  1px black solid;
            width: 600px;

        }
        td,th{
            border: 1px blue solid;
        }
    </style>
</head>
<body>
<table>
    <tr>
        <td>number</td>
        <td>full name</td>
        <td>Age</td>
        <td>mobile phone</td>
    </tr>
    <% List<Student> studentList = (List<Student>)request.getAttribute("stuList"); %>
    <% for(Student s : studentList){ %>
    <tr>
        <td><%= s.getId() %></td>
        <td><%= s.getName() %></td>
        <td><%= s.getAge() %></td>
        <td><%= s.getPhone() %></td>
    </tr>
    <% } %>
</table>
</body>
</html>

design sketch

7. Listener listener

7.1 introduction to listener

1. Listener listener is one of the three major components of Java Web. The three major components of Java Web are: Servlet program, Filter filter and listener listener
2. Listener is the specification of Java EE, which is the interface
3. The function of a listener is to monitor the change of something. Then through the callback function, feedback to the customer (program) to do some corresponding processing

7.2. ServletContextListener listener

ServletContextListener, which can listen to the creation and destruction of ServletContext objects.

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

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

contextInitialized

Call immediately after the ServletContext object is created to initialize

default void contextInitialized(ServletContextEvent sce) {
}

contextDestroyed

After the ServletContext object is destroyed, it is called.

default void contextDestroyed(ServletContextEvent sce) {
}

7.3. How to use ServletContextListener listener

1. Write a class to implement ServletContextListener
2. Implement its two callback methods

public class MyServletContextListenerImpl implements ServletContextListener {
    @Override
    public void contextInitialized(ServletContextEvent sce) {
        System.out.println("ServletContext Object was created");
    }

    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        System.out.println("ServletContext The object was destroyed");
    }
}

3. To the web Configuring listeners in XML

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

That's it 🌶, Come on, come on, there are 13 days left before the end of the winter vacation

Topics: Java JavaEE JSP Tomcat server