Home Javacertification Ibm-287 Chapter 2. Design, build and test web components

Ask Questions?

View Latest Questions

Advertisement


 
 

Chapter 2. Design, build and test web components
Posted on: May 4, 2011 at 12:00 AM
Chapter 2. Design, build and test web components Part I. Exam Objectives

Chapter 2. Design, build and test web components

Design, develop and test Java Servlets, filters and listeners

Creating a dynamic Web project

You create and maintain the resources for your Web applications in Web projects. Dynamic Web projects enable you to create resources such as JavaServer Pages and servlets, and use technologies such as Struts and JavaServer Faces.

Note: If you want to specify a target server for the Web project you are going to create, you should first enable server targeting support on the J2EE preferences page.

To create a new dynamic Web project:

  1. Click File > New > Project. Then select the Web option on the left, the Dynamic Web Project option on the right, and then click the Next button. The New Dynamic Web Project wizard is launched.

  2. Provide a name for the Web project (titan-web).

  3. Accept the default value in the Project location field (this is where your project is stored in your file system), or click Browse to choose a location from the file system.

  4. To specify or customize the project options, select the Configure advanced options check box and click Next.

    Note that you would also select this option if you wanted to add Struts support to your Web project. Also note that if you wanted to accept the defaults associated with a dynamic Web project, you would leave Configure advanced options unchecked and click Finish. This would create an Enterprise Application project (EAR file) named DefaultEAR in the same directory as your new Web project.

    Web project
  5. A new or existing Enterprise Application project must be associated with your new Web project to facilitate deployment. If you selected Configure advanced options and then clicked Next, the J2EE Settings Page appears in which you can customize the project options:

    • If the Enterprise Application project is new, click New and then type a name for the new project. When your Web project is created at the end of the wizard, the new Enterprise Application project is also created with the same name as the project. Note that the default is an EAR file named DefaultEAR located in the same directory as your new Web project.

    • If the Enterprise Application project already exists, select the project from the EAR project drop down list.

    Web project

    Note: If you want to add a Web project as a module to another Enterprise Application project in the future, you can open the application deployment descriptor editor for the Enterprise Application project and select the Add option in the General page.

  6. Provide a Context root value. The context root is the Web application root, the top-level directory of your application when it is deployed to a Web server. You can change the context root after you create a project using the project Properties dialog, which you access from the project's context menu. The context root can also be used by the links builder to ensure that your links remain ready to publish as you move and rename files inside your project.

  7. From the J2EE Level drop-down list, select the appropriate Sun Microsystems Servlet and JSP specification level for the dynamic elements you plan to include in your Web project.

    Any new servlets and JSP files that you expect to create should adhere to the latest specification level available; previous specification levels are offered to accommodate any legacy dynamic elements that you expect to import into the project.

    By default, the Web project's J2EE level is set to the Workbench's J2EE level. Project preferences are initialized when the project is created. If you want to update these preferences, do the following:

    1. Select Window > Preferences > J2EE

    2. Choose the appropriate J2EE level from the J2EE property settings. If you choose to create a new Enterprise Application project for this Web project, the J2EE level setting controls the level of the resulting EAR file as well.

    3. Check Use the same target server as the EAR Project. You must target the same server for both the Web and EAR project in order to deploy your Web application to the server properly. However, if you want to specify a different server for your Web project, in the Target server drop-down menu, select the application server that you want to target. This can be useful if the same Web project is included in two different EAR projects, each targeting different servers.

  8. Click Next.

  9. Select one or more of the Web Project features. The box on the right displays a description of each feature as you select it on the left. The default feature is, Default style sheet (CSS file). Accepting the default creates a default CSS file called Master.css, which is used for any HTML and JSP files included in the project. (Note that the next step assumes you have selected this option)

    If you want to create a project that uses Struts technology, select Add Struts support and click Next; the Struts Settings page appears. You can specify the version of Struts technology you want to use in your project, the package prefix, and whether or not you want to bundle the resources.

    Note: The Add Faces Base Components and WDO Relational database runtime options are available on the Features Page; however, you are not required to select these features when you create your Web project. If you add any Faces resources to your Web project, the Faces tooling will automatically be enabled.

    Web Project features
  10. Click Next.

  11. Select Use a default Page Template for the Web Site if you want your entire Web site to share a common page template. If you want to use one of the sample templates provided, select Sample Template and then choose one of the templates shown in the Thumbnail box. If you want to use a template of your own, select User-defined Template and then click Browse to select the template from the file system.

  12. Click Finish. The wizard creates a new project that reflects the J2EE folder structure that specifies the location of web content files, class files, class paths, the deployment descriptor, and supporting metadata.

    New Web Project

You can now begin creating or importing content for your Web project using Web Site Designer, Web resource editors (such as Page Designer), the New File wizards, or the Import wizards available from the File menu.

Viewing and editing a project's Java build path

A project's Java build path can either be defined when creating the project with the New Wizard or later in the project's property dialog. The Java build path settings dialog is the same in both cases. To view and edit a project's Java build path, follow these steps:

  1. Select the project you want to view or edit (titan-web).

  2. From the project's pop-up menu, select Properties.

  3. Select the Java Build Path page.

  4. Define the source entries for the build path on the Source page:

    • Click the Add Folder button to add source folders to the Java build path. The Remove button removes the selected folder(s) from the build path. Edit lets you modify the selected entry.

  5. On the Projects page, identify the other projects that are required for building this project (titan). The list shows all the existing Java projects from the workbench.

    Projects page

    NOTE: Each selected project is automatically added to the list of referenced projects.

  6. On the Libraries page, define the libraries required by your project. Libraries come in different forms. There are buttons for adding a library in each form. By default, each Java project has a 'JRE System Library' entry on the build path. This entry stands for the workbench's default JRE.

  7. On the Order and Export page, define the Java build path order. The recommended ordering is to have source entries before the library entries and the required projects.

Working in the References page in the deployment descriptor editor

The References page in the Web deployment descriptor editor lets you add or remove references to EJBs (Enterprise Java Beans) in the deployment descriptor. This page also lets you add or remove references to resources, resource environments, and JSP tag libraries.

To work with the References page of the Web deployment descriptor editor:

  1. Open a Web project in the Project Navigator.

  2. Double-click the Web project's Web Deployment Descriptor file in the Project Navigator. The Web deployment descriptor editor opens.

  3. Click the References tab to open the References page.

  4. Click one of the following tabs within the References page:

    • EJB tab

      EJB tab - lets you add or remove references to EJBs used in the application. You can provide a name for the reference (TravelAgent), a link to an enterprise bean in the current module or another module within the application, an EJB type (such as Session or Entity), the fully qualified name of the home interface, the fully qualified name of the remote interface, and a description. You can also enter the JNDI (Java Naming and Directory Interface) name that the servlet code uses to get a reference to an enterprise bean (ejb/com/titan/travelagent/TravelAgentHome):

      env = (Context) new InitialContext();
      home = env.lookup("ejb/com/titan/travelagent/TravelAgentHome");
      agentHome = (TravelAgentHome) PortableRemoteObject.narrow(home, TravelAgentHome.class);
      											

      EJB Reference added to web.xml:

      
      <web-app id="WebApp">
      	...
      	<ejb-ref id="EjbRef_1124278200583">
      		<ejb-ref-name>TravelAgent</ejb-ref-name>
      		<ejb-ref-type>Session</ejb-ref-type>
      		<home>com.titan.travelagent.TravelAgentHome</home>
      		<remote>com.titan.travelagent.TravelAgent</remote>
      		<ejb-link>titan.jar#TravelAgent</ejb-link>
      	</ejb-ref>
      </web-app>
      											
      											
    • EJB Local tab - lets you add or remove EJB local references to EJBs used in the application. The fields are similar to the ones in the EJB tab.

    • Resource tab - lets you add or remove resource references used in the application. You can also list and change details about the selected resource (including the Java Class type, the user roles that should be permitted to access specific resource collections), WebSphere Extensions (connection management and the level of transactional isolation), and WebSphere Binding information (the JNDI (Java Naming and Directory Interface) name that the servlet code uses to get a reference to an enterprise bean).

    • Resource Environment tab - lets you add or remove resource environment references used in the application. The fields are similar to the ones in the Resource tab.

    • JSP tag libraries tab - lets you add or JSP tag library references used in the application. You can also specify the location of each tag library.

Creating servlets

The Servlet wizard walks you through the process of creating Java servlets, step-by-step, and provides you with output files you can use "as is" or modify for your Web application. The resulting servlets run on the WebSphere Application Server or other J2EE-compliant Web server, and provide server-side processing for dynamic content.

To create a servlet, do the following:

  1. To launch the Servlet wizard, from the Web perspective select File > New > Servlet.

  2. In the Create a new Servlet page, supply the following:

    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 a name for the servlet. The Class name value should be the class name of the servlet. You should place the servlet in the Java source folder.

      Folder - /titan-web/JavaSource

      Java package - com.titan.servlets

      Class name - ReservationController

    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.

    Create a new Servlet page
  3. Click Next.

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

    Select a modifier
  5. Specify whether the servlet you create implements the SingleThreadModel interface by selecting the Use Single Thread Model option. This guarantees that there will not be simultaneous access to the same servlet instance, which has a tendency to stabilize thread execution ordering.

  6. 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 click Add. Click OK when you are finished.

  7. 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.

  8. Click Next.

  9. If you select the Add to web.xml check box, the servlet, along with its display name, and any URL mappings and initialization parameters associated with the servlet will be automatically included in the Web project web.xml file. Note that the Class name value provided in the first page of the wizard is automatically mapped on this page. The mapping is updated if you change the value in the Servlet Name field.

    Add to web.xml
  10. Click Finish.

    New servlet

The servlet is generated. To run the generated servlet, launch the WebSphere test environment.

Add the following code to the ReservationController servlet:


public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	doPost(req, resp);
}

					

public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String firstName = req.getParameter("firstName");
	String lastName = req.getParameter("lastName");
	String cruise = req.getParameter("cruise");
	Context env = null;
	TravelAgent agent = null;
	TravelAgentHome agentHome = null;
	Object home = null;
	try {
		env = (Context) new InitialContext();
		home = env.lookup("ejb/com/titan/travelagent/TravelAgentHome");
	} catch (NamingException ne) {
		log("ReservationController: can not lookup TravelAgentHome", ne);
		try {
			env.close();
		} catch (NamingException e) {
			log("ReservationController: can not close JNDI Context", e);
		}
	}

	agentHome = (TravelAgentHome) PortableRemoteObject.narrow(home, TravelAgentHome.class);

	try {
		agent = (TravelAgent) agentHome.create();
	} catch (CreateException ce) {
		log("ReservationController: can not create TravelAgent", ce);
	}
		
	agent.sendReservation(firstName, lastName, cruise);
	RequestDispatcher dispatch = req.getRequestDispatcher("/index.jsp");
	dispatch.forward(req, resp);
}

					

Add the following code to the com.titan.travelagent.TravelAgent interface:

public void sendReservation(String firstName, String lastName, String cruise) throws java.rmi.RemoteException;
					

Add the following code to the com.titan.travelagent.TravelAgentBean class:

public void sendReservation(String firstName, String lastName, String cruise) {
	try {
		ic = new javax.naming.InitialContext();
		qConnFactory = (javax.jms.QueueConnectionFactory) ic.lookup(fName);
		queue = (javax.jms.Queue) ic.lookup(qName);
	} catch (Exception e) {
		System.err.println("TravelAgentBean: JNDI lookup failed " + e);
	}

	try {
		qConn = qConnFactory.createQueueConnection();
		qSession = qConn.createQueueSession(false, javax.jms.Session.AUTO_ACKNOWLEDGE);
		qSender = qSession.createSender(queue);
Advertisement


DMCA.com