content:
Implicit Object Introduction Session Management Flow Control Log Record and Abnormal Input and Output Control Initialization Parameters Conclusion Reference Information About The Author's Evaluation
related information:
J2EE Explorer Series JSTL Getting Started: Expression Language J2EE Explorer: Create and Manage Status Web Applications JSP Technology Getting Started with Web Application Web Getting Started with Web Application
There is also a Java area:
Teaching tools and product code and components all articles practical skills
Light JSP technology to use the most objects
Level: Intermediate
Kyle Gabhart (Kyle@gabhart.com) consultant, Gabhart Consulting September 2003
Then, the introduction of the session scope last month, the company Java expert Kyle Gabhart has deeply studied a variety of use of JSP implicit objects. Next, he will introduce 9 hidden objects to explain the purpose of each object (or multiple purposes), and finally give some best practices for using these convenience tools in JSP programming. You can get to us
Discussions Forum Share your article or
The idea of any other article in the J2EE Explorer Series.
The J2EE explorer in this issue is the continuation of the correct processing session scope of the last month. In addition to accessing the session scope, JSP implicit objects can also be used to process HTML parameters, forwarding requests to a web component, including components, through the JSP container log data, control output flow, processing exception, and more.
This month, you will learn to use implicit objects in the JSP page. We first briefly summarize the JSP architecture, including implicit objects. Then, I will introduce each object and describe its core function. Finally, we will give some best practices that use each type of object and the container management services it offer.
Implicit Object Introduction The concept behind the JSP architecture is to provide a web component that allows developers to focus on the representation of the Web content without falling into detail, programming, and data manipulation. The JSP application is essentially a special web component. Before processing the user request, the J2EE web container first converts it to servlet. There is a complete hidden object in each JSP application.
Implicit objects enable developers to access the services and resources provided by the container. These objects are defined as implicit because you don't have to explicit them. Whether you declare them - although you cannot repeat them, they are defined in each JSP page and is used by the container in the background. Because implicit objects are automatically declared, we only need to use reference variables associated with a given object to call their methods.
A simple description of the 9 hidden objects and its functions is as follows:
Application is the most widely used context state. It allows Servlets of the JSP page to share information with any Web component included in the same application. Config allows initialization data to a servlet of a JSP page. ExceptionInClude contains exception data that can only be accessed by the specified JSP "ERROR PAGES". OUT provides access to the Servlet's output stream. Page is an instance of a Servlet for processing the current request. In general, the author of the JSP page does not use this object. PageContext is the context of the JSP page itself. It provides the only API to manage properties with different scope. This API is used very much when implementing a JSP custom tag handler. Request provides access to the HTTP request data, and also provides contexts for joining the requested data. Response allows you to access the HTTPSERVLETRESPONSE object directly, and JSP programmers rarely use this object. Session may be the most used object in status management context. The concept of "session" is that the single user interacts with a web application in several requests.
Although some implicit objects only provide a single function, several functions can be provided in combination. In the next section, we will use the function classification to examine the implicit objects: Session Management: Application, Session, Request, PageContext, Requibility, Config, PageContext, Request, Session log, and exception: Application, Config, Exception, PageContext, Request, Session Input / Output Control: Request, Response, OUT Initialization Parameters: config
Session Management We mentioned last month, four implicit objects defined for JSP can be used to add state data in a specific context or scope. These four objects are Application, Session, Request, and PageContext. The following table lists the four objects and the status context they defined, and also gives a brief description of each object.
Table 1. JSP status management
Implicit object scope description javax.servlet.ServletContextApplication represents the entire runtime web module (application). The scope is shared between the application of Application's data in all WEB components of the same application module. This is very similar to the "Global" data javax.servlet.http.httpsessionSession represents the current HTTP session. In addition to the PAGE field, the Session action domain is the most common context. This object is using the most common Javax.Servlet.http.httpservletRequestRequence represents the current HTTP request. This context can span multiple web components (servlets and JSP pages) as long as these components belong to a part of the same atom request. The requested data (requesting method, URI, HTTP parameters, etc.) provided by the client are automatically saved in a request context. The servlet or JSP page can also be specified to specify the scope of the data as the request so that other servlets or JSP pages in the same request scope can get the data javax.servlet.jsp.pageContextPage represents the current JSP page Context. Because of a JSP page, the context includes current requests, sessions, and applications, so you can access all namespaces associated with a JSP page using the PageContext instance. It is the default scope of all objects, including JavaBeas objects. Objects with the Page scope typically bind to a local variable to access it in the scriptlet, expression, javabeans tag, and custom tags.
From the position of best practices, we should use the PAGE scope as much as possible. It is simple and is the default scope of JSP data. The REQUEST scope is ideal for sharing data between components during operation to handle a specific request. The session scope is designed to provide a single user with a long-lasting, stateful experience, which can span multiple requests. The Application Scope should only be used if you need to share data across user sessions across the component. Refer to the reference information for more information on the SESSION scope.
The greatest benefit of the flow control-oriented design method is reusability. In particular, the J2EE system borrows them into modular style development, where components can be rearranged, re-packaged and reuse in other applications. Even if you are not interested in designing reusable web modules, you can also find that your J2EE application consists of several parts. When using multiple servlets or JSP pages (that is, components), you need to use some type of stream control technology. The servlet architecture provides two such techniques: Forward and include (including). In J2EE Web development, Forward transfers the control of the user request to other web components. Forward is more useful in some time, for example, you need to set some JavaBeans with a component to open or close the resource, authenticate the user, or you need to perform some preparations before passing control to the next component. Many types of tasks can be performed before forwarding, but the components to be forwarded cannot set the response header information, and they cannot have content to send to the output buffer. All tasks that are directly related to the customer's content must be done by the forwarded components.
The second stream control technology in J2EE is include. When using Forward, transfer control. In contrast, the component to perform the include control of the request, but simply requests the output of another component to include a particular place in this page. This is a very good way for common design elements, such as top, footer, and navigation bar, etc..
FORWARD and INCLUDE are done through a dedicated object java.servlet.RequestDispatcher. Simply call a getRequestDispatcher () method of a servletContext object to get a RequestDispatcher object. There are several ways to get a reference to the servletContext object, we can:
Use an implicit declared Application variable because its type itself is already servletContext. Call method getServletContext (), which returns a reference to an implicit declared Application variable. Call the GetServletContext () method of the implicit declared config variable. Call the GetServletContext () method of the implicit declared PageContext variable. Call the GetServletContext () method of the implicit declared Request variable. Call the GetServletContext () method of the SESSION variable of the implicit declaration.
Listing 1 shows an example of code for the Forward stream control mechanism using implicit variable Application.
Listing 1. Forward stream 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 reason to the current request and
Response Objects * /
Rd.Forward (Request, Response); Listing 2 gives an example example of the code of the include stream control using the variable Application.
Listing 2. Include stream 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 reason to the current request and
Response Objects * /
Rd.includ (Request, Response);
Forward and Include are two great technologies added to the J2EE Web Development Kit. There are other ways to complete include Include in the JSP page, and there are many documents that solve the J2EE design pattern, how to combine these two technologies. See References for more information.
Logging and exception If you need to store information related to web applications to a log, there is still a built-in method available. The servletContext interface declares two methods to pass the data to a log. One method accepts a simple text message: log (java.lang.string), another method accepts an exception information and a text message: log (java.lang.Throwable, java.lang.string).
After two available logging methods provided by the servletContext interface, the remaining critical is to get a reference to the SERVLETCONText type object. Like the flow control objects we have previously discussed, there are many ways to get references to objects of the servletContext type. After obtaining an object reference, simply call the log () method and pass the necessary data to the method. Once this method is called, you will of course you want to view the application log to view the message. ServletContext is a simple interface and does not specify how to implement it declare. Therefore, the specific implementation of the LOG method is processed by the supplier. They can store the log information into a text file, binary, database, or in other formats that the vendor believes in the appropriate format. You need to know the location of the storage log from the server's documentation.
Although it is quite useful to send a message to a log file, many times you might 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 implemented by anywhere in the JSP page to be implemented by including the following Page instruction:
<% @ Page ErrorPage = "ErrorMessage.JSP"%>
If there is an exception thrown while processing the JSP page, the Exception object will immediately throw the specified error page by implicitly declared Exception variables.
In order to make a JSP page can be used as an error page, it must contain an instruction to declare this page is specified for the special page for handling the error, the instructions are as follows:
<% @ page isrrorpage = "true"%>
In order to use the ErrorMessage.JSP page, you can act as an error page, this instruction must appear some place in the page. The error page can display a friendly information to the user, then write the relevant exception information to the log for the administrator to view later. Input and output controls because JSP pages are just a simple abstraction of HTTP Servlet, so you can access HttpServletRequest and HttpservletResponse objects. If requested information, such as the type of client browser, the content type of HTTP POST, client performance, cookie data, or request parameters, simply call the appropriate method directly with the implicit declared Request variable. Similarly, if you need to set the response header information, such as the browser type, content type, content length, etc., simply use the implicit variable response to call the appropriate method.
If you need to directly access the Output stream of the JSP page, you may try to call getWriter () or getOutputStream by implicit response variables. However, due to the particularity of the JSP page, you can't do this. If you need to directly access the output stream, you must access a special buffer PrintWriter object with an Avax.Servlet.jsp.jspwriter type. How to locate a reference to such an object? The JSP container will implicit one and provide you with the OUT variable. You can use it in the JSP scriptlet to use it simply call out.print () or Out.println ().
Generally speaking, it is not necessary to use JSPWRITER objects directly, but simply use the content as normal text or written through JSP expression, then allow the container to translate this information into JSPWRITER calls. However, in both cases you need to use the OUT variable directly. One case is to define a handler for a JSP custom tag, which we will focus on next month. Another situation is that the output you want to create for JSP has more controls. If you have a plug-in HTML, you may find a big scripTlet and then use the out.println () statement when you need to output content to the client, easier, easier.
Initialization Parameters If you have some static data to be used to use it to the JSP page, and those data do not change frequently, and the initialization parameters may be a better choice. Initialization parameters are sometimes called environment variables or "init" parameters, which are specified by web application in a per-servlet / JSP, and they only read once in the life cycle of servlet, ie Read when initialization.
Listing 3 is an example of an initialization parameter declaration.
Listing 3. Initialization parameter declaration
init-param>
servlet>
webapp>
Using Implicit Variable Config Access these parameters, implicit variable config is a reference to servletConfig objects for JSP pages. Two methods for processing the init parameter are provided through the servletconfig interface. You can complete a specific parameter based on a specific parameter, or you can also retrieve a Enumeration (GetInitParameterNames ()) that is defined for the JSP page. After you have Enumeration, you can look for every value by loop. All init parameters are String objects. If other data types, such as integers, floating point, or Boolean values, the corresponding wrapper class must be used to resolve strings. Conclusion JSP technology provides a very useful abstraction above the servlet architecture, which allows Web designers to focus on content representation, but as needed to know less programming details. In this article, you have seen how we use implicit objects to quickly and easily develop web applications.
Next month, we will begin to tell the JSP custom tag and JSP standard tag library (JSTL). Learning Custom Tags How to promote the separation between the logic, but also allow you to merge dynamic data into the representation layer. In the time, explore it happily!