1. Trang chủ
  2. » Công Nghệ Thông Tin

WebSphere Studio Application Developer Version 5 Programming Guide part 24 ppt

10 211 0
Tài liệu đã được kiểm tra trùng lặp

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

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 10
Dung lượng 162,4 KB

Các công cụ chuyển đổi và chỉnh sửa cho tài liệu này

Nội dung

Adding a servlet to your Web project Application Developer provides a servlet wizard to assist you in adding servlets to your Web applications.. Alternatively, you can switch to the J2EE

Trang 1

Application Developer wizards not only support you in creating servlets, JSPs, and JavaBeans, but they also compile the Java code and store the class files in the correct folders for publishing to your application servers In addition, as the wizards generate project resources, the deployment descriptor file, web.xml, is updated with the appropriate configuration information for the servlets that are created You can test the resulting project resources within the Application Developer using the WebSphere Test Environment, or any other configured server that supports the chosen J2EE specification level

Working with 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.3, the supported API is Servlet 2.3

Servlets generate dynamic content by responding to Web client requests When

an HTTP request is received by the application server, the server determines which servlet is responsible for answering that request (based on the requested URI) 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

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

Adding a servlet to your Web project

Application Developer provides a servlet wizard to assist you in adding servlets

to your Web applications

To start it, select File -> New -> Other Select Web -> Servlet and click Next Alternatively, you can switch to the J2EE Navigator view, select the Java Source folder in your Web project folder, and select New -> Servlet from its context menu The wizard starts with the dialog shown in Figure 7-26

Trang 2

Figure 7-26 New servlet wizard (page 1)

The wizard’s first page will require you to fill out the following information:

Folder The source folder of your Web project In our case, it is

\ItsoProGuideBasicWeb\Java Source Java package The package in which the servlet class will be created For our

example, it should be itso.basicweb.control Class Name The servlet’s class name We will implement the ListAccounts

servlet

Superclass Usually, and this is true to our example, you will select the

javax.servlet.http.HttpServlet as your servlet’s superclass Application Developer requires you to select a class that implements the javax.servlet.Servlet interface

Trang 3

Modifiers These are the usual Java class modifiers We will go with

public Servlets can also be abstract or final, but not both Options The only option that you have here is to have your servlet

implement the SingleThreadModel interface This option should

only be selected for servlets that must have read/write state

accessed during their service methods The need to implement the SingleThreadModel interface probably indicates a poor design

Interfaces Which additional interfaces your servlet needs to implement Model No models are available for simple servlets

Click Next to proceed to the wizard’s second page, shown in Figure 7-27

Figure 7-27 New servlet wizard (page 2) This page lets you select the appropriate method stubs to be created in the servlet code These are the servlet’s life-cycle methods, along with its service

Trang 4

For our example, we need both doGet and doPost selected Both are read methods Usually, HTTP gets are used with direct links, when no information needs to be sent to the server HTTP posts are typically used when information in

a form has to be sent to the server

Only one instance of a servlet is created in the application server If you want to perform any initialization when the servlet instance is created, select the init method to be created This method is invoked after the servlet instance has been created and you can perform the initialization tasks

Another check box lets you select whether or not you want to generate stubs for the inherited abstract methods You should select it if your servlet is concrete Because constructors are not inherited in Java, you may also want to generate constructors that call their counterpart in the superclass

Finally, the wizard lets you choose whether or not to add the new servlet to the Web deployment descriptor If you choose to do so, and we do for our sample application, you can also define initialization parameters and their values, and the URLs mapped to the servlet We will stick to the default URL mapping suggested

by the wizard, which equals the servlet name

You can now click Finish to complete the process The servlet is generated and added to the project In the J2EE Hierarchy view you can see the servlet and its mapping in the Web module In the J2EE Navigator view you can see the servlet file ListAccounts.java inside the itso.basicweb.control package An editor is opened, where you can view and edit the generated servlet source code

Editing the servlet

Application Developer generates a skeleton servlet for you Your task is now to add code to the servlet in order to implement the required behavior for your needs The code is provided in:

\sg246957\sampcode\dev-web\servlet

Start by adding these import statements to the statements generated for you: import javax.servlet.http.HttpSession;

import itso.bank.model.Customer;

import itso.bank.model.Account;

import itso.bank.facade.Banking;

Next, change the doGet and doPost methods’ body to look like this:

public void doGet(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException {

performTask(req, resp);

}

Trang 5

public void doPost(HttpServletReq request, HttpServletResponse resp) throws ServletException, IOException {

performTask(req, resp);

}

As you can see, both methods call a third method, called performTask Because both doGet and doPost are read methods, and the Java API for handling the request parameters is the same no matter the request type, this works fine Finally, you need to code the performTask method (see Example 7-1)

Example 7-1 Servlet performTask method public void performTask(HttpServletRequest req, HttpServletResponse resp)

throws ServletException, IOException { try {

// Parameters // Get input parameter and keep it on the HTTP session String customerNumber = req.getParameter("customerNumber");

HttpSession session = req.getSession();

if (customerNumber == null) customerNumber =

(String) session.getAttribute("customerNumber");

else session.setAttribute("customerNumber", customerNumber);

// Control logic - Create the new banking facade Banking banking = new Banking();

// Retrieve customer and related accounts Customer customer = banking.getCustomer(customerNumber);

Account[] accounts = banking.getAccounts(customerNumber);

// Response - Set the request attributes for future rendering req.setAttribute("customer", customer);

req.setAttribute("accounts", accounts);

// Call the presentation renderer getServletContext().getRequestDispatcher("listAccounts.jsp")

.forward(req, resp);

} catch (Exception e) { req.setAttribute("message", e.getMessage());

req.setAttribute("forward", "index.html");

getServletContext().getRequestDispatcher("showException.jsp")

.forward(req, resp);

} }

Trang 6

The performTask method is divided into three main sections:

򐂰 The first section deals with the HTTP parameters This servlet expects to either receive a parameter called customerNumber (underlined) or none at all

If the parameter is passed, we store it in the HTTP session for future use If it

is not passed, we look for it in the HTTP session, because it might have been stored there earlier The parameter name equals the text field name in the index.html page

򐂰 The second section deals with the control logic We create a new Banking facade and use it to get the customer object and the array of accounts for that customer

򐂰 Finally, the third and last section sees that the presentation renderer

(listAccounts.jsp) gets the parameters it requires to perform its job

(customer and accounts, both underlined) The parameters are passed in the request context, because they are no longer needed once this request is answered

We could have written the presentation code in the servlet if we wanted to do so Instead, we chose to use JSPs, which were specially designed for that purpose Servlets do not make very good Web presentation renderers, because writing HTML code in Java is cumbersome

Save your changes and close the source editor

Linking an HTML page to a servlet

Before we write our JSP code, we complete the index.html file by linking it to the ListAccounts servlet that we have just created Open the index.html file and switch to the Design view Select the form element and open its properties view

by selecting Properties on the form’s context menu

The form’s action should be the ListAccounts servlet But you do not have to type that in yourself Instead, click -> Servlet and select the ListAccounts servlet from the pop-up list Remove the Web application context root:

From: /ItsoProGuideBasicWeb/ListAccounts <=== absolute URL

Finally, make sure that the Post method is selected The Attributes view is shown

in Figure 7-28

Trang 7

Figure 7-28 Form element attributes You could have added the link to the servlet in the Source view as the action attribute of the form:

<FORM action="ListAccounts" method="post">

Save the page and close the editor

Links view

Select index.html file and the Links view You should see the files (CSS file and image) and links (servlet, URL) that are used by the HTML file (Figure 7-29)

Figure 7-29 Links view

Working with JSPs

Now that we have managed to build our first static page and our first servlet controller, it is time to complete the cycle by writing our first JSP page:

listAccounts.jsp This page is responsible for presenting the list of accounts belonging to the given user

select servlet

servlet

Trang 8

When an application server such as WebSphere Application Server processes a request that involves a JSP file, it performs the following actions:

򐂰 Compiles the JSP file into executable Java code, if needed

If a previously compiled JSP class file can be found, and the source file is older than the compiled file, the application server does not have to recompile the JSP file

򐂰 Instantiates the JSP servlet, if needed

Because JSPs are just like any other servlet, there will probably be just one instance of each type in memory at the same time (unless they implement the javax.servlet.SingleThreadModel interface) So, if the JSP has already been processed in a previous request, chances are that resulting servlet object is still in memory and can be reused

򐂰 Sends the request to the JSP servlet for processing

򐂰 The JSP servlet renders the HTML result which is sent back to the Web client for output

JSP files are edited in Page Designer, the very same editor you used to edit the HTML page When working with a JSP page, though, Page Designer has additional elements (JSP tags) that can be used, such as JavaBean references, expressions, and scriptlets containing Java code

Creating a JSP

To create a JSP file, select the Web Content folder and select New -> JSP File

to open the new JSP file wizard (Figure 7-30)

򐂰 Because you had the Web Content folder selected when you started the wizard, the folder field comes filled in for you Type the file name

(listAccounts.jsp) into the appropriate field You do not have to type the file extension, as it will be automatically added for you

򐂰 We will be using HTML as the markup language, so leave it as is The options are the same as when you created a new HTML page

򐂰 If you select the Create as JSP Fragment check box, this file will be created

as a fragment that can be added to another JSP file Other JSP files can include JSP fragments using a JSP include directive Creating a fragment causes the resulting file to end in a jspf or jsf extension You will not be prompted for DOCTYPE information, because a fragment cannot stand alone

as a Web page, and it would invalidate any JSP file that included it

򐂰 We want the wizard to generate code without using any special models, so let the model field be set to none Your other option would be to generate a Struts JSP page, but that will be left for Chapter 10, “Developing Struts applications” on page 293

Trang 9

Figure 7-30 New JSP file wizard (page 1) Click Next to continue to the second page (Figure 7-31)

Trang 10

The wizard’s second page lets you add tag libraries from a variety of sources We

do not have any tag libraries on our example, but the steps to add a tag library would be:

򐂰 Click Add Tag Library to locate a tag library directive (TLD) file or a JAR file that contains a TLD file TLD URIs can be located in one of the following places:

– As a taglibname.tld file in the WEB-INF directory (most common)

– Within a JAR file located in the project lib directory that contains

\WEB-INF\taglibname.tld

– Within a JAR file external to the project

– In a loose tld anywhere in the project

򐂰 Taglib files are referenced in the Web deployment descriptor (web.xml) file on the References page

򐂰 In the Select a tag library dialog, either select one of the available tag libraries, or click Import to locate and add a tag library to the list, and then select it The dialog will automatically populate the informational fields that describe the tag library and its contents You must specify a Prefix value Click

OK to add the tag library

򐂰 As you add tag libraries, the Available Custom Tags list box displays the declaration of the tag along with the tag library directive If the selected TLD file is not registered in the web.xml file, it will be added automatically

We will skip working with tag libraries for now, so just click Next to proceed to the third page (Figure 7-32)

Note: We will work with tag libraries in Chapter 10, “Developing Struts

applications” on page 293

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