Dynamic website jsp technology

Article directory

Zero. Learning objectives of this section

Understand the concepts and characteristics of JSP
Be familiar with the operating principles of JSP
Master the basic syntax of JSP
Be familiar with JSP Use of instructions
Master the use of JSP action elements
Master the use of JSP implicit objects

1. Overview of JSP

(1) What is JSP

Goal: Understand the concepts and characteristics of JSP, and be able to know what JSP is used for

1. The concept of JSP

The full name of JSP is Java Server Pages, which is Java server pages. It is a higher-level extension of Servlet. In a JSP file, HTML code and Java code coexist. HTML code is used to display static content in web pages, and Java code is used to display dynamic content in web pages. Finally, the JSP file will be compiled into a Servlet through the Web container of the Web server to handle various requests.

2. Characteristics of JSP

(1) Cross-platform
Since JSP is based on Java language, Web applications developed using JSP are cross-platform and can be applied to different systems, such as Windows and Linux. wait. When porting from one platform to another, JSP and JavaBean code does not need to be recompiled. This is because Java bytecode is platform-independent, which is also in line with the Java language's "compile once, run anywhere" principle. Features.
(2) Separation of business code
When using JSP technology to develop Web applications, the development of the interface can be separated from the development of the application. Developers design interfaces using HTML and use JSP tags and scripts to dynamically generate content on the page. On the server side, the JSP container is responsible for parsing JSP tags and script programs, generating the requested content, and returning the execution results to the browser in the form of HTML pages.
(3) Component reuse
JavaBean can be used to write business components in JSP, that is, a JavaBean is used to encapsulate business processing code or as a data storage model. In JSP This JavaBean can be reused in the page or even in the entire project. At the same time, the JavaBean can also be applied to other Java applications.
(4) Pre-compilation
Pre-compilation means that when the user accesses the JSP page through the browser for the first time, the server will compile the JSP page code and only Perform a compilation. The compiled code will be saved, and the compiled code will be executed directly the next time the user visits. This not only saves the server's CPU resources, but also greatly improves the client's access speed.

(2) Write the first JSP

Goal: Master the writing of JSP files.

1. Create a Web project
  • Create Java Enterprise and add Web Application
    Insert image description here
2. Modify the Artifact name and redeploy the project
  • Modify the Artifact name in the project structure window
    Insert image description here
  • In the service period configuration window, redeploy the project

Insert image description here

  • Switch to the [Server] tab and set the default browser
    Insert image description here
3. Create a welcome JSP page
  • Create in web directorywelcome.jsp
    Insert image description here
  • Note: As can be seen from thewelcome.jsp page, the newly created JSP file is almost the same as the traditional HTML file. The only difference is that when created by default, there is an extra line at the top of the page code. page directive, and the file extension is jsp instead of html.
  • Revisewelcome.jsp
    Insert image description here
4. Start the server and view the results
  • Start the server and accesshttp://localhost:8080/JSPDemo/welcome.jsp
    Insert image description here

  • Note: The content added in the tag of welcome.jsp has been displayed, which shows that HTML elements can be parsed by the JSP container. In fact, JSP just adds some code with Java characteristics to the original HTML file. These are called JSP syntax elements. Classroom exercise: Modify the home page as shown below<body>

    Insert image description here

2. JSP basic syntax

(1) Basic composition of JSP page

Goal: Be familiar with the basic structure of JSP pages

1. JSP page composition

Although the JSP file has been created, the page structure of the JSP file has not been introduced in detail. A JSP page can include content such as instruction tags, HTML code, JavaScript code, embedded Java code, comments, and JSP action tags.

2. Case demonstration - display the current time of the system

  • Buildingtime_info.jspScale page
    Insert image description here
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>JSP页面 - 显示系统当前时间</title>
    </head>
    <body>
        <%
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(date);
        %>
        <h3 style="text-align: center">系统当前时间:<%= currentTime%></h3>
    </body>
</html>

  • Page composition diagram
    Insert image description here
  • Start the server and accesshttp://localhost:8080/JSPDemo/time_info.jsp
    Insert image description here

(2) JSP script elements

Objective: Master the three types of JSP script elements: JSP Scriptlets, declaration tags and JSP expressions
JSP script elements are nested between "<%" and "%" >" one or more pieces of Java program code. Java code can be embedded in HTML pages through JSP script elements, and all executable Java codes can be executed through JSP scripts.

1、JSP Scriptlet

(1) Basic concepts

JSP Scriptlets are snippets of code. The so-called code snippet is the Java code or script code embedded in the JSP page. Code snippets will be executed during the processing of page requests. Java code can define variables or flow control statements, etc.; and script code can use JSP's built-in objects to output content on the page, process requests, and access sessions, etc.

(2) Grammar format
<% java 代码(变量、方法、表达式等)%>

(3) Case demonstration
  • Buildingdemo01.jspScale page
    Insert image description here
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>JSP Scriptlets</title>
    </head>
    <body>
        <%
            int a = 100, b = 150; // 定义两个整型变量
            int sum = a + b; // 计算两个整数之和
            out.print(a + " + " + b + " = " + sum); // 输出求和结果
        %>
    </body>
</html>

  • Start the server and accesshttp://localhost:8080/JSPDemo/demo01.jsp
    Insert image description here

2. Statement of identity

(1) Basic concepts

In JSP Scriptlets, attributes can be defined and content can be output, but methods cannot be defined. If you want to define a method in a script element, you can use the declaration flag. The declaration identifier is used to define global variables or methods in JSP pages. It starts with "<%!" and ends with "%>". Variables and methods defined through the declaration identifier can be accessed by the entire JSP page, so this identifier is usually used to define variables or methods that need to be referenced by the entire JSP page.
What are defined in the JSP declaration statement are member methods, member variables, static methods, static variables, static code blocks, etc. The method declared in the JSP declaration statement is valid within the entire JSP page, but the variables defined within the method are only valid within the method. When the declared method is called, memory will be allocated for the variables defined in the method, and the occupied memory will be released immediately after the call is completed.
Note: There can be multiple JSP declaration identifiers in a JSP page. The Java statement in a single declaration can be incomplete, but the result of the combination of multiple declarations must be a complete Java statement. .

(2) Grammar format
<%! 
	定义变量或方法等
%>

(3) Case demonstration
  • Buildingdemo02.jspScale page
    Insert image description here
<html>
    <head>
        <title>JSP声明标识</title>
    </head>
    <body>
        <%!
            // 定义阶乘函数
            public long factorial(int n) {
                long jc = 1;
                for (int i = 1; i <= n; i++) {
                    jc = jc * i;
                }
                return jc;
            }
        %>
        <%
            // 输出10的阶乘值
            out.println("10! = " + factorial(10));
        %>
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo02.jsp
    Insert image description here
(4) Precautions

The attributes defined in "<%!" and "%>" are member attributes, which are equivalent to the attributes of the class, and the methods are equivalent to global methods and methods in the class, but in "< ";%!" and "%>" cannot be output, only method definitions and attribute definitions can be made there.
"<%!" and "%>" are used to define properties and methods, and "<%" and "%>" are mainly used to output content, so If it involves the operation of member variables, then you should use "<%!" and "%>", and if it involves output content, use "<%" and "%>".
Variables and methods created by declaration identifier are valid in the current JSP page, and their life cycle is from the beginning of creation to the end of the server; variables or methods created by code snippets are also valid in the current JSP page , but its life cycle is that it will be destroyed after the page is closed.

3. JSP expression

(1) Basic concepts

JSP expression (expression) is used to output information to the page. It starts with "<%=" and ends with "%>".

(2) Grammar format
<%= expression %>
  • In the above syntax format, the parameterexpression can be a complete expression in any Java language, and the final operation result of the expression will be converted into a string.
(3) Case demonstration
  • Buildingdemo03.jspScale page
    Insert image description here
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>JSP表达式</title>
    </head>
    <body>
        <%!
            int a = 100, b = 150; // 声明两个整型变量
        %>
        sum = <%= a + b%> <!--JSP表达式-->
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo03.jsp
    Insert image description here
(4) Precautions

Note“<%=” is a complete symbol, there can be no space between “<%” and “=”, and the JSP expression There cannot be a semicolon after a variable or expression in (;).

(3) JSP comments

Familiar with comments with JSP expressions, hidden comments, and dynamic comments in JSP comments

1. Comments with JSP expressions

(1) Single line comment

Basic concept: Code snippets can be embedded in JSP pages, and comments can also be added to the code snippets. Comments in code snippets are the same as Java comments. Single-line comments start with "//" and are followed by the comment content.

  • Syntax format
// 注释内容
(2) Multi-line comments

Basic concept: Multi-line comments start with "/" and end with "/". The content in the middle of this mark is the comment content, and the comment content can be wrapped.

  • Syntax format
/*
  注释内容1
  注释内容2
  ......
 */
  • For the sake of the beauty of the program, it is customary to add a "*" in front of each line of comment content.
/*
 * 注释内容1
 * 注释内容2
 * ......
 */
(3) Prompt document comments

Basic concept: Prompt documentation comments are read when the document is generated by the Javadoc documentation tool. The document is a description of the code structure and function.
Grammar format

/**
  提示信息1
  提示信息2
  ......
 */
  • Like multi-line comments, for the sake of the beauty of the program, it is customary to add a“*”
/**
 * 提示信息1
 * 提示信息2
 * ......
 */
  • Note: The prompt document comment method is very similar to the multi-line comment, but careful readers will find that it uses “/**” as the start tag of the comment instead of “/*”. The server will not do any processing for the content commented in the prompt document comment.
(4) Case demonstration
  • Buildingdemo04.jspScale page
    Insert image description here
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>带有JSP表达式的注释</title>
    </head>
    <body>
        <%!
            /** 
             * @param a
             * @param b
             * @return a + b
             */
            public int sum(int a, int b) {
                /*
                 * a, b都是形式参数
                 */
                return a + b;  // 返回两个整数之和 
            }
        %>
        <%
            int a = 100, b = 150; // 定义两个整型变量
            int sum = a + b; // 计算两个整数之和
            out.println("sum = " + sum); // 输出结果
        %>
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo04.jsp
    Insert image description here

2. Hide comments

(1) Basic concepts

Although the HTML comments added to the document are not displayed in the browser page, you can see the comment information by viewing the source code. So strictly speaking, these annotations are unsafe. To this end, JSP provides hidden comments. Hidden comments are not only invisible in the browser page, but also cannot be seen when viewing the HTML source code, so hidden comments have higher security.

(2) Grammar format
<%-- 注释内容 --%>
(3) Case demonstration
  • Buildingdemo05.jspScale page
    Insert image description here
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>JSP注释</title>
    </head>
    <body>
        <h1>学习JSP元素</h1> <!--HTML注释:一级标题显示-->
        <%= new Date()%> <%--JSP注释:用JSP表达式元素显示当前日期--%>
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo05.jsp
    Insert image description here
  • Right-click on the opened page and select the "View Web Page Source Code" option in the pop-up menu.
    Insert image description here
  • Note: In the picture above, the web page source code only displays HTML comments, but does not display JSP comment information. This is because when Tomcat compiles the JSP file, it will send the HTML comments to the client as ordinary text, and the content in the format of “<%-- 注释信息 --%>” in the JSP page will be ignored and will not be sent to the client.

3. Dynamic annotation

(1) Basic concepts

Since HTML comments do not work on JSP embedded code, their combination can be used to form dynamic HTML comment text.

(2) Grammar format
<!-- JSP元素 -->
(3) Case demonstration
  • Buildingdemo06.jspScale page
    Insert image description here
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        随机数:<%= Math.random() %> <!-- 求随机数,当前日期:<%=new Date()%> -->
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo06.jsp
    Insert image description here
  • Right-click on the opened page and select the "View Web Page Source Code" option in the pop-up menu.

3. JSP instructions

(1) page command

Goal: Be familiar with the page directive defined in JSP 2.0

1. Basic concepts

In JSP pages, it is often necessary to describe certain features of the page, such as the encoding method of the page, the language used in the JSP page, etc. The description of these features can be achieved through the page directive.

2. Grammar format

<%@ page 属性名1 = "属性值1" 属性名2 = "属性值2" ...%>
  • page is used to declare the directive name, and attributes are used to specify certain characteristics of the JSP page. The page directive also provides a series of properties related to JSP pages.
3. Case demonstration
  • pageAmong the common attributes of the directive, except the import attribute, other attributes can only appear once, otherwise the compilation will fail.
  • Create a page to jump to after an errorerror.jsp
    Insert image description here
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
    <head>
        <title>错误页面</title>
    </head>
    <body>
        <h3 style="text-align: center">错误信息:<%= exception.getMessage() %></h3>
    </body>
</html>
  • Buildingdemo07.jspScale page
    Insert image description here
<%@ page import="java.text.SimpleDateFormat" %>
<%@ page import="java.util.Date" %>
<%@ page contentType="text/html;charset=UTF-8" language="java"
         pageEncoding="utf-8" errorPage="error.jsp" %>
<html>
    <head>
        <title>JSP页面 - 显示系统当前时间</title>
    </head>
    <body>
        <%
            Date date = new Date();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String currentTime = sdf.format(date);
        %>
        <h3 style="text-align: center">系统当前时间:<%= currentTime%></h3>
    </body>
</html>
  • View page instructions
    Insert image description here

  • The code in the red box above uses the page directive's language, contentType, pageEncodingandimportattributes. It should be noted that the page directive is valid for the entire page, regardless of where it is written, but it is customary to write the page directive at the front of the JSP page.

  • To start the service period, visithttp://localhost:8080/JSPDemo/demo07.jsp
    Insert image description here

  • Modifydemo07.jsp the page and deliberately make Java code errors
    Insert image description here

  • Start the service period, visithttp://localhost:8080/JSPDemo/demo07.jsp, and display the system default error page
    Insert image description here

  • Ifdemo07.jspSpecify error pageerror.jsp
    Insert image description here

  • Start the service period, visithttp://localhost:8080/JSPDemo/demo07.jsp, and display the user-specified error page
    Insert image description here

  • Correctiondemo07.jspPage errors
    Insert image description here

(2) include directive

  • Goal: Master the include directive defined in JSP 2.0

1. Basic concepts

  • During actual development, sometimes it is necessary to include another JSP page in the JSP page. In this case, this can be achieved through the include directive.

2. Grammar format

<%@ include file="被包含的文件地址" %>
  • includeThe directive has only one file attribute, which specifies the path of the file to be included. It should be noted that the path to the inserted file generally does not start with "/", but uses a relative path.

3. Case demonstration

  • Buildingdemo08.jspScale page
    Insert image description here
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>欢迎页面</title>
    </head>
    <body>
        <h1 style="color: blue; text-align: center">欢迎访问JSP世界~</h1>
        <%@ include file="time_info.jsp"%>
    </body>
</html>

Start the server and accesshttp://localhost:8080/JSPDemo/demo08.jsp
Insert image description here

4. Frequently Asked Questions

(1) The imported file must follow JSP syntax, and its content can include all the content of ordinary JSP pages such as static HTML, JSP script elements and JSP instructions.
(2) Except for the instruction elements, other elements in the imported file are converted into corresponding Java source codes, and then inserted into the Servlet source file translated into by the current JSP page. , the insertion position is consistent with the position of the include directive in the current JSP page.
(3) The setting value of the file attribute must use a relative path. If it starts with "/", it means relative to the root directory of the current web application (note not the site root directory); otherwise, it means Relative to the current file. It should be noted that the relative path specified by the file attribute here is relative to the file (file), not relative to the page (page).
(4) When applying the include directive for file inclusion, in order to prevent the hierarchy of the entire page from conflicting, it is recommended to delete the tags such as and in the included page, because in the file containing the page These labels have been specified in .

  • The included pagetime_info.jsp can be modified as follows
    Insert image description here
  • Start the server and visithttp://localhost:8080/JSPDemo/demo08.jsp, the content of the included page can also be displayed
    Insert image description here

(3) taglib command

  • Goal: Be familiar with the taglib directives defined in JSP 2.0

1. Basic concepts

In the JSP file, you can use the taglib directive to identify the tag library used in the page, reference the tag library, and specify the prefix of the tag. After referencing the tag library in the page, you can reference the tags in the tag library through prefixes.

2. Grammar format

<%@ taglib prefix="tagPrefix" uri="tagURI" %>

3. Case demonstration

  • Createdirectory inWEB-INF and add two packageslibjar

  • Buildingdemo09.jspScale page

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
    <head>
        <title>JSTL核心库演示</title>
    </head>
    <body>
        <c:set var="message" value="欢迎访问JSP世界~"/>
        <h1 style="text-align: center"><c:out value="${message}"/></h1>
    </body>
</html>
  • The introduction of JSTL can make the codes such as <% and %> disappear in the JSP code. Combined with EL expressions, it will be more convenient and beautiful.

  • Start the server and accesshttp://localhost:8080/JSPDemo/demo09.jsp
    Insert image description here

  • If you do not use the JSTL core tag library, use JSP code to achieve the same function.
    Insert image description here

  • Start the server and accesshttp://localhost:8080/JSPDemo/demo09.jsp
    Insert image description here

4. JSP action elements

(1) Contains file elements

Goal: Master the include file elements of JSP<jsp:include>

1. Basic concepts

In JSP pages,<jsp:include> action elements are used to introduce other files to the current page. The introduced files can be dynamic files or static files.

2. Grammar format

<jsp:include page="URL" flush="true|false" />

3. Contain principles

<jsp:include>The principle of inclusion is to include the compiled result of the included page in the current page. For example, use the <jsp:include> element in page 1 to include page 2. When the browser requests page 1 for the first time, the web container will first compile page 2, and then include the compiled and processed return result. In page 1, page 1 is then compiled, and finally the combined results of the two pages are responded to the browser.

4. Case demonstration

  • Buildingdemo10.jspScale page
    Insert image description here
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>被包含的页面</title>
    </head>
    <body style="text-align: center">
        <%
            Thread.sleep(5000); // 线程休眠5秒
        %>
        红豆生南国<br>
        春来发几枝<br>
        愿君多采撷<br>
        此物最相思<br>
    </body>
</html>
  • Createdemo11.jsp page and importdemo10.jsp page. demo10.jspAs an imported file, let it pause for 5 seconds before outputting the content. In this way, it is convenient to test the <jsp:include> element. >Properties. flush

(2) Request forwarding element

  • Goal: Master the JSP request forwarding element jsp:forward

1. Basic concepts

<jsp:forward>The action element can forward the current request to other web resources (HTML page, JSP page, Servlet, etc.). After the request is forwarded, the current page will no longer be executed, but the target page specified by the element will be executed.

2. Grammar format

<jsp:forward page="relativeURL" />

pageThe attribute is used to specify the relative path of the resource to which the request is forwarded. The target file of this path must be an internal resource in the current application.

3. Case demonstration

  • Buildingdemo12.jspScale page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>演示请求转发元素</title>
    </head>
    <body>
        <h1 style="text-align: center">演示请求转发元素</h1>
        <%
            Thread.sleep(5000); // 线程休眠5秒
        %>
        <jsp:forward page="welcome.jsp"/> <!--转发到欢迎页面-->
    </body>
</html>
  • Start the server, visithttp://localhost:8080/JSPDemo/demo12.jsp, and find that the browser will not display the output content in the demo12.jsp page, and will wait for 5 seconds before it will be displayedwelcome.jspThe content of the page.

5. JSP implicit objects

(1) Overview of JSP implicit objects

  • Goal: Preliminary understanding of JSP implicit objects

  • In JSP pages, there are some objects that need to be used frequently. It will be very troublesome to recreate these objects every time. In order to simplify the development of Web applications, the JSP2.0 specification provides 9 implicit (built-in) objects, which are created by JSP by default and can be used directly in JSP pages.

(2) out object

  • Goal: Master the use of out objects in JSP pages to send text content to the client

1. The role of out object

In JSP pages, it is often necessary to send text content to the client. Sending text content to the client can be achieved using the out object. The out object is an instance object of the javax.servlet.jsp.JspWriter class. Its function is very similar to the PrintWriter object returned by the ServletResponse.getWriter() method. They are both used to send entity content in the form of text to the client. The difference is that the type of the out object is JspWriter, which is equivalent to PrintWriter with caching function.

2. Work between the out object and the buffer provided by the Servlet engine

In a JSP page, writing data through the out implicit object is equivalent to inserting data into the buffer of the JspWriter object. Only by calling the ServletResponse.getWriter() method can the data in the buffer be actually written to the buffer provided by the Servlet engine. in the buffer.

3. Case demonstration

  • Buildingdemo13.jspScale page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>演示out对象的用法</title>
    </head>
    <body>
        <%
            out.println("第1行:Web开发很有意思~<br />");
            response.getWriter().println("第2行:我们来学Web开发~<br />");
        %>
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo13.jsp
    Insert image description here

4. Use the page command to set the buffer size of the out object.

  • Sometimes, developers hope that the out object can directly write data into the buffer provided by the Servlet engine. In this case, this can be achieved by operating the buffer attribute of the buffer in the page instruction.
  • Modifydemo13.jspcode and set the buffer of the out object
    Insert image description here
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo13.jsp
    Insert image description here

(3) pageContext object

  • Goal: Master the use of pageContext objects in JSP pages to obtain the other 8 implicit objects of JSP

1. pageContext object

In a JSP page, you can use the pageContext object to obtain the other 8 implicit objects of JSP. pageContext对象 is an instance object of the javax.servlet.jsp.PageContext class, which represents the running environment of the current JSP page and provides a series of methods for obtaining other implicit objects.

2. Method for pageContext object to obtain implicit object

method name Function description
JspWriter getOut() Used to get the out implicit object
Object getPage() Used to obtain the page implicit object
ServletRequest getRequest() Used to get the request implicit object
ServletResponse getResponse() Used to get the response implicit object
HttpSession getSession() Used to obtain the session implicit object
Exception getException() Used to obtain the exception implicit object
ServletConfig getServletConfig() Used to obtain the config implicit object
ServletContext getServletContext() Used to obtain the application implicit object

3. Related methods of pageContext operation attributes

method name Function description
void setAttribute(String name, Object value, int scope) Used to set properties of the pageContext object
Object getAttribute(String name, int scope) Used to obtain the properties of the pageContext object
void removeAttribute(String name, int scope) Used to delete the attribute named name in the specified range
void removeAttribute(String name) Used to delete the attribute named name in all scopes
Object findAttribute(String name) Used to find the attribute named name from 4 domain objects

4. Scope of pageContext object

  • pageContextIn the related methods of operating attributes, the parameter name specifies the name of the attribute, and the parameter scope specifies the scope of the attribute.
constant Scope
pageContext.PAGE_SCOPE Indicates page range
pageContext.REQUEST_SCOPE Indicates the request scope
pageContext.SESSION_SCOPE Represents session scope
pageContext.APPLICATION_SCOPE Represents web application scope
  • It should be noted that when calling the findAttribute() method to find the attribute named name, it will be based on page, request, session and application are searched in order. If found, the name of the attribute is returned, otherwise is returned. null.

5. Case demonstration

  • Buildingdemo14.jspScale page
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>演示pageContext对象</title>
    </head>
    <body>
        <%
            // 获取out对象
            JspWriter myOut = pageContext.getOut();
            // 设置page范围内属性
            pageContext.setAttribute("message", "学习Java基础编程", pageContext.PAGE_SCOPE);
            // 设置request范围内属性
            request.setAttribute("message", "学习Java Web开发");
            // 设置session范围内属性
            session.setAttribute("message", "学习Spring Boot框架");
            // 设置application范围内属性
            application.setAttribute("message", "学习大数据实时处理");
            // 获取page范围属性
            String pageMessage = (String)pageContext.getAttribute("message", pageContext.PAGE_SCOPE);
            // 获取request范围属性
            String requestMessage = (String)pageContext.getAttribute("message", pageContext.REQUEST_SCOPE);
            // 获取session范围属性
            String sessionMessage = (String)pageContext.getAttribute("message", pageContext.SESSION_SCOPE);
            // 获取application范围属性
            String applicationMessage = (String)pageContext.getAttribute("message", pageContext.APPLICATION_SCOPE);
        %>
        <%
            myOut.println("page范围消息:" + pageMessage + "<br />");
            myOut.println("request范围消息:" + requestMessage + "<br />");
            myOut.println("session范围消息:" + sessionMessage + "<br />");
            myOut.println("application范围消息:" + applicationMessage + "<br />");
        %>
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo14.jsp
    Insert image description here

(4) exception object

  • Goal: Master the use of exception objects to handle exception information in JSP pages

1. Overview of exception object

  • In JSP pages, it is often necessary to handle some exception information. The exception information can be processed through the exception object. The exception object is an instance object of java.lang.Exception类, which is used to encapsulate the exception information thrown in JSP. It should be noted that the exception object can only be used on the error handling page, that is, the page where the attribute <%@ page isErrorPage="true"%> is specified in the page directive.

2. Case demonstration

  • View the previously created pageerror.jsp
    Insert image description here
  • Buildingdemo15.jspScale page
<%@ page contentType="text/html;charset=UTF-8" language="java"
    pageEncoding="UTF-8" errorPage="error.jsp" %>
<html>
    <head>
        <title>演示页面异常</title>÷
    </head>
    <body>
        <%
            int a = 10;
            int b = 0;
        %>
        <%
            out.print(a + " ÷ " + b + " = " + (a / b));  // 产生异常
        %>
    </body>
</html>
  • Start the server and accesshttp://localhost:8080/JSPDemo/demo15.jsp
    Insert image description here

Guess you like

Origin blog.csdn.net/qq_65584142/article/details/131145105