Detailed explanation of Java Web (V) JSP (four scopes, nine built-in objects, etc.)

We explained the servlet earlier, learned about the inheritance structure and life cycle of the servlet, and learned more about the ServletConfig and ServletContext objects in it. However, we will find that it is very inconvenient to write some HTML code in the servlet. We need out every time println(HTML); Therefore, JSP appears to solve this problem. The content of JSP is HTML, but Java language can be nested. Now let's learn more about JSP.

                                  --WZY

1、 JSP

1. What is JSP?

JSP (Java Server Pages): it is a dynamic web page development technology based on Java language,

Features:

Servlet features: embed HTML source code in Java source code

JSP features: embed java code in HTML source code

JSP is servlet

1. After Tomcat obtains the JSP file, it first converts the JSP into a servlet and becomes XXX Java (servlet source code),

            D:\java\tomcat7. 0\apache-tomcat-7.0. 53\apache-tomcat-7.0. 53\work\Catalina\localhost\test01\org\apache\jsp

          |------------------------------------------------------------------------|   |---------|----------|-------|-----------------|

Under the fixed package name of the Tomcat installation directory engine host project is the servlet file that stores the JSP Java and compiled files class 

2. Tomcat compiles java files into class files

3. Tomcat runs the class file and outputs the results to the browser,

Example:

Create a JSP. View its converted servlet code.

          NewFile. jsp          

          NewFile_ jsp. java          

You can see the public final class newfile_ jsp extends org. apache. jasper. runtime. HttpJspBase implements org. apache. jasper. runtime. JspSourceDependent

            NewFile_ jsp. Java inherits from httpjspbase. Let's take a look at the source code of httpjspbase

          HttpJspBase. java         

          public abstract class HttpJspBase extends HttpServlet implements HttpJspPage

We see a familiar class, httpservlet. When we write a servlet, we inherit from this class. Here, we also inherit httpservlet. Moreover, the source code of httpjspbase will find that the life cycle also has init () method, service () method and destruction () method, which is equivalent to_ The jspservice () method is the execution of the service () method of the servlet, so JSP is also a servlet.

All HTML code we write in JSP will be converted into out. HTML in servlet Write (HTML) code to output. Look at the picture

Summary:

For the servlet source code converted from JSP, we will analyze it in detail later. Now we only need to know what and where the content in JSP is converted in servlet. Among them_ The details of the jspservice () method are explained below

Note: JSP generates java source code. It is generated for the first time by default and then executed directly, unless the content is modified. Specifically, because JSP will only be compiled when the client requests it for the first time, it will feel slow when requesting JSP for the first time, and the subsequent requests will not compile JSP, so the speed is much faster, If the compiled class file of the JSP saved by Tomcat is deleted, Tomcat will recompile the JSP. When developing web programs, it is often necessary to modify the JSP. Tomcat can automatically detect the changes of the JSP program. If it detects that the JSP source code has changed, Tomcat will recompile the JSP the next time the client requests the JSP without restarting Tomcat. This automatic detection function is enabled by default, and detecting the changes will consume a small amount of time, When deploying a web application, you can Turn it off in XML. This is why we can modify the content directly on the JSP page without restarting the server.

Because JSP is a servlet, the life cycle is the same as Serlvet.

One difference between JSP and servlet is that JSP is deployed before compilation, while servlet is compiled before deployment.

2、 JSP syntax

JSP template data:

It is the HTML code in JSP. Its content is fixed. No matter how the program runs, the template data will not change when it is output to the client browser. When we create a JSP, the template has been fixed.

Element: the Java part of JSP, including script (JavaScript, or Java code), JSP directive and JSP tag. The element determines the process of the program, and the element will not be displayed to the browser. These will be explained later

JSP script:

1. Use <% to write java code% >. The intermediate java code must follow Java syntax,

Why can I use out output? This involves the nine built-in objects of JSP, which will be explained later. When you look back here, you will know why you can use it.

Let's see how the code is written when JSP becomes a servlet.

JSP instructions in JSP (described later):

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

This code becomes

                response. setContentType("text/html; charset=UTF-8");// This code means to inform Tomcat and the browser to use UTF-8 code table, and the data type sent back to the browser is text / HTML. This is the code transformation of the red part in the JSP instruction, and the pageencoding = "UTF-8" in the instruction means that the UTF-8 code table coding is adopted when the JSP is converted into a servlet, because the JSP may contain Chinese.

For JSP template data, use out as it is Write() to output to the browser

For JSP elements, they will become ordinary java code, because java code can be written directly in servlets.

2. Use <% = XXX% > to output results

Use <% = result% > to output the result, which will be converted to out in the servlet Print (result) for output. Output various types of data: int, double, Boolean, string, object, etc

3. JSP comments

<% ---% >: JSP comment,

/ /: Java single line comment

/ * * /: Java multiline comment

           : this comment will be sent to the source code on the browser side

How are the comments displayed in the servlet?

JSP comments will not be displayed in the servlet file, while Java comments will, but all their comments will not appear in the source code when they reach the browser, only This comment will go to the web source code of the browser

4. Methods and attributes (global variables) declared in JSP use <%! Method, attribute% >

This is not demonstrated, that is, when writing methods or attributes in JSP, use <%!% > Wrap it up.

5. You can use if statement in JSP, or use for loop, while loop, etc., that is, you can write a script.      

3、 JSP instruction

Instructions are used to declare some attributes of JSP pages, such as coding method and document type. We will also declare the encoding method we use and the document type of response in the servlet, and JSP is declared with instructions. We also mentioned an instruction above, that is, the page instruction,

JSP instruction format: <% @ directive {attribute = value} *% >

Explanation:

Directive: instruction name, such as page instruction

Attribute = value: the attributes immediately following the instruction name are written in the form of key value pairs

*: represents that 0 or more attributes can be followed.

For example: page instruction: used to declare the attributes of JSP pages.

<% @ page language = "Java" contenttype = "text / HTML; charset = UTF-8" pageencoding = "UTF-8"% > the page instruction is followed by three attributes: language, contenttype and pageencoding. These are just a few attributes, but they are not completely written. The attributes allowed by the page instruction are shown in the following table

Attribute name value range description

Language Java is the language used to interpret the JSP file. It is generally Java language, and the default is Java

Extends the full name of any class. When compiling the JSP file, which class to inherit, JSP is a servlet. Therefore, when indicating the inheritance of ordinary classes, you need to implement the init, destroy and other methods of the servlet

Import any package name and class name. Import is the only page instruction attribute that can be declared multiple times. An import can reference uogelei, separated by English commas,

For example, <% @ page import = "Java. Util. List, Java. Util. ArrayList"% >

Session true, false whether there is a built-in session object in the JSP. If true, there is a built-in session object, which can be used directly. Otherwise, it defaults to true

Autoflush true, false whether to run cache. If true, use out The string output by methods such as println () does not arrive at the client server immediately, but is temporarily stored in the cache, which is full

Either the program is finished or out The client can only be accessed when the flush() operation is performed. The default value is true.

Buffer none or number KB specifies the cache size, which is valid when autoflush is set to true, for example <% @ page buffer = 10KB% >

Isthreadsafe true, false is thread safe. If true, multiple threads will be run and the JSP program will be run at the same time. Otherwise, only one thread will be run and the other threads will wait. The default is false

Iserrorpage true, false specifies whether the page is an error display page. If true, the JSP has an exception object exception built-in, which can be used directly. Otherwise, it is not, and the default is false

Errorpage the relative path of a JSP page indicates an error page. If the JSP program throws an uncapped exception, go to the page specified by errorpage. The page specified by errorpage usually

The iserrorpage property is true, and the built-in exception object is an uncapped exception

Contenttype is a valid document type. The client browser judges the document type according to this attribute. For example, the HTML format is text / HTML, the plain text format is text / plain, the JPG image is image / jpeg, the GIF image is image / GIF, and the word document is application / msword, This attribute is often used together with the charset setting code to notify the server and browser to use the same code table

Info any string indicates the information of JSP, which can be passed through servlet Getservletinfo() method gets

Trimdirective whitespaces true, false whether to remove the white space characters before and after the instruction. The default is false

Pageencoding, UTF-8, iso-8859-1, etc. specify a code table to encode the JSP page,

Include instruction

Relatively simple, there is only one form <% @ include file = "relativeurl"% > relativeurl: the path of another JSP file or HTML file in the application. For example, all pages in the website have a unified style navigation bar and footer copyright, so you can use this instruction to include it

Features: the include instruction will add the source code containing the page to the page using the include instruction, and then compile it into a class file. A JSP behavior that will be discussed later, < jsp: include page = "relativeurl" > has the same function as the include instruction, but the difference is that the include behavior is to execute the included page separately at runtime, Then include the execution results on this page, which belongs to run first and then include.

Taglib instruction

JSP supports tag technology. The usage of tags and the use of JSTL tag library will be discussed later,

Function: used to indicate the JSP tag library used in the JSP page. The taglib instruction has two attributes. URI is the address of the class library and prefix is the prefix of the tag

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

4、 JSP behavior

We talked about the JSP syntax, and introduced the contents and functions of JSP pages, just two things, module data and elements. The elements include scripts, instructions and tags. Scripts are java code embedded in JSP. The role of instructions is to declare the attributes of the page. What are the tags? Tags are divided into JSP built-in tags, and JSP tag library or user-defined tags through taglib instructions. Now let's talk about some JSP built-in tags.

JSP built-in tags are called JSP actions. As long as you write little tag code, you can use the rich functions provided by JSP. JSP behavior is actually the abstraction and encapsulation of commonly used JSP functions. It can replace JSP scripts and make JSP have less places to embed java code.

Format: < jsp: elements {attribute = "value"} * / >

Jsp: prefix of the tag, indicating that it is a built-in tag of JSP,

Elements: the name of the behavior,

Attribute = value: use key value pairs to write attributes

*: 0 or more attribute pairs can be specified

< jsp: Include / > behavior

The include behavior is used to include a file at runtime. If the included file is a JSP program, the JSP program will be executed first, and then the execution results will be included. The function is the same as the include instruction. The only difference is that the include instruction adds the source code of the included file to the JSP program, and then compiles it. It belongs to static inclusion, while the include behavior only includes the operation results of the included file into itself. Dynamic inclusion

Java bean behavior

It is a group of behaviors related to Java beans, including usebean behavior, setproperty behavior, getproperty behavior, etc

Java beans are ordinary Java classes, also known as POJOs. There are only private attributes and corresponding getter and setter methods. Note that when the private attribute is of boolean type, it is customary to write the getter method as isxxx(); Instead of getxxx();

Usebean behavior

< jsp: usebean id = "beanobject" class = "classname" scope = "value" > function: define a java bean object in JSP

ID: indicates the name of the Java Bean object, which can be used in JSP to refer to the Java Bean object, which is equivalent to taking a variable name for the new object,

Class: the full name of the java bean class

Scope: there are only four scopes that can be written for the Java Bean object, that is, the four scopes of JSP, page, request, session and application

Page: it can only be used in the current JSP page. If it is not in the JSP page, it will become invalid

Request: as I learned earlier, if page a requests to be forwarded to page B, then the same request is used, then both pages a and B are the scope of the request, that is, the pages forwarded through the request are its scope

Session: the scope should be read and accessed anywhere under a web project, as long as the cookie is not closed and the access path set by the cookie is "/",

Application: in fact, it is the ServletContext in the servlet, which can be accessed by all projects under the server.

Setproperty behavior

          

Set the properties of the Java Bean object

Name: the name of the Java Bean object, that is, the ID in the usebean behavior

Property: the name of the property in the object,

Value: the value whose attribute is to be assigned

Getproperty behavior

          

Gets a property value of a JavaBean object

Name: the name of the Java Bean object, that is, the ID in the usebean behavior

Property: the property name of the object

Example: JavaBean: user java  NewFile. jsp

      User. java

      NewFile. jsp

You can view newfile The source code after the JSP is changed into a servlet. Let's see what kind of statements the JavaBean behavior we write will be converted into

One of the nine built-in objects of JSP, pagecontext, appears here. To put it simply, pagecontext is the manager (context) of JSP pages. The getattribute (name, scope) method is used to obtain the data in the specified scope. If the getattribute (name) method is used, it operates on the page scope by default, and findattribute (name) obtains the content from page, request, session and application in turn.  

The first red box represents our usebean behavior. A judgment is made that if the user object cannot be found in the page scope, a new one will be created, otherwise the found user object will be used,

The second red box represents our setproperty behavior. First find the user object, and then assign its property

The third red box represents our getproperty behavior, which is to find the user object first, and then obtain the value of its property.

Note: for the behavior of Java beans, one feature is that when the requested parameters correspond to the properties of Java beans, all values can be set at one time

< jsp: setproperty name = "user" property = "*" / > / / set all properties of user. The property value is automatically obtained from the request, and * represents all properties.

< jsp: forward / > behavior

Realize the request forwarding function through request. In the servlet getRequestDispatcher("someServlet"). forward(request,response); The same function can be realized in JSP, but the < jsp: forward / > behavior is used. In fact, the forward behavior encapsulates it.

Format:

        

           

           

        

Page: the page to jump to or servlet, < jsp: param / > parameter behavior, with some parameters. Name and value are brought in the form of key value pairs

For example:

         NewFile. jsp

         MyServlet. java

Access: http://localhost:8080/test01/NewFile.jsp

The browser address bar has not changed, indicating that it is a request for forwarding

         NewFile_ jsp. java

The advantage of using return is that after the above forwarding, you can directly return. There is no need to execute the following code. The URLEncode is used to encode the parameters, indicating that the < jsp: param / > can be passed directly to Chinese, but the premise is to set request setCharacterEncoding("UTF-8"); Why? Look at the code in the box above.

< jsp: directive / > behavior

The directive behavior is equivalent to JSP instructions, such as < jsp: directive Page / > is equivalent to the <% @ page% > instruction. Other instructions have the same writing format.         

5、 Nine built-in objects and four scopes hidden by JSP

Before that, a large section of content was to explain what JSP is and what the content in JSP is. We should know almost here, but we also need to understand some things deeply. We know that there are only two kinds of content in JSP, template data and elements. Elements include instructions, scripts and tags (behavior), The script will slowly be replaced by all tags, that is, java code will not be embedded in JSP, but we also know that JSP will be converted into servlet. In servlet, when outputting data, we need to pass response getWrite(); But in JSP, the out object is directly used for output. Why? This is because out is a hidden object of JSP. Nine hidden objects are built in JSP, which makes JSP easier and more convenient to use than servlet,

    page、config、application、request、response、session、out、exception、pageContext

Page: the page object represents the current JSP page and is the object of the servlet class compiled by the current JSP. Equivalent to this.

Config: identifies the servlet configuration. Type: ServletConfig. The API is the same as the ServletConfig object in the servlet. It can obtain some configuration information of the servlet and ServletContext

Application: identifies the web application context. Type: ServletContext. See the use of ServletContext in the servlet for details

Request: request object, type: HttpServletRequest

Response: response object type: httpservletresponse

Session: refers to the technology of recording user information on the server side in a session

Out: output response body type: jspwriter

Exception refers to the object with exception, which is of type throwable. We talked about it when we introduced an errorpage attribute in the page instruction above

Pagecontext: indicates the JSP page context (JSP manager). Type: pagecontext

Objects marked in red are unique to JSP, and others are old things in servlets.

In the file converted from JSP to servlet, only 8 built-in objects can be seen, with the exception object missing. Because we said an iserrorpage attribute in the page instruction, which is false by default and closed, there is no exception object in it.

The four scopes of jsp: page, request, session and application

These four scopes are actually four of the nine built-in objects. Why are they also the four scopes of JSP? Because these four objects can store data, such as request Setattribute() note and request Setparameter () is distinguished from session. One is stored in the domain and the other is the request parameter SetAttribute () and application are actually serlvetcontext. Naturally, there are setAttribute () methods. The operation of the page scope depends on the pagecontext object. We also mentioned the four scopes of JSP,

Page scope: represents that the variable can only take effect on the current page

Request: represents that the variable can take effect in a request. A request may contain one page or multiple pages. For example, page a requests to be forwarded to page B

Session: the representative variable can take effect in a session, which is basically valid under Web projects. The use of session is also closely related to cookies. Generally speaking, as long as the browser is not closed, the cookie will always take effect. When the cookie takes effect, the use of session will not be affected.

Application: the representative variable can be used in one application (multiple sessions) and among multiple projects under the server. For example, Baidu, Wenku and other shared accounts.

Out object:

Type: jspwriter

The bottom layer of JSP output uses response getWriter(); What do you mean? Here we will explain JSP cache and servlet cache. The output process is like this

After the JSP page is converted into a servlet, the out object used is of type jspwriter, so the data to be sent will be stored in the JSP output cache first. Then, when the JSP output cache is full, it will be automatically refreshed to the servlet output cache. When the servlet output cache is full, or the program ends, it will be output to the browser. Unless manually out flush()。

Verify that the servlet output cache and JSP output cache are correct as we mentioned above.

Analysis: if there is no JSP cache and servlet cache, the output result should be aaaabbbbcccc, but the output is bbbbaaaacccc. Why? According to the principle mentioned above, the out object is output to the JSP cache first, so AAAA adds the JSP cache and response getWriter(). Print ("BBBB") directly outputs the BBBB to the servlet cache, and then uses the out object to output the CCCC to the JSP cache. At the end of the program, there is a BBBB in the servlet cache, and then the JSP will refresh the contents of the cache to the servlet cache. The Serlvet is bbbbbbaaaacccc, and then to the browser to get our output results. If the comment is removed in line 12, what will be the output? The answer is aaaabbbbcccc, and the process analyzes itself.

Pagecontext object: focus

This function is more powerful and powerful. It basically has everything. Because it is the manager (context) of JSP pages, it can obtain all the built-in objects in JSP. The following describes its API.

1. Get the other eight built-in objects getxxx()

          pageContext. getOut(); / / get out object

          pageContext. getApplication(); / / obtain the application object

Wait

2. Operate on the properties of the scope (four scopes)

Operate on the properties of the default scope. page

          pageContext. getAttribute(name); / / get page scope data

          pageContext. setAttribute(name,value); / / set the content for the page scope

          pageContext. removeAttribute(name); / / remove content for page scope

3. Operate on the properties of the specified scope

          getAttribute(name,scope); / / obtain the data in the specified scope

          setAttribute(name,value); / / set the content for the specified scope

Removeattribute (name, scope) removes the content of the specified scope (page / request / session / application)

4. Provide scope constants

          PageContext. PAGE_ SCOPE  page

          PageContext. REQUEST_ SCOPE  request      

          PageContext. SESSION_ SCOPE  response

          PageContext. APPLICATION_ SCOPE  application

5. Obtain the specified name content at one time

          findAttribute(name); / / get the content from page, request, session and application in sequence

Response object:

It's the response object. If you don't understand it, take a look at the chapter explaining request and response

Config object:

Type: ServletConfig

It can obtain the initialization parameters of the servlet, the ServletContext object and the servletname

For API details, see the section explaining servlets

Exception exception object:

Contains information about the exception

To use it, you must combine the iserrorpage attribute and the errorpage attribute in the page directive.

        exception. JSP throws a nullpointexception of the exception and jumps to error The errorpage attribute of the JSP error display page means that if an uncapped exception occurs, it will jump to error JSP page

        error. If the JSP iserrorpage property indicates that the page is an error display page, you can use the exception object

Visit http://localhost:8080/test01/exception.jsp

6、 Summary

Through a lot of learning above, we should know these things

1. What is JSP?

JSP is essentially a servlet, because it is too troublesome for servlet to output HTML, so there is JSP. JSP is specially used to write HTML. Of course, java code can also be written.

2. What does JSP include?

Template data and elements. The elements include scripts (Java code), instructions (page attributes), and behaviors (tags, which are derived from Java code in order not to embed so much in JSP)

3. Which are the nine built-in objects in JSP?

Nine built-in objects: page, config, application, request, response, session, out, exception and pagecontext

4. Relationship between the nine built-in objects and objects in servlets

Page is the servlet object itself, that is, this

Config -- ServletConfig in Servlet

Application -- ServletContext in Servlet

Request -- request in Servlet

Response -- response in Servlet

Session -- session in Servlet

      out  -- JspWriter

Exception -- exception object

Pagecontext -- indicates the JSP page context (JSP manager) type: pagecontext,

The pagecontext object is the most awesome. With it, you will have the world. Ha ha~

5. Four scopes in JSP.

      page、request、session、application

The operation of the attributes in the page field requires the help of the pagecontext object.

6. There are two other large pieces of content in JSP

One is El expression, which is very important,

The other is the use of JSTL tag library, which is also very important. It will be explained in the next two sections. Coming soon.

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>