Java EE Explorer: multiple usages of an implicit object

Source: Internet
Author: User
Tags config functions header http post http request implement include reference
J2ee| object then last month's introduction to the session scope, enterprise Java expert Kyle Gabhart In-depth study of the various uses of JSP implicit objects. Next, he introduces 9 implicit objects, explains the purpose (or multiple uses) of each object, and finally gives some best practices for how to use these handy tools in JSP programming. You can share your thoughts about this article or any other article in the EE Explorer series in our discussion forum.
This issue of the EE Explorer is the sequel of last month's proper handling of the session scope. In addition to accessing session scopes, JSP implicit objects can also be used to process HTML parameters, forward requests to a WEB component, include component content, log data through the JSP container, control the output stream, handle exceptions, and so on.

This month, you'll learn to use implicit objects in JSP pages. We start with a brief overview of the JSP architecture, which includes implicit objects. Then, I'll introduce each object and describe its core functionality. Finally, we will give some best practices for using each type of object and the container management services it provides.

An Introduction to implicit objects
The idea behind the JSP architecture is to provide a Web component that allows developers to focus on the presentation of Web content without being bogged down in details such as parsing, programming, and data manipulation. The JSP application is essentially a special web component, and the Java-EE Web container First converts it to a servlet before processing the user request. There is a complete set of implicit objects within each JSP application.

Implicit objects enable developers to access the services and resources provided by the container. These objects are defined implicitly because you do not have to explicitly declare them. Whether or not you declare them-although you cannot declare them repeatedly, they are defined in each JSP page and used in the background by the container. Because implicit objects are declared automatically, we only need to use reference variables associated with a given object to invoke its methods.

A brief description of the 9 implicit objects and their functions is as follows:

Application is the most widely used context state. It allows the servlet of the JSP page to share information with any WEB component that is included in the same application.


Config allows you to pass initialization data to a servlet in a JSP page.


Exceptioninclude contains exception data that can only be accessed by the specified JSP "error pages."


Out provides access to the output stream of the servlet.


Page is an instance of the Servlet page that handles the current request. In general, JSP page authors do not use this object.


PageContext is the context of the JSP page itself. It provides only one by one APIs to manage attributes with different scopes. This API is used very much when implementing JSP custom tag handlers.


The request provides access to HTTP request data, as well as a context for adding data specific to the request.


Response allows direct access to httpservletresponse objects, which are rarely used by JSP programmers.


Sessions may be the most frequently used objects in the context of state management. The concept of "session" means that an individual user interacts with a WEB application on several requests.
Although some implicit objects provide only a single function, several combinations can provide multiple functions. In the next section, we'll examine the implicit objects by functional classification:

Conversation Management: Application, session, request, PageContext
Flow control: Application, config, PageContext, request, session
Log records and Exceptions: Application, config, exception, PageContext, request, session
Input/Output control: Request, response, out
Initialization parameters: Config
Session Management
As we mentioned last month, the four implicit objects defined for JSP can be used to add stateful data to a particular context or scope. These four objects are application, session, request, and PageContext. The following table lists the four objects and their defined state contexts, and gives a simple description of each object.

Table 1. JSP state-managed implicit object Scope description
Javax.servlet.ServletContext application represents the entire runtime's Web module (application). The scope for application data is shared across all Web components of the same application module. It's much like the "global" data provided in Java EE
Javax.servlet.http.HttpSession sessions represent the current HTTP session. The session scope is the most common context except page action. This object is most commonly used in providing a durable, stateful user experience across multiple requests
Javax.servlet.http.HttpServletRequest requests represent the current HTTP request. This context can span multiple Web components (servlet and JSP pages) as long as those components are part of the same atomic request. The request-specific data provided by the client (request method, URI, HTTP parameter, and so on) is automatically saved in a request context. A servlet or JSP page can also programmatically designate the scope of the data as request to allow other servlet or JSP pages in the same request scope to obtain that data programmatically
The Javax.servlet.jsp.PageContext page represents the context of the current JSP page. Because the context of a JSP page includes current requests, sessions, and applications, you can use the PageContext instance to access all namespaces associated with a JSP page. It is the default scope for all objects, including the Javabeas object. Objects with page scopes are usually bound to a local variable so that it can be accessed in scriptlet, expressions, JavaBeans tags, and custom tags


From a best practice standpoint, we should use the page scope as much as possible. It is simple and is the default scope for JSP data. The request scope is ideal for sharing data between components during run time to handle a particular request. Session scopes are designed to provide a persistent, stateful experience for a single user, spanning multiple requests. The application scope should only be used when data is shared across a user session between components. See Resources for more information on session scope.

Flow control
The greatest benefit of object-oriented design methods is reusability. In particular, the Java EE system borrows them into modular-style development, where components can be rearranged, repackaged, and reused in other applications. Even if you are not interested in designing reusable WEB modules, you are likely to find that your Java EE application is made up of several parts. Any time you use multiple servlet or JSP pages (that is, components) to complete a request, you need to use some type of flow control technology. The Servlet architecture provides two such techniques: forward (forwarding) and include (included).

In Java EE Web Development, forward transfers control of the processing of user requests to other Web Components. Forward can be useful in some cases, such as the need to set some JavaBean with a component, turn resources on or off, authenticate users, or perform some preparatory work before passing control to the next component. Many types of tasks can be performed before forwarding, but the component to be forwarded cannot set the response header information or have content to be sent to the output buffer. All tasks that are directly related to sending content to the customer must be completed by the component being forwarded.

The second type of flow control technology in Java EE is include. When you use forward, you pass control. In contrast, the component that executes the include maintains control over the request, but simply requests that the output of another component be included in a particular place on the page. This is a great way to design elements that are common, such as the header, footer, and navigation bars.

Forward and include are done through a dedicated object java.servlet.RequestDispatcher. Simply call a ServletContext object's Getrequestdispatcher () method to get a RequestDispatcher object. There are several ways to get a reference to a ServletContext object, and we can:

Use an implicitly declared application variable, because its type is already servletcontext.
Invokes the method Getservletcontext (), which returns a reference to an implicitly declared application variable.
Invokes the Getservletcontext () method of an implicitly-declared config variable.
Invokes the Getservletcontext () method of an implicitly-declared PageContext variable.
Invokes the Getservletcontext () method of an implicitly-declared request variable.
Invokes the Getservletcontext () method of an implicitly-declared session variable.
Listing 1 shows a code example of a forward flow control mechanism using an implicit variable application.

Listing 1. Forward Flow Control Example

Javax.servlet.RequestDispatcher Rd;

/* Obtain a reference to a RequestDispatcher object via the implicit
Application variable*/
RD = Application.getrequestdispatcher ("/nextpage.jsp");

/* Perform the forward specified by the RequestDispatcher
and pass along a reference to the current request and
Response Objects * *
Rd.forward (request, response);



Listing 2 shows a code example that also uses the include flow control of variable application.

Listing 2. Include flow Control Example

Javax.servlet.RequestDispatcher Rd;

/* Obtain a reference to a RequestDispatcher object via the implicit
Application variable*/
RD = Application.getrequestdispatcher ("/header.jsp");

/* Perform the include specified by the RequestDispatcher
and pass along a reference to the current request and
Response Objects * *
Rd.include (request, response);



Forward and include are two great technologies added to the Java EE Web Development Toolkit. There are other ways to complete include in a JSP page, and there are a number of references to the Java EE design patterns that discuss how to use both technologies. See Resources for more information.

Log records and exceptions
If you need to store information related to a WEB application in a log, there are still built-in methods available. The ServletContext interface declares two methods for passing data to a log. One method accepts a simple text message: Log (java.lang.String), and another method accepts an exception message and a text message: Log (java.lang.Throwable, java.lang.String).

After having the two available logging methods provided by the ServletContext interface, the remaining key is to get a reference to an object of type ServletContext. Like the flow control objects we discussed earlier, there are several ways to get a reference to an object of type ServletContext. After you get the object reference, simply call the log () method and pass the necessary data to the method. Once this method is invoked, you will of course want to be able to view the application log to see the message. The ServletContext is a simple interface, and there is no way to implement how it is declared. Therefore, the specific implementation of the log method is handled by the supplier. They can store log information in a text file, binary file, database, or other format that the vendor deems appropriate. You need to know the location of the storage log from the server's documentation.

Although it is useful to send a message to a log file, many times you may want to display a user-friendly error message when an unrecoverable exception occurs. To achieve this, you can declare that your JSP page uses a separate page to handle error messages. This is done anywhere on the JSP page by including the following page instruction:


<%@ page errorpage= "errormessage.jsp"%>



If an exception is thrown when a JSP page is processed, the exception object immediately throws the specified error page through an implicitly-declared exception variable.

In order for a JSP page to be an error page, it must contain an instruction to declare that the page is a special page specified to handle the error, as follows:


<%@ page iserrorpage= "true"%>



In order to use the Errormessage.jsp page as an error page, this instruction must appear somewhere on the page. The error page can display a friendly message to the user and can then write the relevant exception information to the log for later viewing by the administrator.

Input and output control
Because JSP pages are just a simple abstraction of the HTTP servlet, you can access HttpServletRequest and HttpServletResponse objects. If you need information that is specific to the request, such as the type of client browser, the content type of the HTTP post, client performance, Cookie data, or request parameters, simply invoke the appropriate method directly with an implicitly-declared request variable. Similarly, if you need to set up response header information, such as browser type, content type, content length, and so on, simply invoke the appropriate method with an implicit variable response.

If you need to directly access the output stream of a JSP page, you may try to invoke getwriter () or Getoutputstream () via an implicit response variable. However, because of the specificity of the JSP page, you cannot do so. If you need to access the output stream directly, you must access it through a special buffered PrintWriter object of the Avax.servlet.jsp.JSPWriter type. How do you locate a reference to such an object? The JSP container will implicitly declare one for you and provide it to you through an out variable. You can use it in a JSP scriptlet by simply calling Out.print () or out.println ().

In general, you do not need to use JspWriter objects like this directly, but simply write the content as plain text or through a JSP expression, and then allow the container to translate the information into JspWriter calls. However, in both cases you need to use the out variable directly. One scenario is to define a handler for the JSP custom tag, which we'll focus on next month. Another scenario is that you want to have more control over the output created by the JSP. If you have HTML with JSP scriptlets and expressions, you might find it simpler and easier to create a large scriptlet and use the OUT.PRINTLN () statement when you need to output the content to the client.

Initialization parameters
Initialization parameters may be a good choice if you have some static data that you want to provide to your JSP pages and that data doesn't change frequently. Initialization parameters are sometimes called environment variables or "init" parameters, which are specified by the Web.xml file of a WEB application located within a per-servlet/jsp, and they are read only once in the lifecycle of the servlet, which is read at initialization time.

Listing 3 is an example of an initialization parameter declaration.

Listing 3. Initialization parameter declaration

<webapp>
<servlet>
<servlet-name>MyServlet</servlet-name>
<servlet-class>com.gabhart.MyTestServlet</servlet-class>
<init-param>
<param-name>contactEmail</param-name>
<param-value>kyle@gabhart.com</param-value>
</init-param>
</servlet>
</webapp>



The values of these parameters can be accessed using implicit variable config, which is a reference to the ServletConfig object of the JSP page. Two methods for handling init parameters are provided through the ServletConfig interface. You can complete a lookup (Getinitparameter (java.lang.String) on a specific parameter by name), or you can retrieve one of the names of all the parameters defined for the JSP page. Enumeration (Getinitparameternames ()). After you have the enumeration, you can iterate through each value. All init parameters are string objects. If you need additional data types, such as integers, floating-point numbers, or Boolean values, you must use the appropriate wrapper class to parse the string.

Conclusion
JSP technology provides a very useful abstraction on top of the Servlet architecture, which allows WEB designers to focus on content representation and only require less programming details. In this article, you've seen how we use implicit objects to quickly and easily develop WEB applications.

Next month, we'll start with JSP custom tags and JSP standard tag libraries (JSTL). Learn how custom tags facilitate separation between presentation and business logic, while also allowing you to incorporate dynamic data into the presentation layer. Then, we'll explore together happily!


Author blog:http://blog.csdn.net/zaowei21/
Related articles
Analysis on some mistaken ideas about the construction of government informatization
SOA: Service Architecture Component
Three technologies of building support system
The history and future of enterprise-class software
Teach you to implement 3d programming in Java


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.