Detailed description of JSP built-in objects

Source: Internet
Author: User

JSP is based on the Java language, and object-oriented is also a major feature of it. JSP contains a large number of built-in objects and scalable component objects. it can be said that the object is the essence of JSP programming technology. in this chapter, we will introduce JSP objects, focus on JSP built-in objects, describe their functions, and introduce their usage through examples.

Master the usage of built-in JSP objects and the development skills of JSP

Requirements

Flexible application of built-in JSP objects to develop programs

Skills

Introduction to JSP built-in objects

Theory

3.1 objects and built-in objects

Objects are typical things with methods, attributes, and collections.

The object property reflects the object state and can be read or set. The object set is composed of many different attributes and values related to the object.

For a general object, to use it, you must declare a class first, and then instantiate it to get an object that can be used.

The following example shows how to use a common object.

File useobject. jsp _____

Eight default built-in objects in JSP programs

They can be directly used without Declaration. These eight objects are request, response, pagecontext, session, application, out, config, and page.

Page

Instance that processes the current request class on this page

Java.1ang. Object

Page

Page

Servletconfig of this JSP

Javax. servlet. servletconfig

Config

Page

The object that writes content to the output stream.

Javax. servlet. jsp. jspwriter

Out

Application

Servlet context obtained from the servlet configuration object (for example, in the call to getservletconfig () and getcontext)

Javax. servlet. servletcontext

Application

Session

Session object created for the requested customer

Javax. servlet. http. httpsession

Session

Page

Page Context of this JSP

Javax. servlet. jsp. pagecontext

Pagecontext

Page

Response to the request

Java. servlet. servletresponse subclass dependent on the Protocol (for example, javax. servlet. httpservletresponse)

Response

Request

Request to trigger a service call

Yi ?? Java. servlet. servletrequest subclass of the Protocol (for example, javax. servlet. httpservletrequest)

Request

Range

Representative content

Type

Built-in object

3.2 request object

The request object is an instance of servletrequest. when the client requests a JSP webpage, the JSP engine packs the client request information in this request object. The request information includes the request header ), information (such as the browser version information, language, and encoding method), request method (such as HTTP Method: Get, post, put, etc.), Request Parameter Name, the parameter value and the host name of the client, and then the request object is treated as the httpservletrequest parameter value of the jspservice method. Therefore, we can use this object to obtain request information about the client.

3.2.1 method of the request object

Method

Return the port for receiving the request

Getserverport

Returns the Host Name of the server that receives the request.

Getservername

Returns the request URL.

Getscheme

Returns the fully qualified Host Name of the interface program sending the request.

Getremotehost

Returns the IP address of the interface program sending the request.

Getremoteaddr

Returns the actual address obtained from the virtual address using the replacement rule.

Getrealpath

Returns the cached data of the text read from the request body.

Getreader

Returns the protocol and version number of the request.

Getprotocol

Returns the value of a specified parameter listed as a string.

Getparametervalues

Returns the parameter name of this request.

Getparametername

Returns a string containing a single value of a specified parameter.

Getparameter

Returns the input stream for reading binary data in the Request body.

Getlnputstream

Returns the internetmedia type of the request object data.

Getcontentype

Returns the size of the request object data.

Getcontentlength

Returns the character set that is encoded for the request input.

Getcharacterencoding

Returns the attribute value of the name given by the request.

Getattribute

Description

Method

Example of request object usage

1. The request object obtains information about the server and client.

File request1.jsp

2. Use the request object to obtain and process the parameter values passed in the form.

(1) Create an HTML form

(2) Use the get and post Methods

(3) process with the request object

The data entered by the user is stored in the request object and executed using javax. servlet. httpservletrequest. You can directly access the request object in the JSP code and process the data transmitted from the form.

File request3.htm request3.jsp

3. Use the request object to obtain and process the Chinese parameter values passed in the form.

File request2.htm request2.jsp

3.3 response object

The response object type is javax. servlet. the JSP Engine creates a default response object based on the client's request information. it is used to provide browser reference information, such as the response header, response body (HTML content), Server Status Code, and other information to the client.

3.3.1 response object Method

Redirect client address

Sendredirect

Set the HTTP File Header Value of the specified name

Setheader

Send error message to client

Senderror

Determine whether the specified Http File Header exists

Containsheader

Adding an HTTP header will be sent to the client

Addheader

Add a cookie object to save the user information of the client.

Addcookie

Set content type for response

Setcontenttype

Set content length for the response

Setcontentlength

Returns the print program used to format the text response.

Getwriter

Returns the output stream used to write binary response data.

Getcharacterencoding

Returns the mime-encoded character set combination.

Getcharacterencoding

3.3.2 response object usage example

The following sample program provides the function of regularly refreshing pages.

File refresh. jsp

This Program specifies that the page is automatically refreshed every five seconds. The server re-executes this program to generate a new current time and then outputs it to the client. therefore, the time displayed on the page is increased by 5 seconds every 5 seconds, implementing a similar clock function.

The following sample program implements the page redirection Function

File request2.htm

Enter the admin user name to go to the management interface. Otherwise, enter the normal user interface.

3.4 Session Object

Session object is a very important internal object in JSP. We use it to save some specific information that a specific client (visitor) accesses at a time.

In JSP network programming, there are multiple methods to save customer information, but the most common and practical method is the session object.

3.4.1 Introduction to session objects

The Session object is actually the "session" between the server and the client"

(1) The session can be used to store some specific information of the visitor. The host server tracks the information based on the session.

(2) session allows you to create a Visitor Information container.

(3) A session can be used to track the access path of a visitor and mine useful information, such as the interests and objectives of the visitor.

When a user accesses the same page in a web application, the session variable always exists. When the user redirects between pages of the application, the variables stored in the session object are not cleared, of course, you can also use the session method to explicitly end a session and set the timeout period of the idle session.

Session is a built-in object in the JSP program.

Each client has a session object to store data related to this client.

In JSP programs, you can directly use the session object without any Code. However, to confirm, you can add the following code to enable the session function.

If the preceding session value is set to false, the session function is disabled.

The Session object class is httpsession, which provides many usage methods.

3.4.2 method of Session Object

The Session object class is httpsession. httpsession is implemented by the server program and provides sessions between the HTTP server and the HTTP client. A session is a continuous multi-channel connection and request over a given period of time. sessions are used to maintain the status and user authentication in Multi-page requests.

Common Methods of session objects

Remove the object that is connected to the specified name in the session application layer data

Removevalue

Connects the specified object to the application layer data of the session with the specified name.

Putvalue

Check whether the client has participated in the session

Isnew

Invalidate the session and remove it from the context

Invalidate

Returns the name of the application-layer data object connected to the session.

Getvaluenames

Returns the object associated with the specified name in the application layer data.

Getvalue

Returns the context of a session.

Getsessioncontext

Returns the time when the client sent the last message containing the session account.

Getlastaccesstime

Response session ID

GETID

Returns the time when the session was created.

Getcreationtime

3.4.3 Session object usage example

To describe the specific application of the session object, we use three pages to simulate a multi-page web application as an example.

(1) The first page (q1.html) only contains an HTML form that requires the user name to be entered.

File q1.htm

(2)the second page is a jsppage (q2.jsp), extract the thename value in the q1.html form through the requestobject, store it as the name variable, and then save the name value to the Session object. Another task of q2.jsp is to ask the second question.

(3) The Third page is also a JSP page (q3.jsp). The main task is to display the Q & A result, and the other task is to extract user input from the second page and display it.

Generally, session management uniquely identifies a user session by storing sessionid as a cookie in the user's web browser.

If the browser does not support cookies or sets the browser to reject cookies, we can rewrite the URL to implement session management.

File hello1.jsp

Use the session object to save information in three different JSP files

File example0.htm (a number is required in accountbalance)

3.5 Application Object

The application object stores some common data in an application system. compared with Session objects, application objects are shared by all customers, while session objects are dedicated to each customer. the application object can be javax. servlet. servletcontext type. the servletcontext interface allows the servlet to access information about its environment. the range of the Application object is application.

3.5.1 method of Application Object

Method

Set a property value of an Application Object

Setattribute

Obtain information about the servlet compiler of the current version.

Getserverinfo

Returns the value of an attribute of the application.

Getinitparameter

Returns the attribute names of all application objects in the form of enumeration data.

Getattributenames

Returns the attribute value of the Application Object of the corresponding name in the form of an object.

Getattribute

Description

Object

3.5.2 example of application object usage

A counter that uses the Application Object

File appcount. jsp

Use the built-in application object to change the session example above to the application example.

File application1.htm

3.6 out object

The out object is used to output data. It can be an instance of javax. servlet. jsp. jspwriter. The out object range is page.

From Java. io. the common abstract class jspwriter extended by writer imitates Java. io. bufferedwriter and Java. io. some functions in printwriter. however, the difference is that it will throw (throw) Java in the printing method. io. ioexception exception, but printwriter does not.

The out object in JSP is of this type. if the page command selects autoflush = "true", when the buffer overflow occurs because the current operation does not clear the cache, all I/O operations of this class will automatically clear the buffer content. if autoflush = "false", when the operation causes a buffer overflow, All I/O operations of this class will throw an ioexception.

3.6.1 variables of the out object

Autoflush

Type: protected Boolean autoflush

If the variable value is true, the buffer is cleared when the current operation causes a buffer overflow.

If the variable value is false, an ioexception is thrown if the current operation causes buffer overflow.

Buffersize

Type: protectedintbuffersize

The current size of the buffer. The initial value varies with devices, but not less than 8 KB.

Default_buffer

Publicstaticfinalintdefault_buffer type

Indicates the default buffer size setting that writer is using.

No_buffer

Public static final int no_buffer type

Indicates whether the writer is in the cache output status.

3.6.2 out object Method

Method

Print an object

Object

Print

Print a long integer

Long

Print

Print an integer

Int

Print

Print a floating point number

Float

Print

Print a double-precision floating point number

Double

Print

Print a character array

Char []

Print

Print a character

Char

Print

Print a Boolean Value

Boolean

Print

Write a line Separator

_

Newline

Obtains the current autoflush value.

_

Isautoflush

Obtain the number of unused bytes in the buffer.

_

Getremaining

Obtain the buffer size.

_

Getbuffersize

Clear the buffer stream

_

Clearbuffer

Clear buffer content

_

Clear

Output stream

_

Flush

Close the stream and Output

_

Close

Description

Parameters

Method

Print a string and end the line

String

Println

Print an object and end the row

Object

Println

Print a long integer and end the row

Long

Println

Print an integer and end the row.

Int

Println

Print a floating point number and end the row

Float

Println

Print a double-precision floating point number and end the row

Double

Println

Print a character array and end the row

Char []

Println

Print a character and end the line

Char

Prinfln

Print a Boolean value and end the row

Boolean

Println

End the current row by writing a line Separator

_

Println

Print a string

String

Print

3.6.3 usage example of the out object

Output a variety of different types of data with an out object, including the output of Chinese Characters

File out. jsp

3.7 other objects

Pagecontext object

The pagecontext object is javax. servlet. JSP. an instance of the pagecontext class. the pagecontext object provides all attributes and methods required for JSP program execution, such as Session, application, config, and out. for a pagecontext object, its range is page.

Page Object

The page object is Java. lang. object type. It is an instance of the implementation class for processing the JSP page of the current request. the page object can be seen as a synonym for "this" in the page body. the range of the page object is page.

Config object

The Config object is of the javax. servlet. servletconfig type. It provides the scope of the servletcontext object. config object for accessing the initial servlet class parameters and server environment information.

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.