Chapter 1. Web Component Design and Implementation

Design, develop and test Java Servlets, Filters and Life-cycle Listeners

Design, develop and test Java Servlets

Servlets are flexible and scalable server-side Java components based on the Sun Microsystems Java Servlet API, as defined in the Sun Microsystems Java Servlet Specification. For J2EE 1.4, the supported API is Servlet 2.4.

Servlets generate dynamic content by responding to Web client requests. When an HTTP request is received by the application server, the server determines, based on the request URI, which servlet is responsible for answering that request and forwards the request to that servlet. The servlet then performs its logic and builds the response HTML that is returned back to the Web client, or forwards the control to a JSP.

Application Developer provides the necessary features to make servlets easy to develop and integrate into your Web application. Without leaving your Workbench, you can develop, debug, and deploy them. You can set breakpoints within servlets, and step through the code. You can make changes that are dynamically folded into the running servlet on a running server, without having to restart the server each time.

A Java servlet is a Java class that extends the javax.servlet.http.HttpServlet class and implements the javax.servlet.Servlet interface. A servlet can provide dynamic contents to a Web application. It can also provide static contents, with some effort. A servlet can be called directly from a Web browser or indirectly from another Web resource. HTTP-based requests are sent to the servlet when the servlet is invoked. It receives the request and returns a response back to the client.

There are several methods for sending a HTTP request, such as GET, POST, PUT, HEAD, and DELETE. The GET and POST HTTP request methods are the most commonly used ones. Both GET and POST send data to the server to be processed. They differ, however, in the way the data is sent. Without getting into too much technical detail, a GET request sends the data through the URI itself, so the data is visible to users. A POST request, on the other hand, sends the data in a message body, so that it cannot be seen.

A servlet has doGet and doPost methods for handling the GET and POST requests, respectively. When a servlet is invoked from a Web browser, the doGet method is automatically called. If the servlet is called from another resource, such as an HTML form, the user can specify which of the two HTTP-based request methods to use. A servlet can obtain information from the request, such as the fields for an HTML form. It can also create a response for the client, or redirect the controls to another Web resource. A servlet can respond to the client with both static and dynamic content.

The servlet wizard helps you create Java servlets by walking you through the creation process and by providing you with output files that you can use or that you can modify for use with your Web application. The servlets can run on WebSphere Application Server or other J2EE-compliant Web servers.

To create a servlet using the Servlet wizard, complete the following steps:

  1. From the Web perspective, expand your dynamic project in the Project Explorer view, and expand the Deployment Descriptor.

  2. Right click on the Servlet icon, and select New > Servlet from the pop-up menu. The Create Servlet wizard appears.

    Create Servlet wizard

  3. In the Create a Servlet page, supply the following:

    1. Type the name and description of the servlet. Notice that the name that you type in the name field is used as the default URL mapping.

    2. Optionally add or remove initialization parameters and URL mappings.

    3. Optionally choose an existing servlet class. To do this, select the Use existing servlet class check box, and then select the Browse button. A window appears in which you can choose an existing servlet or a JSP.

    4. Optionally choose whether you want to generate an annotated servlet class.

    5. If you selected an existing servlet class, click Finish; otherwise, select Next.

  4. Supply the following information:

    Create Servlet wizard - Step 2

    1. Specify the folder where the servlet class will be placed, the package that the class will belong to (it is added into a default package if you do not specify one), and the class name of the servlet.

    2. Specify a superclass for the servlet class. A servlet created by this wizard can have HttpServlet, or any class that has HttpServlet in its hierarchy as its superclass. Click Browse to choose from the available superclasses.

    3. Click Finish or click Next for more options.

  5. Select a modifier to specify whether your servlet class is public, abstract, or final. (Classes cannot be both abstract and final.)

    Create Servlet wizard - Step 3

    1. The javax.servlet.Servlet is provided as the default Interface. You can also add additional interfaces to implement. Click Add to open the Interface Selection dialog.

      In this dialog, as you type the name of the interface that you are interested in adding in the Choose interfaces field, the list of available interfaces listed in the Matching types list box updates dynamically to display only the interfaces that match the pattern. Choose an interface to see the Qualifier, and then click Add. Click OK when you are finished.

    2. Select any appropriate method stubs to be created in the servlet file. The stubs created by using the Inherited abstract methods option must be implemented if you do not intend to create an abstract servlet. This is not true for Constructors from superclass.

    3. Click Finish. The servlet is generated.

In Java editor update class content:

protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1)
		throws ServletException, IOException {
	PrintWriter out = arg1.getWriter();
	out.println("Hello, World!!");
}

protected void doPost(HttpServletRequest arg0, HttpServletResponse arg1)
		throws ServletException, IOException {
	doGet(arg0, arg1);
}
					

Testing artifacts on a server

You can use the server tools to test one or more application artifacts on an application server.

  1. In the Project Explorer view from the J2EE perspective, expand the project that contains the file you want to test (TestServlet).

  2. Right-click the artifact that you want to test. Examples of artifacts include the Web project or a file within the Web project (such as a JSP file, servlet, or HTML file), or an enterprise bean.

  3. Select Run > Run on Server. The Server Selection wizard appears:

    The Server Selection wizard

  4. Use the radio buttons to specify how you want to select the server. Select from the following options:

    Choose an existing server - This option uses an existing server that is defined in your workbench.

    Manually define a server - This option creates a new server.

  5. Under the Select the server that you want to use list, select a server you want to run your application. The list of available servers, under the Select the server that you want to use list, depends on the J2EE specification level you defined for the artifact and the supported servers for this product.

  6. (Optional) Click Next to configure additional settings, such as configuring settings specific to the server, and adding or removing projects configured on the server.

  7. Click Finish. The server tools automatically complete the following tasks for you:

    1. If the Create server resources in workspace check box on the Server preferences page (Windows >Preferences > Server) is enabled, the server tools creates a server project with Servers as the default name.

    2. Creates the server and adds it to the Servers View.

    3. Adds your project to the server.

    4. Starts the server. (This may take time depending on the server settings.)

    5. If the Automatically publish before starting servers check box on the Server preferences page (Window > Preferences > Server) is selected, the server tools check to see if your project and files on the server are synchronized. If they are not, the project and the files are automatically updated on the remote machine when the server is restarted.

    6. If testing enterprise beans, the server tools display the enterprise bean in the Universal Test Client.

    7. If testing Web artifacts, the server tools adds the EAR project containing your Web project to the server. And display the file in the Web Browser.

      Display the servlet in the Web Browser

  8. For testing EJB projects, you can now test your beans in the Universal Test Client.

Design, develop and test Filters

The Filter wizard enables you to create Java filter classes for various J2EE filter types, such as authentication filters, encryption filters, and data compression filters.

To create a filter class, do the following:

  1. Open the Filter wizard. To do this:

    1. Open the Web perspective and display the Project Explorer view.

    2. Expand the project in which you want to create the filter (Chapter1Web).

    3. Expand the deployment descriptor icon.

    4. Right click on the Filters icon.

    5. Select New > Filter from the pop-up menu:

      New Filter

    The Create Filter wizard appears.

  2. Type a name and description for the filter (GreetingFilter). Notice that the name that you type in the Name field is used to create a URL Mapping for the filter. Optionally add initialization parameters or an alternative URL mapping (/*), and then select Next:

    New Filter - Step 2

  3. Specify the folder where the filter class will be placed (\Chapter1Web\JavaSource). (You should place the filter in the Java source folder). Also specify the package that the class will belong to (by.iba.rad257) (it is added into a default package if you do not specify one), and the class name of the filter (GreetingFilter).

    New Filter - Step 3

  4. Specify a superclass for the filter class. A filter created by this wizard can have any class that has Object in its hierarchy as its superclass. Click Browse to choose from the available superclasses. When finished select Next.

  5. Select a modifier to specify whether your filter class is public, abstract, or final. (Classes cannot be both abstract and final).

  6. The javax.servlet.Filter is provided as the default Interface. You do not have to implement the Filter interface if you subclass a class that implements Filter, or if you implement an interface which has Filter in its hierarchy.

    You can also add additional interfaces to implement. Click Add to open the Interface Selection dialog. In this dialog, as you type the name of the interface that you are interested in adding in the Choose interfaces field, the list of available interfaces listed in the Matching types list box updates dynamically to display only the interfaces that match the pattern. Select an interface to see the Qualifier and click Add. Click OK when you are finished. The qualifier that you chose appears in the Interfaces dialog.

  7. Choose which method stub you want to create.

    The Inherited abstract methods option adds stubs for inherited abstract methods, and that must be implemented (unless you intend to create an abstract class). Because the init(), destroy(), and doFilter() methods are all defined in the javax.servlet.Filter interface, stubs for these methods are automatically generated for each new filter class.

    New Filter - Step 4

  8. Click Finish.

The filter that you created appears under the Filters icon.

In the Project Explorer View expand JavaSource folder and open GreetingFilter Java class.

Add the following code in the doFilter(...) method:

PrintWriter out = arg1.getWriter();
HttpServletResponse httpResp = (HttpServletResponse) arg1;
HttpServletResponseWrapper wrapper = new HttpServletResponseWrapper(httpResp) {
	CharArrayWriter caw = new CharArrayWriter();

	public String toString() {
		return caw.toString();
	}

	public PrintWriter getWriter() {
		return new PrintWriter(caw);
	}			
};

arg2.doFilter(arg0, wrapper);
String originalContent = wrapper.toString();
String newContent = originalContent.replaceAll("Hello", "Hi");
arg1.setContentLength(newContent.length());
out.write(newContent);
out.close();
					

Organize imports to fix compilation errors (Source > Organize Imports).

Run TestServlet on the server (you need to update servlet last modification date after you added dynamic filter):

Test New Filter

Design, develop and test Life-cycle Listeners

The Life-cycle Listener wizard enables you to create Java listener classes for various J2EE listener types related to servlet context and session events and attributes.

To create a listener class, do the following:

  1. Open the Life-cycle Listener wizard. To do this, open the Web perspective and from the Project Explorer, expand the project (that you have created), and expand the deployment descriptor icon. Then right click on the Listener icon, and select New > Life-cycle Listener from the pop-up menu. The Create Listener wizard appears:

    New Life-cycle Listener

  2. Specify a listener name (TestListener). Click the Next button.

  3. Supply the following information:

    • The folder where the listener class will be placed (\Chapter1Web\JavaSource).

    • The Java package that the class will belong to (it is added into a default package if you do not specify one) - (by.iba.rad257).

    • The class name of the listener (TestListener).

      Note: You should place the listener in the JavaSource folder.

    • The superclass for the listener class. A listener created by this wizard can have Object, or any class that has Object in its hierarchy, as its superclass. Click Browse to choose from the available superclasses.

    New Life-cycle Listener - Step 2

  4. Click Next.

  5. Select a modifier to specify whether your listener classes are public, abstract, or final. (Classes cannot be both abstract and final).

  6. You can also add additional interfaces to implement in addition to the default interfaces. Click Add to open the Interface Selection dialog. In this dialog, as you type the name of the interface that you are interested in adding in the Choose interfaces field, the list of available interfaces listed in the Matching types list box updates dynamically to display only the interfaces that match the pattern. Choose an interface to see the Qualifier and click Add. Click OK when you are finished.

    New Life-cycle Listener - Step 3

  7. Choose which method stub you want to create. The Inherited abstract methods and Constructors from superclass options add stubs for inherited abstract methods and superclass constructors that must be implemented (unless you intend to create an abstract listener). One method with the Inherited abstract methods option must be created for the class not to be abstract.

  8. Click Finish.

The listener class that you created appears under the Listener icon.

In the Project Explorer View expand JavaSource folder and open TestListener Java class.

Copy-paste the code below to the listener class body (replace method stubs).

public void requestInitialized(ServletRequestEvent arg0) {
	System.out.println("[TestListener] Request initialized : " + arg0.toString());
}

public void requestDestroyed(ServletRequestEvent arg0) {
	System.out.println("[TestListener] Request destroyed : " + arg0.toString());
}

public void contextInitialized(ServletContextEvent arg0) {
	System.out.println("[TestListener] Context initialized : " + arg0.toString());
}

public void contextDestroyed(ServletContextEvent arg0) {
	System.out.println("[TestListener] Context destroyed : " + arg0.toString());
}
					

Stop the server.

In the Project Explorer View right click on TestServlet and select Run > Run on Server... Click Finish button.

Open Console View. Explore TestListener's output in server's console. Refresh servlet in Web Browser – new TestListener messages should appear in Console View:

[21.3.07 11.53.04:626 EET] 00000013 ApplicationMg A   WSVR0221I: Application started: DefaultApplication
[21.3.07 11.53.04:657 EET] 00000014 SystemOut     O [TestListener] Context initialized : javax.servlet.ServletContextEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]
[21.3.07 11.53.04:657 EET] 00000014 VirtualHost   I   SRVE0250I: Web Module Chapter1Web has been bound to default_host[*:9080,*:80,*:443].
...
[21.3.07 11.53.14:469 EET] 00000031 ServletWrappe A   SRVE0242I: [TestServlet]: Initialization successful.
[21.3.07 11.53.14:501 EET] 00000031 SystemOut     O [TestListener] Request initialized : javax.servlet.ServletRequestEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]
[21.3.07 11.53.14:532 EET] 00000031 SystemOut     O [TestListener] Request destroyed : javax.servlet.ServletRequestEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]
[21.3.07 12.04.15:590 EET] 00000032 SystemOut     O [TestListener] Request initialized : javax.servlet.ServletRequestEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]
[21.3.07 12.04.15:590 EET] 00000032 SystemOut     O [TestListener] Request destroyed : javax.servlet.ServletRequestEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]
[21.3.07 12.04.17:668 EET] 00000031 SystemOut     O [TestListener] Request initialized : javax.servlet.ServletRequestEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]
[21.3.07 12.04.17:668 EET] 00000031 SystemOut     O [TestListener] Request destroyed : javax.servlet.ServletRequestEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]				
					

Stop the server:

[21.3.07 12.05.01:059 EET] 00000035 ApplicationMg A   WSVR0217I: Stopping application: Chapter1EAR
[21.3.07 12.05.01:105 EET] 00000035 SystemOut     O [TestListener] Context destroyed : javax.servlet.ServletContextEvent[source=com.ibm.ws.webcontainer.facade.ServletContextFacade@6a557bb7]
[21.3.07 12.05.01:105 EET] 00000035 ApplicationMg A   WSVR0220I: Application stopped: Chapter1EAR					
					

BOOT.BY - Tech Industry News         Free SCBCD 1.3 Study Guide     Free SCDJWS 1.4 Study Guide     SCDJWS 1.4 Quiz     Free IBM Certified Associate Developer Study Guide     Free SCJP 5.0 (Tiger) Study Guide     Free Mock Exam Engine     Free SCWCD 1.4 Study Guide     IBM Test 000-287. Enterprise Application Development with IBM WebSphere Studio, V5.0 Study Guide     Free SCBCD 5.0 Study Guide