Escolar Documentos
Profissional Documentos
Cultura Documentos
1
WebSphere makes Web development a snap
Skill Level: Introductory Ron Ben-Natan (ron_bennatan@guardium.net) CTO and VP Guardium Inc.
07 Jan 2004 This tutorial demonstrates how to use WebSphere Studio V5.1.1 for building dynamic Web sites. The tutorial walks you through a simple example that makes use of Java servlets and JavaServer Pages in order to implement a simple messaging center. Using WebSphere Studio, you learn how to develop dynamic Web sites and then how to test and debug your code.
developerWorks
ibm.com/developerWorks
Site Developer is used in this tutorial but you can choose to download and use WebSphere Studio Application Developer V5.1.1 if you prefer -- all of the steps and screens remain identical. Application Developer includes all the functions within Site Developer, and other functions that will not be used in this tutorial.
Prerequisites
To run the examples in this tutorial, you'll need the following software: WebSphere Studio Version 5.1.1. WebSphere Application Server Version 5.1. You can download the latest trial version of Application Server at no charge.
Trademarks
IBM and WebSphere are trademarks or registered trademarks of IBM Corporation in the United States, other countries, or both. Windows and Windows NT are registered trademarks of Microsoft Corporation in the United States, other countries, or both. Java and all Java-based trademarks and logos are trademarks or registered
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved. Trademarks Page 2 of 42
ibm.com/developerWorks
developerWorks
trademarks of Sun Microsystems, Inc. in the United States, other countries, or both. UNIX is a registered trademark of The Open Group in the United States and other countries. Other company, product, and service names may be trademarks or service marks of others. IBM copyright and trademark information
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 3 of 42
developerWorks
ibm.com/developerWorks
Site level Web management templates and support Integrated easy-to-use visual layout tool for JSP and HTML file creation, validation editing, and debugging JavaScript editing and validation An extensible view, called the Library view, which allow users to catalog and organize reusable programming objects, such as HTML, JavaScript, and JSP code, along with files and tag libraries Image editing and animation Cascading Style Sheet (CSS) editing support HTTP/FTP import FTP export to a server Link viewing, parsing, validation, and management, which includes converting links, flagging broken links, and fixing links as resources are moved or renamed Enhanced wizard to create new servlets and add servlet mapping to the deployment description ( web.xml ) file Web project creation, using the J2EE container structure Generation of Web applications using wizards that create Web resources from database queries and bean
V5.1.1
In addition, WebSphere Studio V5.1.1 adds the following above and beyond V5: Web Site Designer allowing you to visually create, import, and manage complete Web sites An enhanced Web Perspective making building HTML, JSP and Javascript easier Enhancements to Page Designer and Visual Editor for Java making your development experience even better Hot method replacement allowing code you change within the debugger to be immediately replaced within your embedded server environment; you no longer have to restart the server during your debug cycle Support for the de-facto Java application framework standard Struts 1.1
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 4 of 42
ibm.com/developerWorks
developerWorks
The Web Services Description Language (WSDL) Editor and the Web Services Explorer used for building Web services conforming to the WS-I Basic Profile 1.0 Support for Java APIs for XML based RPC (JSR-101) and Enterprise Web Services in Java (JSR-109). Support for DB2 UDB V8.1 Support for SQLJ WebSphere Application Server (WAS) 5.1 is now the default embedded test environment Improved performance
developerWorks
ibm.com/developerWorks
inputs. The shift to dynamic Web sites involves a new server -- the application server. Values sent within the HTTP request are passed from the Web server to the application server and used by application code. This application code executes within the context of the application server and performs business logic, accesses data stores, and more. It then dynamically generates the HTML that is returned to the browser within the HTTP response:
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 6 of 42
ibm.com/developerWorks
developerWorks
familiar with these technologies, you can go to the Building a dynamic Web application section.
Servlets
Servlets are Java classes that implement the Servlet interface. The Servlet interface defines a doGet and a doPost method for handling client requests. HTTP Servlets handle HTTP requests encapsulated as an HTTPServletRequest object. The HTTPServletRequest object is passed as an argument to the service method. Using this object, the servlet developer accesses parameters sent as part of the request, cookies delivered with the request, and headers within the HTTP request. The servlet generates dynamic content, usually as HTML. Using an HTTPServletResponse object, the servlet developer writes the dynamic content onto a servlet output stream. This creates the page that is returned to the browser. As a simple example, the following servlet retrieves a username from the request parameters and prints a hello string:
import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class SimpleHelloServlet extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) { this.doPost(req, res); } public void doPost(HttpServletRequest req, HttpServletResponse res) { String username = req.getParameter("username");
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 7 of 42
developerWorks
ibm.com/developerWorks
// tell the browser that the content is an HTML page res.setContentType("text/html"); // Generate the dynamic content PrintWriter out = res.getWriter(); out.println("<HTML><BODY><H3>"); out.println("Hello " + username); out.println("</H3></BODY></HTML>"); out.close(); }
JavaServer Pages
Hard coding HTML within Java code is bad form because it creates inflexible code. HTML elements become strings hard coded within Java print commands (as shown in Servlets). That means that tools for building Web pages cannot be used, and that the role of the Web page designer -- which should be separate from that of the Java developer -- is not well supported. JSPs solve this problem by embedding Java code that generates dynamic content within the HTML page. As an example, the SimpleHelloServlet can be replaced with the following JSP:
<HTML> <BODY> <H3> <% out.println(request.getParameter("username")); %> </H3> </BODY> </HTML>
In this scheme, HTML elements are well represented and Java code is embedded using special scriplet tags (< % ... %> or <jsp:scriplet> ... </jsp:scriplet> ). Servlets and JSP files are used to generate dynamic content. While this content can be of any type, it is usually HTML when building dynamic Web sites.
Taglibs
JSPs allow embedding Java code within tags from the HTML tag set. That means that the tags in a JSP come from a finite and limited group that deals mostly with layout. This is limited in terms of how expressive you can make your tag-centric page; much of the behavior tends to be implemented as calls to various Java methods and the page ceases to "belong" to the page designer. WebSphere Studio V5.1.1 supports the JSP1.2 standard and with it custom tag libraries - taglibs. Taglibs allow you to extend the tag/element vocabulary of your JSP by allowing you to define new elements that can be used inside a JSP as any other tag. By providing a tag implementation class you define how the Web container will process the tag when the JSP is evaluated. For example, you can
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 8 of 42
ibm.com/developerWorks
developerWorks
easily implement a new tag that will print out the value of the username parameter in which case the JSP code fragment from the previous panel could become a simple:
<HTML> <BODY> <H3> <USERNAME/> </H3> </BODY> </HTML>
This example would be relevant in the unlikely event that you decide build a specialized implementation for printing out the username parameter. A more common JSP would result if you used one of the core tags in the JavaServer Pages Standards Tag Library (JSTL) in which case the page would become:
<HTML> <BODY> <H3> <c:out value="${param.username}" /> </H3> </BODY> </HTML>
Taglibs make authoring JSP pages easier and increase productivity by encouraging a division of labor between library developers and library users. Taglibs are create by a developer who is an implementation expert and are used by Web page authors who, by building on these libraries, can produce most functional and higher quality applications. Because taglibs are part of the JSP1.2 standard they are also portable and supported by all major J2EE environments. This in turn means that many people write taglibs and that you can often find great reusable resources. Two important starting point are the Sun taglib page at: http://java.sun.com/products/jsp/taglibraries.html and the Jakarta taglib project at http://jakarta.apache.org/taglibs/.
Dynamic HTML
Dynamic HTML (DHTML) = HTML + Javascript + Document Object Model (DOM) + Cascading Style Sheets (CSS). While DHTML is not the topic of this tutorial, it is important to remember that DHTML is an important technology in building dynamic Web sites. DHTML is a collection of client-side technologies. A DHTML page is delivered by the server and runs within the Web browser, so the browser runs the code within the DHTML page. A DHTML page is first and foremost an HTML page. The DHTML developer can embed Javascript scripts within this HTML page. These scripts run on the client and
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved. Trademarks Page 9 of 42
developerWorks
ibm.com/developerWorks
improve the user experience. An example is the use of Javascript to do client-side validations to eliminate unnecessary network traffic. Most of the scripts that run within the browser need to access the elements on the page, i.e., the HTML elements. The Document Object Model (DOM) defines a set of objects that are directly related to the HTML elements on the page. The DOM allows Javascript code to refer to each HTML element on the page as an object with attributes and methods. As an example, Javascript code can access a text field in an HTML form as an object, retrieve its current value, and even change the value. The Javascript code can even access an HTML table as an object and add rows by manipulating the table object -- all completely within the browser. Cascading Style Sheets (CSS) are used to associate formatting information with HTML elements. Instead of hard coding this information as HTML markup (such as bold and italics), all formatting information is externalized to a CSS file and associated with the HTML elements. This makes it easy to quickly and uniformly change the appearance of a complete Web site. Armed with this impressive set of server-side and client-side technologies, you're now ready to turn to the tutorial's example of a dynamic Web site -- the messaging center application.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 10 of 42
ibm.com/developerWorks
developerWorks
A user starts by accessing a login of the form http://localhost/MessagingCenter/login.jsp. The JSP engine processes the JSP files and generates an HTML form that is returned and displayed by the browser. The user enters a username and clicks the submit button. This makes a call to the MessageCenterLoginServlet running on the application server. If there is an error, the servlet forwards handling to the login JSP. The login JSP creates an error message and presents the login form for the user to try again. If the username is correct, the servlet prepares the object with the message data and forwards handling to the message center JSP. The JSP generates dynamic content, which is based on the messages, as an HTML page that is returned to the browser. Using an HTML form, the user can send a message to another user by clicking the submit button, which makes a call to AddMessageServlet.
developerWorks
ibm.com/developerWorks
If you're following along with a running copy of WebSphere Studio V5.1.1, select File => New => Project to create a new project. A project contains files and folders, and it's how you organize resources within the WebSphere Studio V5.1.1 workbench. WebSphere Studio V5.1.1 supports many types of projects, as shown in the left pane of the wizard below.
Select Web in the left pane and Dynamic Web Project in the right pane, and then click Next. WebSphere Studio V5.1.1 will create a new project for a Web application and generate resources required for dynamic Web applications such as servlets, JSP files, HTML pages, etc. Enter a project name -- MessagingCenter in this example. Before letting WebSphere Studio V5.1.1 create the project lets add a few standard tag libraries. Click on the Configure advanced options check box and click Next. In the next panel leave the default J2EE level (1.3) because you need to have version 2.3 of the servlet specification and version 1.2 of the JSP specification. Click Next.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 12 of 42
ibm.com/developerWorks
developerWorks
Select Tag Libraries for accessing JSP objects, Utility Tag Libraries and the JSP Standard Tag Library -- and click Finish. WebSphere Studio V5.1.1 goes to work and creates the Web project and the various resources needed for a Web application. The WebSphere Studio V5.1.1 workbench now assumes the Web Perspective and in the Project Navigator you will see both the MessagingCenter project as well as a DefaultEAR project (encapsulating your work in an enterprise archive that can later be installed on a production WebSphere Application Server). A perspective defines the initial set and layout of panes in the workbench. This concept introduces a role-based customization of the views and editors; it is a user-centric metaphor bringing together all the tools useful for a certain role. Views provide different ways to look at a certain resource, and editors are used to create and modify code. WebSphere Studio V5.1.1 includes a variety of different editors suitable for specific file types such as HTML files, JSP files, Java source files. Now that you've created the project, you're ready to start creating some of the resources.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved. Trademarks Page 13 of 42
developerWorks
ibm.com/developerWorks
This brings up a wizard in which you select Java in the left pane and Class in the right pane. Click Next. This brings up the Java class editor. You need to set the class name (User) and the package name (com.ibm.tutorials.wssd). All the rest (including the superclass java.lang.Object) remains as default. At this point, you also need to create a Java class that represents the message object. The code for both classes is shown in User and Message class code.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 14 of 42
ibm.com/developerWorks
developerWorks
developerWorks
ibm.com/developerWorks
package com.ibm.tutorials.wssd; public class Message { private String senderName = null; private String text = null; public Message(String senderName, String text) { this.senderName = senderName; this.text = text; } public String getSenderName() { return this.senderName; } public String getText() { return this.text; } }
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 16 of 42
ibm.com/developerWorks
developerWorks
Once you've fixed all errors, select Project => Rebuild All and save your current workbench. You're now all set with the back-end entities and you're ready to build the servlets that will implement the "business transactions."
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 17 of 42
developerWorks
ibm.com/developerWorks
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 18 of 42
ibm.com/developerWorks
developerWorks
When the wizard completes its work, you'll have a skeleton servlet class with the following code:
package com.ibm.tutorials.wssd; import java.io.IOException; import javax.servlet.Servlet; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /**
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 19 of 42
developerWorks
ibm.com/developerWorks
* @version 1.0 * @author */ public class MessageCenterLoginServlet extends HttpServlet { /** * @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } /** * @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { } }
Now it's time to implement the doPost method. First, you need to get the username from the request. If it is null, set an error message and dispatch the handling to the login JSP (all HTML will be generated by JSP files). The login JSP will then generate the HTML based on this error message:
String username = req.getParameter("username"); if (username == null) { // Can't perform a login with no user name. // Set an error message and redirect to login page. req.setAttribute("errorMessage", "User name not specified"); // Dispatch to login.jsp using the RequestDispacther // Use a relative URL for simplicity RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp"); disp.forward(req, resp); }
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 20 of 42
ibm.com/developerWorks
developerWorks
Back to the code -- with the username in hand, you can proceed to look up the User object using the facilities coded in the User class. If a User object is not found, you can use another error message. If a User object is found, place it in the session object and forward handling to the JSP file responsible for displaying the messages:
// Otherwise proceed to looking for the User object User user = User.getUser(username); if (user == null) { req.setAttribute("errorMessage", "User not found"); RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp"); disp.forward(req, resp); } // Put the user object in the session object and forward to messageCenter JSP HttpSession session = req.getSession(true); session.setAttribute("user", user); RequestDispatcher disp = getServletContext().getRequestDispatcher("/messageCenter.jsp"); disp.forward(req, resp);
This completes the servlet responsible for accessing the "business objects." You are ready for the servlet handling the "business transaction."
The AddMessageServlet
AddMessageServlet is responsible for adding a new message to one of the users, in effect sending a text message from one user to another. This functionality will be
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 21 of 42
developerWorks
ibm.com/developerWorks
invoked from an HTML form within the message center. Building the servlet follows the same process as that of building the MessageCenterLoginServlet. The method implementing the sending of the message has two parameters: the username of the recipient of the message, and the text message to be sent. The originator of the message is retrieved from the session object:
package com.ibm.tutorials.wssd; import java.io.IOException; import javax.servlet.ServletException; import import import import import javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServletResponse; javax.servlet.RequestDispatcher; javax.servlet.http.HttpSession;
/** * @version 1.0 * @author */ public class AddMessageServlet extends HttpServlet { /** * @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { this.doPost(req, resp); } /** * @see javax.servlet.http.HttpServlet#void (javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse) */ public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { String recipient = req.getParameter("recipient"); String messageText = req.getParameter("messageText"); // Get the session object. If it does not exist or if there is no User object // in it then we cannot process the message send and need to ask the user // to login once more HttpSession session = req.getSession(false); if (session == null) { req.setAttribute("errorMessage", "Need to login before sending a message"); RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp"); disp.forward(req, resp); } User user = (User)session.getAttribute("user"); if (user == null) { req.setAttribute("errorMessage", "Need to login before sending a message"); RequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp"); disp.forward(req, resp); } // Need to check that there is a recipient and that it is a legal user // This is omitted for lack of interest // Otherwise proceed to send the message
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 22 of 42
ibm.com/developerWorks
developerWorks
The back-end code is now ready. It is time to move on to build the presentation layer.
Building login.jsp
WebSphere Studio V5.1.1 has an editor for building JSP files following the feel of HTML builders. To create the JSP file, right-click on the Web Content folder and select New => JSP File. Then enter the JSP file name as shown below:
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 23 of 42
developerWorks
ibm.com/developerWorks
The New JSP File wizard can help you specify many of the JSP's attributes. While you can click the Finish button on the first step of the wizard, you can also check Configure advanced options and continue with the other panels in the wizard. Using the wizard you can specify explicit init and destroy method stubs, initialize parameters for the servlet that is automatically generated from the JSP, attach style sheets, define the DTD used in the JSP (WebSphere Studio V5.1.1 supports XHTML) and specify the tag libraries to be used from within the JSP -- the topic of the next panel. Go ahead and click the Next button.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 24 of 42
ibm.com/developerWorks
developerWorks
WebSphere Studio V5.1.1 shows you a form of a catalog of taglibs including tag libraries from the Apache Jakarta project, the JSTL core library and much more. You can also import additional tag libraries into the catalog using the Import... button. Select the JSTL core library and click OK. You can change the prefix that will be used within the JSP but the default for the core tag library is the letter c. Back on the panel from which you added the tag library click the Finish button:
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 25 of 42
developerWorks
ibm.com/developerWorks
Now you're ready to start designing the JSP file. Use the central pane in the workbench to design your page. You can drag and drop elements from the toolbar. You can also insert elements from the Insert menu bar item.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 26 of 42
ibm.com/developerWorks
developerWorks
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 27 of 42
developerWorks
ibm.com/developerWorks
The identifier of the bean throughout the page is errorMessage and the bean should be retrieved from the request object (remember from the MessageCenterLoginServlet that the error message is placed using request.setAttribute(errorMessage) ). The class of the bean is a String. Once this bean is available in the context of the page, you can display the message using a printing element from a taglib. Select JSP => Insert Custom. Then pick out in the right pane, click Insert and then Close and adjust the value to print out the error message variable. Note that you could also have chosen to use a cout custom element with a value of ${param.errorMessage} in which case the use bean element would not have been necessary.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 28 of 42
ibm.com/developerWorks
developerWorks
Click Source at the bottom of the design pane to see the generated JSP source code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <HTML> <HEAD> <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %> <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1" %> <META http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <META name="GENERATOR" content="IBM WebSphere Studio"> <META http-equiv="Content-Style-Type" content="text/css"> <LINK href="theme/Master.css" rel="stylesheet" type="text/css"> <TITLE>login.jsp</TITLE> </HEAD> <BODY> <P></P> <jsp:useBean id="errorMessage" class="java.lang.String" scope="request"></jsp:useBean> <c:out value="${errorMessage}"></c:out> <HR> <FORM action="/MessagingCenter/MessageCenterLoginServlet" target="_self"> <INPUT type="text" name="username" size="20"> <INPUT type="submit"></FORM> </BODY> </HTML>
You're done building your first JSP file and are ready to move on to the second.
Building messageCenter.jsp
The messageCenter JSP is very similar to the login JSP. Start by creating a new JSP file by right-clicking on the Web Content folder in the Navigator pane and selecting New => JSP File. Enter messageCenter.jsp as the JSP name, click Next, add the JSTL taglib and click Finish. Then move over to the designer and
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 29 of 42
developerWorks
ibm.com/developerWorks
drag the following elements onto the canvas: A use bean element for getting the User Static text (simply type in the text you want to display, in our case the string "Welcome") Property display element for displaying the username Static text ("Your messages are as follows") HTML table Within the table you need to place a Java loop. Each iteration of the loop creates a new TR element with the message sender and text in TDs. The loop is created using the JSTL core tag library, which supports iteration as follows: Select JSP => Insert Custom... This opens the Insert Custom Tag wizard. The wizard displays all the taglibs in your JSP and the available custom tags:
Select forEach for an iteration loop and click Insert. Iteration for this element should be on ${user.messages}. HR element A form for sending a new message
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 30 of 42
ibm.com/developerWorks
developerWorks
A text field for the recipient of the message A text area for the message text A submit button for the form When you're done with the designer, the page should look as follows:
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 31 of 42
developerWorks
ibm.com/developerWorks
<P><jsp:useBean id="user" class="com.ibm.tutorials.wssd.User" scope="session"> </jsp:useBean>.<BR>Welcome <jsp:getProperty name="user" property="name" />. Your messages as following:<BR> </P> <TABLE border="1"> <TBODY> <TR> <TD width="217">From</TD> <TD width="258">To</TD> </TR> <c:forEach items="${user.messages}" var="aMessage"> <TR> <TD width="217"><c:out value="${aMessage.senderName}"/></TD> <TD width="258"><c:out value="${aMessage.text}"/></TD> </TR> </c:forEach> </TBODY> </TABLE> <HR> <FORM action="/MessagingCenter/AddMessageServlet" method="get" target="_self" >Send message to: <INPUT type="text" name="recipient" size="20"><BR> <TEXTAREA rows="2" cols="20" name="messageText"></TEXTAREA> <BR> <INPUT type="submit"> </FORM> </BODY> </HTML>
You're done with the coding of the application and can move on to testing the message center. Before doing so rebuild the project.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 32 of 42
ibm.com/developerWorks
developerWorks
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 33 of 42
developerWorks
ibm.com/developerWorks
The application will be published to the server and the test environment will be initialized. You will see many printouts on the console; the last two lines should be of the form:
[11/29/03 9:48:40:507 EST] 3e864999 WsServer A WSVR0001I: Server server1 open for e-business [11/29/03 9:49:04:071 EST] 4c4498a WebGroup I SRVE0180I: [MessagingCenter] [/MessagingCenter] [Servlet.LOG]: /login.jsp: init
The phrase "Server ... open for e-business" means that the WebSphere Application Server environment has been successfully started.
An example message
The top right pane is a browser view that displays the login HTML (the HTML page generated by login.jsp). If you proceed to log in using one of the fixed usernames, you can start sending messages among the users. Remember that since messages are not persistent, all these messages will be lost if you shut down the server. As an example, suppose you want to send a message from Joe to Jane. Log in as Joe as follows:
In Joe's message center enter the text for a message to send to Jane and click Submit:
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 34 of 42
ibm.com/developerWorks
developerWorks
Now, go back to the login page and login as Jane; Jane's message center should look as follows:
developerWorks
ibm.com/developerWorks
One of the really great things about WebSphere Studio V5.1.1 is that the WebSphere test environment is very tightly integrated. That means that you don't have to develop your application, deploy it on a server (with all kinds of print commands), look at the log files, and figure out what went wrong. You can do everything within one integrated development environment using a single set of tools. For example, suppose that an exception occurs when you run the application. You can add a breakpoint by right-clicking on the left border of the code and setting a breakpoint as shown below:
You can also simply double-click on the right of the pane. This sets a breakpoint in the code, displayed as a blue-green circle:
When running the application, the server will stop at the breakpoint within the Server Perspective (note that you have to run the server in debug mode - for example, instead of selecting Run on Server right-click on login.jsp and select Debug on Server ). When you login next time you will be asked whether you want to enter and
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved. Trademarks Page 36 of 42
ibm.com/developerWorks
developerWorks
The Inspector
The Inspector is another useful tool. Suppose that once you have stopped at the breakpoint you want to know what string value is stored in the username variable. Double-click on the variable to mark the variable, then right-click and pick the Inspect entry. The top right pane now allow you to view the value of the marked variable as follows (in our case the value is "Jane"):
Finally, remember that WebSphere Studio V5.1.1 is a very well-integrated environment. If you change code even within a running application you can see the
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 37 of 42
developerWorks
ibm.com/developerWorks
Packaging
Now that you have tested the message center and feel comfortable with the Web application, you're ready to deploy it on a WebSphere Application Server. You need to package your Web application in a Web Archive (WAR) file within a Enterprise Archive (EAR). Recall that when you created the MessagingCenter project WebSphere Studio V5.1.1 automatically created a DefaultEAR project for you - all in order to help in the packaging process. To create the EAR file, right-click on the MessagingCenter folder and select Export:
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 38 of 42
ibm.com/developerWorks
developerWorks
In the Enterprise Application project name drop down list, select DefaultEAR. In the Destination field, enter the location and name of the EAR file you want to create. Finally, click Finish.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 39 of 42
developerWorks
ibm.com/developerWorks
Section 8. Summary
In this tutorial you learned how to use WebSphere Studio V5.1.1 to develop an end-to-end Web application. Using both servlets and JSPs the tutorial demonstrated the use of WebSphere Studio V5.1.1 to develop a basic messaging center. Starting with the back-end Java code for managing users and messages, you then built a set of servlets and JSP files implementing messaging functionality and generating a presentation layer in the form of HTML pages. These HTML pages were dynamically generated based on the data maintained by the Java objects. Once development was completed, you used the WebSphere Studio V5.1.1 server tools to test and debug your dynamic Web site. Finally, you learned how to package your Web application for deployment in a WebSphere Application Server.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 40 of 42
ibm.com/developerWorks
developerWorks
Resources
Learn A tutorial on building Java HTTP servlets is available on developerWorks. The Java Servlet technology home page includes the latest specification as well as a reference servlet server implementation. The JavaServer Pages home page includes the latest specifications as well as pointers to custom tag libraries and other advanced JSP technologies. The DHTML school Web page includes resources, examples, and reference materials. For information on the WebSphere Studio Family of Development tools, see http://www-3.ibm.com/software/info1/websphere/index.jsp?tab=products/studio. The Eclipse project can be found at www.eclipse.org The Apache Jakarta Taglib project can be found at http://jakarta.apache.org/taglibs/. The Sun tag library page can be found at http://java.sun.com/products/jsp/taglibraries.html. Stay current with developerWorks technical events and Webcasts. Get products and technologies Register to download a copy of WebSphere Application Server. Build your next development project with IBM trial software, available for download directly from developerWorks. Discuss Participate in the discussion forum for this content.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 41 of 42
developerWorks
ibm.com/developerWorks
and co-authored numerous books, including CORBA: A Guide to Common Object Request Broker Architecture, CORBA on the Web, and The San Francisco Developer's Guide, all published by McGraw-Hill; IBM WebSphere Starter Kit and IBM WebSphere: The Complete Reference, both published by Osborne/McGraw-Hill; and Integrating Service Level Agreements published by John Wiley & Sons. He is also the author of numerous articles and tutorials.
Building dynamic Web sites with WebSphere Studio V5.1.1 Copyright IBM Corporation 2004. All rights reserved.
Trademarks Page 42 of 42