WebSphere Studio Application Developer Version 5 Programming Guide part 26 docx

10 223 0
WebSphere Studio Application Developer Version 5 Programming Guide part 26 docx

Đang tải... (xem toàn văn)

Thông tin tài liệu

224 WebSphere Studio Application Developer Version 5 Programming Guide Creating a server for testing To test a Web application we require a server. Because our project is a J2EE 1.3 project we require a WebSphere Version 5 server (or a Tomcat server). A server can be created automatically or manually:  For automatic server creation, select the ItsoProGuideBasicWeb project and Run on Server (context). The dialog shown in Figure 7-39 is displayed. Figure 7-39 Server selection dialog The default selection is correct and clicking OK defines a server project named Servers, a server named WebSphere v5.0 Test Environment, and starts the server. The drawback of this method is that we cannot select a name for the server and we cannot tailor the server before it starts. Stop the server, delete it from the Server Configuration view and delete the Servers project. We want to create a server manually.  For manual creation of a server, open the Server perspective and select New -> Server and Server Configuration . In the dialog (Figure 7-40) enter the name of the server (for example, ItsoServer), set the folder as ItsoProGuideServers (this creates the ItsoProGuideServers project), and select WebSphere version 5.0 -> Test Environment . Click Next and confirm that you want to create the ItsoProGuideServers project. Accept the default port of 9080 and click Finish . Select the ItsoServer in the Server Configuration view and Add -> ItsoProGuide (context). This adds the EAR project (with the Web module) to the server. The ItsoServer server also appears in the Servers view, from where it can be started and stopped. Chapter 7. Developing Web applications 225 Figure 7-40 Creating a WebSphere test server Testing the application Start the ItsoServer server. While the server is starting, you can check its initialization message log on the Console view. If the view is not visible, select Window -> Show View -> Console from the menu bar. You will know that the server is ready when you read the message “Server server1 open for e-business“. Select the ItsoProGuideBasicWeb project and Run on Server (context). When you run a Web project itself, instead of a single HTML file, then the welcome page is displayed. Welcome pages are defined in the deployment descriptor (web.xml) on the Pages page. Usually the index.html file is the first in the list. 226 WebSphere Studio Application Developer Version 5 Programming Guide If you are prompted to select a server, select the ItsoServer and also select Set server as project default (do not prompt) . This stores a server as the default in the properties of the Web project., where it can be changed at any time. The Web browser window opens and displays the index page (Figure 7-2 on page 182). In the customer ID field, type any number from 101 to 106 and submit the form. The resulting page (Figure 7-3 on page 182) should display the selected customer’s account list. Working with filters Servlet filtering is a new addition to the Servlet 2.3 API. It provides a new type of reusable object called a filter, that can transform requests and responses on the fly. You can chain filters together so that a group of filters can act on the input and output of a specified resource or group of resources. Filters typically include logging filters, image conversion filters, encryption filters, and MIME type filters. Although filters are not servlets, their life cycle is very similar. Filters are handled in the following manner:  The Web container determines which filters must be constructed for the Web application, before a request causes a Web resource to be accessed.  The container instantiates and initializes each filter (if this was not previously done) by calling the filter’s init method.  When the container receives a request for a Web resource, it creates a filter chain containing the filters associated with the resource.  The container invokes the chain’s doFilter method, which in turn invokes each filter’s doFilter method. A filter’s doFilter method typically: – Pre-processes the request object, or wraps it with a customized implementation of ServletRequest or HttpServletRequest to modify request headers or data. – Pre-processes the response object, or wraps it with a customized implementation of ServletResponse or HttpServletResponse to modify response headers or data. – Typically invokes the next filter on the chain by calling the chain’s doFilter method, but may alternatively block the chain. After this step, the filter may examine the response’s headers. – Does additional post-processing to the request and response objects. Chapter 7. Developing Web applications 227  Finally, after all the filters on the chain have been invoked, the filter chain calls the originally requested resource.  Before a filter can be removed from service, the container must call its destroy method. Figure 7-41 shows how the chaining of filters work: Figure 7-41 Filter chaining Creating a filter in Application Developer We implement a simple filter that audits all the banking transactions by writing an audit trail to a file. This filter in invoked before the PerformTransaction servlet gets control. To create a new filter in Application Developer, open the J2EE Navigator view of the ItsoProGuideBasicWeb project. Create a new package (under Java Source) names itso.basicweb.filter. Select the itso.basicweb.filter package and New -> Filter from the context menu to start the New Filter wizard (Figure 7-42). Resource Web Container Filter 1 doFilter Filter 2 doFilter Filter Chain doFilter Note: This is a simple example that uses a file for auditing. Such a design should not be used in a real application. 228 WebSphere Studio Application Developer Version 5 Programming Guide Figure 7-42 Creating a new filter (page 1) Make sure the correct package (itso.basicweb.filter) is selected. In the Filter Name field, type TransactionAuditingFilter. Our filter will audit every transaction that is performed with the bank accounts, logging the transaction type, time stamp, and parameters, as well as the client’s hostname and IP address. Click Next to proceed to the second page (Figure 7-43). The wizard’s second page lets you select method stubs and deployment descriptor information. Chapter 7. Developing Web applications 229 Figure 7-43 Creating a new filter (page 2) The filter has to be added to the Web deployment descriptor. Configure the initialization parameter by clicking the respective Add . Enter pathname for the parameter name and c:/transactionAudit.txt for its value. Finally, we have to set with which servlets this filter should be associated. Click the respective Add to open the Choose a Servlet dialog. Select PerformTransaction and click OK . Click Finish to complete the wizard. The TransactionAuditingFilter.java file is opened for editing. Note: To change the filter’s servlet associations or initialization parameters, open the Web deployment descriptor on the Filters page. 230 WebSphere Studio Application Developer Version 5 Programming Guide Editing the filter Switch to the Java editor opened on the TransactionAuditingFilter.java file. The source code of the sample filter is available in: \sg246957\sampcode\dev-web\filter\TransactionAuditingFilter.java Add an import statement and declare the following instance variable: import java.io.RandomAccessFile; private RandomAccessFile auditFile; The auditFile property holds a reference to the audit file. Generate its getter and setter methods by selecting the field in the Outline view and Generate Getter and Setter from its context menu. Change the generated method access modifiers from public to private (Figure 7-44): Figure 7-44 Getter and setter methods for the auditFile property The audit file should be opened upon the filter initialization. Edit the init method as shown in Figure 7-45. Figure 7-45 TransactionAuditingFilter init method After opening the file for both read and write access, we move the file pointer to the end, so that the file can be appended instead of overwritten. Because we opened the file in the init method, we have to close it in the destroy method (Figure 7-46). private RandomAccessFile getAuditFile() { return auditFile; } private void setAuditFile(RandomAccessFile auditFile) { this.auditFile = auditFile; } public void init(FilterConfig config) throws ServletException { String pathname = config.getInitParameter("pathname"); try { setAuditFile(new RandomAccessFile(pathname, "rw")); getAuditFile().seek(getAuditFile().length()); } catch (IOException e) { e.printStackTrace()); } } Chapter 7. Developing Web applications 231 Figure 7-46 TransactionAuditingFilter destroy method Finally, edit the filter’s doFilter method as shown in Figure 7-47. Figure 7-47 TransactionAuditingFilter doFilter method Save your changes and close the editor. The next time you perform a transaction with any of the accounts, the audit file c:\transactionAudit.txt is created and populated. See Figure 7-54 on page 236 for sample output of the filter (and the listener that we create next). public void destroy() { try { getAuditFile().close(); } catch (IOException e) { e.printStackTrace(); } } public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException { String protocol = req.getProtocol(); String address = req.getRemoteAddr(); String host = req.getRemoteHost(); String transaction = req.getParameter("transaction"); String parameters = ""; java.util.Enumeration parameterNames = req.getParameterNames(); while (parameterNames.hasMoreElements()) { String name = parameterNames.nextElement().toString(); String value = req.getParameter(name); parameters += name + "=" + value + ", "; } parameters = parameters.substring(0, parameters.length() - 2); String output = "- " + transaction + " being performed from " + host + " (" + address + ") using " + protocol + " at " + new java.util.Date() + " Parameters: " + parameters + "\r\n"; synchronized (getAuditFile()) { getAuditFile().writeBytes(output); } System.out.println(output); chain.doFilter(request, response); } 232 WebSphere Studio Application Developer Version 5 Programming Guide Working with listeners Life-cycle listeners, now part of the Servlet API, enable you to be notified when servlet contexts and HTTP sessions are created, destroyed or modified. They give the application developer greater control over interactions with ServletContext and HttpSession objects. Servlet context listeners manage resources at an application level. Session listeners manage resources associated with a particular client’s HTTP session. Listeners are available for life-cycle events and for attribute modification events. The listener developer creates a class that implements the interface corresponding to the desired listener functionality:  javax.servlet.ServletContextListener Receives javax.servlet.ServletContextEvent events that notify that a servlet context has just been created or is about to be destroyed.  javax.servlet.ServletContextAttributeListener Receives javax.servlet.ServletContextAttributeEvent events that notify that an attribute in the servlet context has been added, removed, or modified.  javax.servlet.http.HttpSessionListener Receives javax.servlet.http.HttpSessionEvent events that notify that an HTTP session object has just been created or is about to be destroyed.  javax.servlet.http.HttpSessionAttributeListener Receives javax.servlet.http.HttpSessionBindingEvent events that notify that an attribute in an HTTP session has been added, removed, or modified. Note that the same listener may implement any combination of the above interfaces. At application startup time, the container uses introspection to create an instance of the listener class and registers it with the appropriate event generators. As an example, we will create a listener that implements both the HttpSessionListener and HttpSessionAttributeListener interfaces. It will be called HttpSessionInspector and will print to the standard output detailed HTTP session event notifications that can be used by the developer to determine:  When HTTP sessions are created and destroyed.  The size of the HTTP session objects at creation and destruction.  When HTTP session attributes are added, removed or modified, and their sizes. Chapter 7. Developing Web applications 233 Creating a listener in Application Developer To create a listener in Application Developer, open the J2EE Navigator view of the ItsoProGuideBasicWeb project. Create a new package (under Java Source) names itso.basicweb.listener. Select the itso.basicweb.listener package under the Java Source folder and then select New -> Life-cycle Listener from the context menu to start the New Life-cycle Listener wizard (Figure 7-48): Figure 7-48 Creating a new life-cycle listener (page 1) Make sure the correct package (itso.basicweb.listener) is selected. In the Listener Name field, type HttpSessionInspector. In the Listener Types field, select both Http Session Listener and Http Session Attribute Listener . Click Next to continue to the second page (Figure 7-49): . 224 WebSphere Studio Application Developer Version 5 Programming Guide Creating a server for testing To test a Web application we require a server. Because. Pages page. Usually the index.html file is the first in the list. 226 WebSphere Studio Application Developer Version 5 Programming Guide If you are prompted to select a server, select the ItsoServer. for auditing. Such a design should not be used in a real application. 228 WebSphere Studio Application Developer Version 5 Programming Guide Figure 7-42 Creating a new filter (page 1) Make sure

Ngày đăng: 03/07/2014, 20:20

Từ khóa liên quan

Tài liệu cùng người dùng

Tài liệu liên quan