Nine built-in JSP objects

Source: Internet
Author: User
Tags error status code

Nine built-in JSP objects

Although SpringMVC + AJAX is basically used to develop Java Web, it is necessary to know about nine built-in JSP objects. Objects such as request, response, and session are frequently used even when other frameworks are used. Therefore, it is necessary to understand.

These objects can be called on JSP pages without prior definition, which makes JSP programming more convenient and convenient. In fact, these built-in objects correspond to a Servlet class. After JSP is translated into Servlet, these built-in objects are converted into corresponding class instances.

The following nine built-in objects are used in JSP:

Request built-in object response built-in object page built-in object session built-in object application built-in object out Built-in object exception built-in object config built-in object pageContext built-in object

In jsp development, many request, response, session, and out objects are used.

The following describes the introduction and use of each object.

1. built-in request object

The built-in request object is one of the most commonly used objects. It represents the objects of the java. servlet. HttpServletRequest class. The built-in request object contains information about browser requests and provides multiple methods for obtaining cookie, header, and session data.

Common request object Methods

The request object is mainly used for client request processing. The methods contained in this object include:

The request object is mainly used for client request processing. The methods contained in the object include getMethod (): the name of the method used in the returned HTTP request information; getServletPath (): return the URL part of the Servlet call in the request information; getQueryString (): returns the query string after the URL in the http get request information; getContentType (): returns the MIME type of the Request Entity; getProtocol (): return the protocol name and version number in the request information; getPathInfo (): returns information about any path; getServletName (): returns the server host that accepts the request; getServletPort (): return the server port number; getRemoteHost (): return the standard name of the client that submitted the request; getRemoteAddr (): return the IP address of the client that submitted the request; getScheme (): the format (Protocol) name used by the returned request; getParamete R (): return the parameter value submitted by the client through the form. For example, request. getParameter ("myname") can be used to obtain the myname parameter passed by the client. GetContextPath (): return the part indicating the request context in the HTTP request. GetHeaderNames (): returns an enumeration type, which contains all the request names contained in the request. GetAuthType (): returns the name of the authentication mode used to protect the Servlet. For example, BASIC, SSL, or NULL (not protected ). GtRequestURL (): return the URL section of the first line in the HTTP request information from the protocol name to the query string. For example http://www.zzbsite.com/helloworld ? Name = johnson & age = 20, this method will return http://www.zzbsite.com/helloworld String. GtCountLength (): return an integer, indicating the length of the Request Entity (in bytes ). GtUestPrincipal (): returns the Principal object of the java. security class, which contains the name of the currently authorized user. IUserInRole (String role): returns a Boolean value indicating whether an authorized user is included in a specific logical role. GtRemoteHost (): if the user has been authorized, the Registration Name of the user who submitted the request is returned. Otherwise, a NULL value is returned.

Examples of common request methods

The following provides an example to help you understand common call methods in the built-in request object. Create a request. jsp file. The detailed source code of this file is as follows:

<%@ page contentType="text/html;charset=GBK" %>
Return the name of the method used in the HTTP request information: <% = request. getMethod () %>
The URL part of the Servlet call in the returned request information: <% = request. getServletPath () %>
Return the query string after the URL in the http get request information: <% = request. getQueryString () %>
The MIME type of the returned request object: <% = request. getContentType () %>
The protocol name and version number in the returned request information: <% = request. getProtocol () %>
For any path information: <% = request. getPathInfo () %>
Return the server host that receives the request: <% = request. getServerName () %>
Return server port: <% = request. getServerPort () %>
Return the canonical name of the client that submitted the request: <% = request. getRemoteHost () %>
Return the IP address of the client that submitted the request: <% = request. getRemoteAddr () %>
Name of the mode (Protocol) used in the returned request: <% = request. getScheme () %>
Return the request value. Submitted value: <% = request. getParameter ("myname") %>

Program Description: The getParameter () method in the request is the most common. Use this method to obtain the parameter values submitted on the previous page. Here, the page submits a myname parameter to this page, and CALLS request. getParameter ("myname") to obtain this parameter value. Other request methods on the page are used to obtain various request information.

2. response built-in object

The response object corresponds to the request object, which is used to respond to the customer request and output information to the client. Response is the object of the javax. servlet. HttpServletResponse class.

Common Methods for response objects

The response object provides multiple methods for processing HTTP responses. You can call the methods in response to modify the MIME type in ContentType and implement page Jump,
Common methods are as follows:

SetContentLength (int len): This method is used to set the length of the response header. SetContentType (String type): used to set the MIME type in the HTTP Response's contentType, which can contain character encoding rules. For example, you can set contentType to "text/html; charset = GBK ". This method needs to be called to set the content in the compiling process of Servelet. However, in JSP, the page command is generally used to directly specify the contentType attribute. GetOutputStream (): This method returns the output stream of a Servlet. Used to write binary data in the response. The Servlet container does not encode binary data. GetWriter (): This method returns a PrintWriter object, which is frequently used during Servlet compilation. In JSP files, getWriter () the created PrintWriter object's implicit object, so you can directly call the out object for output response. GetCharacterEncoding (): This method obtains the encoding type used for the response. SendError (int status): sends an error message to the client using the specified error status code. SendError (int status, String message): Use a custom error status code and description to send an error message to the client. SendRedirect (String location): locates the request on a different URL (page. This method is often used in actual development. SetDateHeader (String headername, long date): sets the specified header name and date as the response header information. The date is represented by the long value, which is the number of milliseconds from the beginning of the new era. ContainsHeader (String name): checks whether the specified header information exists. Returns a Boolean value. SetHeader (String headername, String value): This method uses the specified header name and the corresponding value to set the header information. If this header is already set, the new value overwrites the old one. If the header information has been sent, the settings of this method will be ignored. Addheader (String headername, String value): adds the specified header name and corresponding value to the header information. AddIntHeader (String headername, int value): sets the specified header name and integer as the header information. If the header information has been set, the new setting value overwrites the previous one. SetStatus (int SC): code that sets the status for the response. SetStatus (int SC, String sm): sets the status code and information for the response. This is used when there is no error.

Among these methods, getWriter () and sendRedirect (String location) are most frequently used in actual development. GetWriter () is often used in Servlet compiling.

GetWriter () method instance of the response object

In server-side Servlet files, the getWriter () method is often used to obtain a PrintWriter object, and the println () method is called to output content to the client. The following Servlet code example:

Package com. helloworld; import java. io. printWriter; // introduce the PrintWriter class import javax. servlet. http. httpServletResponse; // introduces the HttpServletResponse class public class PrintHTML {// Method for printing HTML code public static void printHTML (HttpServletResponse response) throws Exception {PrintWriter out = response. getWriter (); // call the getWriter () method in the HttpServletResponse class. Out. println (""); out. println (""); out. println ("
This is an example of the getWriter () method in the HttpServletResponse class.
"); } }

Program Description: The Java code dynamically returns a simple HTML page to the client.
Note: On the JSP page, response is an object of the HttpServletResponse class. You can directly use response to call all methods in the HttpServletResponse class on the JSP page.

Page redirection instance

Next, we will use an example to better understand the sendRedirect (String location) method for page redirection. Create an index4.jsp file in the helloworld module:

<%@ page language="java" contentType="text/html;charSet=GBK" %>
Response. sendRedirect () Example <% String pg = request. getParameter ("pg"); // get the Pass Parameter pg if ("1 ". equals (pg) // If pg is equal to 1 response. sendRedirect ("hello. jsp "); // The page is redirected to hello. jsp else if ("2 ". equals (pg) // If pg is equal to 2 response. sendRedirect ("goodbye. jsp "); // The page is redirected to goodbye. jsp else // otherwise, page redirection is not performed, that is, the page out is displayed. println ("Page redirection not performed"); %>

Program Description: there is a drop-down menu on the page. Select the page to jump. The request built-in object obtains the passed parameter value through the getParameter () method. The response object then calls the sendRedirect () method based on the parameter value for page Jump.

The redirected hello. jsp page code is as follows:

 
<%out.print("  
Hello!  
");%>  

Goodbye. jsp page code:

 
<%out.println("  
Goodbye!  
");%> 3. built-in page objects 

The page object is similar to the this pointer in Java programming, that is, the current JSP page itself. Page is the Object of the java. lang. Object Class.

Common Methods for page objects

Common built-in page Object methods include:

GetClass (): return the class of the current Object. HashCode (): returns the hash code of this Object. ToString (): converts the Object class to a string. Equals (Object o): checks whether the Object is equal to the specified Object. Copy (Object o): copy the Object to the specified Object. Clone (): This object is cloned.

Because built-in page objects are not frequently used in actual development, other methods of page objects are not listed here.

Examples of common page Methods

The following is an example to better understand the use of built-in page objects. Create a page. jsp file. The detailed source code is as follows:

<%@ page language="java" contentType="text/html;charSet=GBK" %><%@ page import="java.lang.Object" %>
Page built-in object instance <%! Object obj; %> <! -- Object declaration --> getClass: <% = page. getClass () %>
HashCode: <% = page. hashCode () %>
ToString: <% = page. toString () %>
Equals: <% = page. equals (obj) %>
Equlas2: <% = page. equals (this) %>
Iv. session built-in objects

A session is a request-related session. It is a java. servlet. http. HttpSession object used to represent and store the request information of the current page.

In the actual Web application development process, we often encounter the following problem: Session status maintenance. Of course, there are many ways to solve this problem, such as Cookies, hidden form input fields, or directly attaching status information to URLs. However, these methods are inconvenient to use.

Java Servlet provides an HttpSession object that can be continuously valid between multiple requests. This object allows users to store and extract session state information. JSP also supports this concept in Servlet. The session built-in object in JSP corresponds to the HttpSession object in Servlet. When the Web application system wants to complete a transaction through multiple pages, session usage is very useful and convenient.

Common Methods of session objects

The common methods of built-in session objects are as follows:

GetId (): This method returns unique identifiers generated for each session. When only one single value is associated with a session, or when the log information is related to the previous sessions, it is used as a key name. GetCreationTime (): return the time when the session was created. The minimum unit is 1‰ seconds. To obtain a value that is useful for print output, you can pass the value to the Date constructor or GregorianCalendar method setTimeInMillis. GetLastAccessedTime (): return the time when the session was last sent by the customer. The minimum unit is 1‰ seconds. GetMaxInactiveInterval (): Total time (seconds) returned. A negative value indicates that the session will never time out. GetAttribute (String key): obtains the corresponding information stored in the session with the given keyword. For example, Integer item = (Integer) session. getAttrobute ("item "). SetAttribute (String key, Object obj): provides a keyword and an Object value, which then exists in the session. For example, session. setAttribute ("ItemValue", itemName ).

Generally, a 30-minute expiration time is set on the server. When the client stops the operation for 30 minutes, the information stored in the session will automatically expire.

In addition, readers should note that the stored and searched information in the session cannot be basic types, such as int and double, but must be objects corresponding to Java, such as Integer and Double.

Q & A operation example

Next, this book will create three pages to simulate a multi-page Web application, so that readers can have a deep understanding of session usage. The first page (session1.jsp) only contains an HTML form that requires the user name to be entered. The Code is as follows:

<%@ page contentType="text/html;charSet=GBK" %>
User name input page
Program Description: Pass

The second page (session2.jsp) needs to get the username parameter value in the session1.jsp page through the request object and save it in the session. The session object stores information in a hash table. Another operation of session2.jsp is to ask the second question. The specific code is as follows:

<%@ page contentType="text/html;charSet=GBK" %>
Answer page <% String username = request. getParameter ("username"); // get the passed parameter username session. setAttribute ("theusername", username); // saves the user name in the session. String can be used as the object %>

Your username is: <% = username %>

What do you like:
Program Description: Use the getParameter () method in the built-in request object to obtain the parameter value passed on the session1.jsp page, and use setAttribute () in the session object () in this way, the user name is stored in the session hash table as an object. You need to specify the keyword theusername. In addition, use

The main task on the third page (session3.jsp) is to display the answer result. The Code is as follows:

<%@ page contentType="text/html;charSet=GBK" %>
Show answer <%! String food = ""; %> <% food = request. getParameter ("food"); // get the food parameter value String name = (String) session. getValue ("theusername"); // retrieves the object with the keyword theusername from the session. %> your Username: <% = name %>
You like to eat: <% = food %>

Program Description: Use the keyword theusername to get the user name using the getAttribute (String key) method in the session object, and display the user name and the answer to the second question.

Session built-in objects are frequently used. For example, you can use session to store user information and determine whether a user has logged on to the session based on whether the user object in the session is empty. Therefore, readers must be familiar with the use of this object.

5. built-in application objects

Application is an instance of the javax. servlet. ServletContext class object. It is used to share data between users (mostly used in online chat systems ).

Difference between application object and session Object

It is similar to the session built-in object introduced in the previous section. However, there are differences between them. Generally, a user corresponds to a session, and the information in the session disappears as the user leaves, therefore, the session between different customers must ensure that at least one customer does not terminate the session at a certain time point. applicat is different and always exists, similar to the system's "global variable ", there is only one instance.

Common methods of application objects

Common Methods for built-in application objects are as follows:

GetAttribute (String key): return the information required by the user using a keyword. The return type is Object, similar to the getAttribute (String key) method in session. GetAttributeNames (): returns all available attribute names. The return type is Enumeration ). SetAttribute (String key, Object obj): stores an Object and specifies a keyword. RemoveAttribute (String key): deletes the information of an object using the keyword. GetServletInfo (): returns information about the JSP Engine. GetRealPath (String path): returns the real path of the virtual path. GetContext (String URLPath): returns the application object for executing the Web application. GetMajorVersion () and getMinorVersion (): return the maximum and minimum versions of the Servlet API supported by the server. GetMineType (String file): returns the MIME type of the specified file. GetResource (String path): return the URL path of the specified resource. GetResourceAsStream (String path): returns the input stream of the specified resource. GetRequestDispatcher (String URLPath): returns the RequestDispatcher object of the specified resource. GetServlet (String name): The Servlet with the specified name is returned. GetServlets (): returns all servlets of the enumerated type. GetServletNames (): returns all Servlet names. The return type is Enumeration type. Log (String msg): Write the specified information to the Servlet log file. Log (String msg, Throwable throwable): writes stack tracing and descriptions of Throwable exceptions to the Servlet log file.

Website counter instance

Similarly, we will use an example to explain how to use common methods in the Application built-in object.

Create a setappattr. jsp page in the helloworld module to obtain information in the built-in application Object and set the initial count value. The detailed code is as follows:

<%@ page contentType="text/html;charSet=GBK" %>
Obtain application Information
ServletInfo:<%=application.getServerInfo()%>
application.jsp real path: <%=application.getRealPath("/application.jsp")%>
HelloServlet Real Path: <%=application.getRealPath("/servletsample/HelloServlet")%>
Major Version: <%=application.getMajorVersion()%>
get MIME: <%=application.getMimeType("/servletsample/demo.htm")%>
getResource: <%=application.getResource("/HelloJSP.jsp")%> <% out.println("

Set Value "); Application. setAttribute ("name", "zzb"); // Save the string "zzb" Object in application. setAttribute ("counter", "1"); // Save the string value "1" in application. println ("set name = zzb"); out. println ("
Set counter = 1 "); %>

Program Description: The setAttribute () method in the built-in application object is called to store User Name Information and count the initial value.

In addition, create another getappattr. jsp file in the same directory to obtain the Count value. The specific code is as follows:

<%@ page contentType="text/html;charSet=GBK"%>

Username: <% = application. getAttribute ("name") %>
Count value: <% // retrieves the string object that stores the keyword counter in the application, and forcibly converts it to an Integer int mycounter = Integer. valueOf (application. getAttribute ("counter "). toString ()). intValue (); out. println (mycounter); // Add a value, update and save it with a new value, and then apply the counter object application. setAttribute ("counter", Integer. toString (mycounter + 1); %>

Program Description: like the session object, the application stores the object type instead of the common numeric type. Here, the getAttribute () method in the application object is called to obtain the information stored on the previous page, add the read Count value, and store it in the application again.

When the preceding two browser windows are closed, and the getappattr. jsp window is opened and closed repeatedly, the Count value is continuously increasing and the tomcat service is used only. The session Object Storage information will be released as the window is closed.

6. built-in out objects

Out objects are the most frequently used objects in JSP development, but they are also the easiest to use.

Common out object Methods

The common method of an out object is as follows:

Print (): print the string information on the page without line breaks; println (): print the string information on the page and wrap the line; clear (): clear existing content in the buffer. ClearBuffer (): This method clears existing content in the current buffer. Flush (): clears data streams. GetBufferSize (): memory size of the returned buffer, measured in byte streams. If you do not set the buffer, the size is 0. GetRemaining (): the number of bytes remaining in the buffer returned by this method. IsAutoFlush (): checks whether the current buffer is set to automatically cleared or if it is full or throw an exception. Close (): close the output stream.

The print () and println () methods are most frequently used.

Data Output instance

Next, we will also give an example to illustrate how to use out Built-in objects. Create an out. jsp file with the following code:

<%@ page buffer=”1kb” autoFlush=”true” contentType=”text/html;charSet=GBK” %>
<% For (int I = 0; I <135; I ++) // iteratively outputs Out. println ("Hello world," + I + ""); %>
BufferSize: <% = out. getBufferSize () %>
BufferRemain: <% = out. getRemaining () %>
AutoFlush: <% = out. isAutoFlush () %> <% out. clearBuffer (); %>

Program Description: The buffer attribute in the page command is used to set the buffer size. If the autoFlush attribute is true, the buffer is automatically cleared. Run the JSP page in the browser and you will find that the program can only output to I = 106, and all the subsequent numbers and content will be cleared and cannot be displayed. This is because the clearBuffer () method called by the out object clears all the current content of the buffer.

If you change the clearBuffer () method in the program to the clear () method, an error is returned when you run it again. This is because the buffer has been automatically cleared (autoFlush = true) before the clear () method is called ). If you reduce the number of loops in the program, no matter whether the program calls the clear () or clearBuffer () method, nothing will be displayed on the browser. Because the content has been cleared by the clear () or clearBuffer () method. However, when the clear () method is used, there is no error, because the buffer is not full yet, autoFlush does not play a role.

VII. built-in exception object

The built-in exception object is used to handle page exception errors. It is an object of the java. lang. Throwable class. As mentioned above, in the actual JSP website development process, the errorPage attribute of the page command is usually added to the page to point it to a page dedicated to handling exception errors. If the error message received by this page is encapsulated on this page, and the isErrorpage attribute contained on the error handling page is set to true, the error handling page can be accessed using the following methods:

GetMessage () and getLocalizedMessage (): both methods return the exception message string of the exception object and the exception error in the localization language respectively. PrintStackTrace (): displays abnormal stack tracing traces. ToString (): return a brief message description about an exception or error. FillInStackTrace (): overwrite the stack execution track with an exception or error.

Exception errors are generally unavoidable by developers. Therefore, it is necessary to handle and prompt various possible exceptions. Readers should develop the habit of timely handling various abnormal errors.

8. built-in config objects

The config built-in object is an instance of the ServletConfig class. During Servlet initialization, the JSP Engine transmits information to it through config. This information can be a parameter that matches the property name/value, or it can be information about the server passed through the ServletContext object.

Common Methods of config built-in objects are as follows. GetServletContext (): This method returns a ServletContext object containing server-related information. GetInitParameter (String name): return the value of the initialization parameter. GetInitParameterNames (): returns all parameters required for Servlet initialization. The return type is enumeration.

The config built-in object is rarely used in JSP development. It is used only when Servlet compilation requires the init () method of Servlet to be reloaded.

9. built-in pageContext object

The pageContext object is a special object. It is equivalent to the maximum integrator of all other object functions on the page, that is, it can be used to access all other objects on the page, such as the request, response, and application objects described above.

Common Methods for pageContext objects

The common method of this object is as follows:

GetRequest (): returns the request object on the current page. GetResponse (): This method returns the response object on the current page. GetPage (): This method returns the page object on the current page. GetSession (): returns the session object on the current page. GetOut (): returns the out object on the current page. GetException (): returns the exception object on the current page. GetServletConfig (): returns the config object of the current page. GetServletContext (): returns the application object on the current page. SetAttribute (String name): Set the attribute value for the specified attribute name. GetAttribute (String name): locate the attribute value based on the attribute name. SetAttribute (String name, Object obj, int scope): Set the attribute value within the specified range. GetAttribute (String name, int scope): obtains the attribute value within the specified range. FindAttribute (String name): searches for an attribute and returns it. If no attribute is found, a null value is returned. RemoveAttribute (String name): deletes an attribute by its name. RemoveAttribute (String name, int scope): deletes an attribute within a specified range. GetAttributeScope (String scope): returns the scope of an attribute. GetAttributeNamesInScope (int scope): returns the enumeration of all attribute names in the specified range. Release (): releases all resources occupied by pageContext. Forward (String relativeURLpath): use the current page to re-export to another page. Include (String relativeURLpath): use another page contained in the current position.

Meanings of scope values mentioned above:

1:Page scope2:Request scope3:Session scope4:Application scope

Simple Example of pageContext object

The following is an example of applying the pageContext object:

 
<% Request. setAttribute ("MyName", "zzb1"); // save MyName in the request range session. setAttribute ("MyName", "zzb2"); // Save the MyName and apply it in the session range. setAttribute ("MyName", "zzb3"); // save MyName in the application range. %> request: <% = pageContext. getRequest (). getAttribute ("MyName") %>
Session: <% = pageContext. getSession (). getValue ("MyName") %>
Application: <% = pageContext. getServletContext (). getAttribute ("MyName") %>

PageContext objects are rarely used in the actual JSP development process, because objects such as request and response can directly call methods for use. If other objects are called through pageContext, it is a little farther away.

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.