wesdynweb5-a4

40
Building dynamic Web sites with WebSphere Studio V5 Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/ Table of Contents If you're viewing this document online, you can click any of the topics below to link directly to that section. 1. Introduction ............................................................. 2 2. Elements of dynamic Web sites ..................................... 5 3. Building a dynamic Web application ............................... 11 4. Building the back end: Java and servlets ......................... 15 5. Building the presentation layer: JSP ............................... 25 6. Testing the message center ......................................... 34 7. Summary ................................................................ 39 Building dynamic Web sites with WebSphere Studio V5 Page 1 of 40

Upload: sushant-puranikmath

Post on 25-May-2017

215 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: wesdynweb5-a4

Building dynamic Web sites withWebSphere Studio V5

Presented by WebSphere Developer Domain

www7b.software.ibm.com/wsdd/

Table of ContentsIf you're viewing this document online, you can click any of the topics below to link directly to that section.

1. Introduction ............................................................. 22. Elements of dynamic Web sites ..................................... 53. Building a dynamic Web application ............................... 114. Building the back end: Java and servlets ......................... 155. Building the presentation layer: JSP ............................... 256. Testing the message center ......................................... 347. Summary ................................................................ 39

Building dynamic Web sites with WebSphere Studio V5 Page 1 of 40

Page 2: wesdynweb5-a4

Section 1. Introduction

Should I take this tutorial?

You should take this tutorial if you are a developer or Web site builder and you want toquickly learn how to use WebSphere Studio V5 to build dynamic Web sites. The tutorialassumes basic knowledge of HTML and Java. Because WebSphere Studio V5 is easyto use, you'll find the tutorial easy to follow even if you're a beginner to HTML and Java.

Although downloading WebSphere Studio V5 is not a prerequisite for completing thistutorial, it does make the tutorial easier to follow. You can download the applicationfrom the Tools and resources on page 3 page. The installation process isstraightforward and hassle free, although you will need to complete a short registrationform.

What is this tutorial about?

This tutorial illustrates how to develop a Web application using Java servlets andJavaServer Pages (JSP), how to organize code in a project within WebSphere StudioV5, and how to use Java servlets and JSP files to generate dynamic HTML content. Italso shows how to test and debug code within WebSphere Studio V5 and how topackage a Web application for deployment on a WebSphere Application Server.

The tutorial makes use of a simple application -- the messaging center. Using themessaging center, users can log in and view messages that have been sent to them.They can also send messages to any other user that has access to the messagingcenter. Using WebSphere Studio V5 in conjunction with Java, Java servlet and JSPtechnologies, you will build the following:

• User and Message Java classes

• Two JSP forms: login.jsp and messageCenter.jsp

• Two servlets: MessageCenterLoginServlet and AddMessageServlet

What's new in WebSphere Studio Version 5

WebSphere Studio V5 is a major revision of WebSphere Studio and has many featuresabove and beyond those that were available in V4. WebSphere Studio V5 hasimproved functionality in all aspects of Java and Web development, including:

• Support for J2EE 1.3 including EJB 2.0, Servlet 2.3, and JSP 1.2 levels

• Concurrent support for WebSphere Application Server Version 4 (J2EE 1.2) andWebSphere Application Server Version 5 (J2EE 1.3)

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 2 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 3: wesdynweb5-a4

• Accessibility support

• Enhanced integration with Rational ClearCase LT and new support for namespaceversioning

• Numerous updates and new functions for Java, Web services, XML, Database, Testand Analysis, and Web components

WebSphere Studio V5 also improves upon the existing wizards and tools, creating aneven better integrated Web development environment for building dynamic Webapplications. The Web development environment includes:

• Custom JSP tags (taglib) support, based on the JSP 1.2 specification

• New support for XHTML

• 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 andorganize 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 mappings to thedeployment description (web.xml) file

• Web project creation, using the J2EE container structure

• Generation of Web applications using wizards that create Web resources fromdatabase queries and beans

Tools and resources

The following tools are necessary if you plan to run the examples in this tutorial:

• WebSphere Studio Version 5 trial edition. At the time of writing this tutorial, theWindows version of the WebSphere Studio download includes WebSphereApplication Developer and the Linux version includes the more limited WebSphereStudio Site Developer. However, tools exist in both versions to enable readers tocomplete the examples in this tutorial.

• WebSphere Application Server for Developers Version 5 trial edition.

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 3 of 40

Page 4: wesdynweb5-a4

About the author

Ron Ben-Natan, a Studio B (www.studiob.com) author, is VP, Technology at RobinLissak Associates. Prior to that he worked for companies such as Intel, AT&T BellLaboratories, Merrill Lynch, J.P. Morgan and ViryaNet. He has a Ph.D. in ComputerScience in the field of distributed computing and has been architecting and developingdistributed applications for over 15 years. His hobby is writing about how technology isused to solve real problems, and he has authored and co-authored numerous books,including CORBA: A Guide to Common Object Request Broker Architecture, CORBAon the Web, and The SanFrancisco Developer's Guide all published by McGraw-Hill ;IBM WebSphere Starter Kit and IBM WebSphere: The Complete Reference bothpublished by Osborne/McGraw-Hill; and Integrating Service Level Agreementspublished by John Wiley & Sons. He is also the author of numerous articles andtutorials. He can be reached at [email protected].

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 4 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 5: wesdynweb5-a4

Section 2. Elements of dynamic Web sites

The static Web

When the World Wide Web was born, it consisted of static Web sites. Web sitesconsisted of static documents (mostly HTML pages) that were accessible through Webservers. Users used Web browsers to access these Web sites. A Web browsercommunicated with a Web server over the Hyper Text Transfer Protocol (HTTP). Usingan HTTP request, the browser communicated with the Web server and asked to getaccess to a certain document. The Web server managed a set of documents stored ona file system. When asked for a document, it would retrieve it and return it within anHTTP response:

The evolution of the dynamic Web

Technology visionaries saw that the Web model could be more powerful if the pagesreturned to the browser were not statically stored on a file system. Pages could begenerated by accessing data stored in databases, by accessing legacy applicationsand reformatting their user interface, and by performing computations based on userinputs.

The shift to dynamic Web sites involves a new server -- the application server. Valuessent within the HTTP request are passed from the Web server to the application serverand used by application code. This application code executes within the context of theapplication server and performs business logic, accesses data stores, and more. It thendynamically generates the HTML that is returned to the browser within the HTTPresponse:

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 5 of 40

Page 6: wesdynweb5-a4

A new generation of tools

Paralleling the advancements made on the server side, browsers also became better.Early browsers could parse simple HTML and present the page. Today's browsersinclude powerful layout engines, the ability to execute scripts, and even a Java VM forrunning Java on the client (in the form of applets). Using a technology called DynamicHTML (DHTML), the pages returned to the browser can themselves include manydynamic components that make for a better user experience.

Powerful application models require powerful tools. When Web sites consisted of staticHTML pages, developers used HTML editors to build static content. For buildingdynamic Web sites, developers need a new generation of tools. These tools need tofacilitate building applications that include server-side components such as servletsand JSP. They also need to support the entire code/test/debug life cycle and need tocombine advanced testing and debugging environments in addition to a developmentenvironment. WebSphere Studio V5 is such a tool.

The rest of this section provides an overview of the client- and server-side technologiesthat are an integral part of the message center application. If you're familiar with thesetechnologies, you can go to the Getting started with WebSphere Studio V5 on page 11section.

Java, servlets, and JSP

Java has emerged as the premier environment for building server-side applicationcode. Using Java makes it easy to build well-structured, object-oriented code, toaccess data stores, and to build robust business logic.

In the context of this tutorial, back-end Java code runs within a Java application server.

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 6 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 7: wesdynweb5-a4

A Java application server uses a Java Virtual Machine (JVM) to execute Java code.The Java code in this tutorial includes objects representing real-world entities (likeusers and messages) as well as servlets and JSP.

You'll build all your code in this tutorial within WebSphere Studio V5. This singleintegrated environment allows you to simply compose your business entities, build thebusiness transactions using servlets, and build the JSP files used to generate the userinterface. WebSphere Studio V5 supports the servlet specification version 2.3 and theJSP specification version 1.2. As part of JSP 1.2, WebSphere Studio V5 also supportcustom tag libraries (sometimes called taglibs).

Servlets

Servlets are Java classes that implement the Servlet interface. HTTP servlets inheritfrom the HttpServlet class where the doGet and doPost methods are defined tohandle HTTP requests encapsulated as an HTTPServletRequest object. Usuallyyou would implement one of these methods to perform the specific action you needand implement the second as a call to the first - unless you want GET and POST to behandled differently. The HTTPServletRequest object is also passed as an argumentto the service method - a method that you would normally not implement becausethe default is to have it call either doGet or doPost depending on the HTTP request.Using this object, the servlet developer accesses parameters sent as part of therequest, cookies delivered with the request, and headers within the HTTP request. Theservlet generates dynamic content, usually as HTML. Using anHTTPServletResponse object, the servlet developer writes the dynamic content ontoa 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 requestparameters 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");// tell the browser that the content is an HTML pageres.setContentType("text/html");

// Generate the dynamic contentPrintWriter out = res.getWriter();out.println("<HTML><BODY><H3>");out.println("Hello " + username);out.println("</H3></BODY></HTML>");out.close();

}

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 7 of 40

Page 8: wesdynweb5-a4

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 inServlets on page 7 ). This 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 theJava developer -- is not well supported. JavaServer Pages (JSP) solve this problem byembedding Java code that generates dynamic content within the HTML page. As anexample, 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 embeddedusing special scriplet tags ( <% ... %>).

Servlets and JSP files are used to generate dynamic content. While this content can beof any type, it is usually HTML when building dynamic Web sites.

Taglibs

JSPs allow embedding Java code within tags from the HTML tag set. This means thatthe 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 ofthe behavior tends to be implemented as calls to various Java methods and the pageceases to "belong" to the page designer.

WebSphere Studio V5 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 allowingyou to define new elements that can be used inside a JSP as any other tag. Byproviding a tag implementation class you define how the Web container will processthe tag when the JSP is evaluated. For example, you can easily implement a new tagthat will print out the value of the username parameter in which case the JSP codefragment from the previous panel, JavaServer Pages on page 8 , could become asimple:

<HTML><BODY><H3> <USERNAME/></H3></BODY></HTML>

This example would only be relevant in the unlikely event that you decide to build aspecialized implementation for printing out the username parameter. A more common

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 8 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 9: wesdynweb5-a4

JSP would result if you used one of the core tags in the JavaServer Pages StandardsTag 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 adivision of labor between library developers and library users. Taglibs are created bydevelopers who are implementation experts and are used by Web page authors who,by building on these libraries, can produce more functional and higher qualityapplications.

Because taglibs are part of the JSP1.2 standard, they are also portable and supportedby all major J2EE environments. This in turn means that many people write taglibs andthat you can often find great reusable resources. Two important starting points are theSun taglib page (see Resources on page 39 for links).

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 isan important technology in building dynamic Web sites. DHTML is a collection ofclient-side technologies. A DHTML page is delivered by the server and runs within theWeb browser, so the browser runs the code within the DHTML page.

A DHTML page is first and foremost an HTML page. The DHTML developer canembed Javascript scripts within this HTML page. These scripts run on the client andimprove the user experience. An example is the use of Javascript to do client-sidevalidations to eliminate unnecessary network traffic.

Most of the scripts that run within the browser need to access the elements on thepage, i.e. the HTML elements. The Document Object Model (DOM) defines a set ofobjects that are directly related to the HTML elements on the page. The DOM allowsJavascript code to refer to each HTML element on the page as an object with attributesand methods. As an example, Javascript code can access a text field in an HTML formas an object, retrieve its current value, and even change the value. The Javascriptcode can even access an HTML table as an object and add rows by manipulating thetable object -- all completely within the browser.

Cascading Style Sheets (CSS) are used to associate formatting information with HTMLelements. Instead of hard coding this information as HTML markup (such as bold anditalics), all formatting information is externalized to a CSS file and associated with theHTML elements. This makes it easy to quickly and uniformly change the appearance ofa complete Web site.

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 9 of 40

Page 10: wesdynweb5-a4

Armed with this impressive set of server-side and client-side technologies, you're nowready to turn to the tutorial's example of a dynamic Web site -- the messaging centerapplication.

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 10 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 11: wesdynweb5-a4

Section 3. Building a dynamic Web application

Getting started with WebSphere Studio V5

The use of WebSphere Studio V5 to develop dynamic Web sites is illustrated bydeveloping a simple Web application. The messaging center application allows users tosend messages to one another. Every user may log into the Web site and view all ofthe messages sent to them. For every message, users see who sent the message, andthe message text. A user may then send a message to any other registered user.

The focus of this tutorial is the use of WebSphere Studio V5 to build such a dynamicWeb application, not the application itself. The messaging center application is not acomplete application and it includes many shortcuts. For example, there is a limited setof possible users (instead of maintaining the users in a database), login does notrequire a password, no error handling is performed, and messages cannot be edited orgrouped.

Elements within the messaging center application

Before delving into the code, it's useful to take a high-level view of the componentsyou'll build and how they interact with each other. The following scheme shows anexample flow:

A user starts by accessing a login of the formhttp://localhost/MessagingCenter/login.jsp. The JSP engine processesthe JSP files and generates an HTML form that is returned and displayed by thebrowser. The user enters a username and clicks the submit button. This makes a call

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 11 of 40

Page 12: wesdynweb5-a4

to the MessageCenterLoginServlet running on the application server. If there is anerror, the servlet forwards handling to the login JSP. The login JSP creates an errormessage and presents the login form for the user to try again. If the username iscorrect, the servlet prepares the object with the message data and forwards handling tothe message center JSP. The JSP generates dynamic content, which is based on themessages, as an HTML page that is returned to the browser. Using an HTML form, theuser can send a message to another user by clicking the submit button, which makes acall to the AddMessageServlet.

Creating the messaging center project

If you're following along with a running copy of WebSphere Studio V5, select File=>New =>Project... to create a new project. A project contains files and folders, andit's how you organize resources within the WebSphere Studio V5 workbench.WebSphere Studio V5 supports many types of projects, as shown in the left pane ofthe wizard below.

Select Web in the left pane and Web Project in the right pane, and then click Next.WebSphere Studio V5 will create a new project for a Web application and generateresources required for dynamic Web applications such as servlets, JSP files, HTMLpages, etc.

Enter a project name -- MessagingCenter in this example. Before letting WebSphereStudio V5 create the project lets add a few standard tag libraries.

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 12 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 13: wesdynweb5-a4

Selecting standard tag libraries

Using the selection list at the bottom of the following wizard page adds some basic taglibraries that you can then use when building your JSPs:

Add taglibs for accessing JSP objects, utility tags, and the JSP standard tag library,and click Finish. WebSphere Studio V5 goes to work and creates the Web project andthe various resources needed for a Web application.

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 13 of 40

Page 14: wesdynweb5-a4

The WebSphere Studio V5 workbench now becomes the Web Perspective. Aperspective defines the initial set and layout of panes in the workbench. This conceptintroduces a role-based customization of the views and editors; it is a user-centricmetaphor bringing together all the tools useful for a certain role. Views provide differentways to look at a certain resource, and editors are used to create and modify code.WebSphere Studio V5 includes a variety of different editors suitable for specific filetypes such as HTML files, JSP files, and Java source files.

Incidentally, if you have already been running a server session, WebSphere Studio willautomatically inform you that the server configuration needs to be updated to reflect thenew Web application, saving you the bother of remembering to "deploy" the applicationyourself:

Now that you've created the project, you're ready to start creating some of theresources.

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 14 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 15: wesdynweb5-a4

Section 4. Building the back end: Java and servlets

Building User.java and Message.java

First you need to build the Java class that will be used to represent the user. To createa Java class, right click on the Java source folder within the Navigator pane on theworkbench and select New =>Other... :

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 15 of 40

Page 16: wesdynweb5-a4

This brings up a wizard in which you select Java in the left pane and Class in the rightpane. 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 (includingthe superclass java.lang.Object ) remain as defaults. At this point, you also needto create a Java class that represents the message object. The code for both classes isshown in User and Message class code on page 16 .

User and Message class code

Below is the code for the User.java and Message.java classes. After both classesare created, the navigator pane will appear as shown in the figure following the code.

package com.ibm.tutorials.wssd;

import java.util.Vector;import java.lang.String;

public class User {private String name;private Vector messages;

// Simple implementation of a set of users -// only for illustration purposes. Normally users// would have to be maintained and managed in a databaseprivate static User[] hardCodedUsers = {

new User("Joe"),new User("Jane"),new User("Tony"),new User("Tina") };

public static User[] getHardCodedUsers() {return User.hardCodedUsers;

}

public User(String name) {this.name = name;messages = new Vector();

}

public String getName() {return this.name;

}

public Vector getMessages() {return messages;

}

public void addMessage(Message message) {messages.addElement(message);

}

// Return a User object based on user name or a null if a user// by that name does not exist

public static User getUser(String username) {User[] allUsers = User.getHardCodedUsers();for (int i = 0 ; i < allUsers.length ; i++)

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 16 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 17: wesdynweb5-a4

if (allUsers[i].getName().compareTo(username) == 0)return hardCodedUsers[i];

return null;}

}

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;

}}

Doing a build

You can rebuild the project at any point while you're editing resources. Rebuilding theproject means that WebSphere Studio V5 will try to compile all Java code, do syntaxchecking on all resources, and check references between the different elements of theWeb application. If, for example, we misspell the import statement for the classString (as shown below, where we have imported java.util.String instead ofjava.lang.String ), WebSphere Studio V5 will signal the error as well as the errormessage and the location of the error.

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 17 of 40

Page 18: wesdynweb5-a4

Once you've fixed all errors, select Project=>Rebuild All and save your currentworkbench.

You're now all set with the back-end entities and you're ready to build the servlets thatwill implement the "business transactions."

Creating the MessageCenterLoginServlet

The MessageCenterLoginServlet is responsible for looking up the user based onthe username, and for preparing the collection of messages to be displayed for thatuser. It does not generate the dynamic content (i.e., the HTML); a JSP will do that.

To create the servlet, right click on one of the folders in the Navigator pane (e.g., theJava Source folder or the com.ibm.tutorials.wssd folder) and select New =>Servlet :

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 18 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 19: wesdynweb5-a4

The New Servlet dialog

In the New Servlet dialog, set the servlet name and the package name. The superclassremains javax.servlet.http.HttpServlet and click Next. By default, both thedoGet and doPost methods are checked for code creation in the last panel of thewizard, so if this is the behavior you want, click Finish in the screen on which youspecified the servlet name.

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 19 of 40

Page 20: wesdynweb5-a4

When the wizard completes its work, you'll have a skeleton servlet class with thefollowing code:

package com.ibm.tutorials.wssd;

import java.io.IOException;import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

/*** @version 1.0* @author*/public class MessageCenterLoginServlet extends HttpServlet {

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 20 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 21: wesdynweb5-a4

/*** @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 {

}

}

Implementing the MessageCenterLoginServlet

Now you need to implement the behavior of the servlet. The servlet needs to processboth GET HTTP requests and POST HTTP requests in the same way. The simplestthing is to change the doGet method so that it calls the doPost method. This ensuresthat the behavior is identical regardless of what action was used:

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

this.doPost(req, resp);}

Now it's time to implement the doPost method. First, you need to get the usernamefrom the request. If it is null, set an error message and dispatch the handling to thelogin JSP (all HTML will be generated by JSP files). The login JSP will then generatethe HTML based on this error message:

String username = request.getParameter("username");

if (username == null) {// Can't perform a login with no user name.// Set an error message and redirect to login page.request.setAttribute("errorMessage", "User name not specified");

// Dispatch to login.jsp using the RequestDispacther// Use a relative URL for simplicityRequestDispatcher disp = getServletContext().getRequestDispatcher("/login.jsp");disp.forward(request, response);

}

Using auto-completion to finish the servlet

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 21 of 40

Page 22: wesdynweb5-a4

One of the more useful features of WebSphere Studio V5 is auto-completion. If youforget which methods are applicable within a certain context, you can place the cursorafter the period following a variable name and type CTRL + space to bring up acontext-sensitive list of possible methods based on the object in the context. As anexample, if you forget which method of the request object you should use wheninserting the error message, you can bring up the coding assistant as follows:

With the username in hand, you can proceed to look up the User object using thefacilities coded in the User class. If a User object is not found, you can use anothererror message. If a User object is found, place it in the session object and forwardhandling to the JSP file responsible for displaying the messages:

// Otherwise proceed to looking for the User objectUser 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 JSPHttpSession 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 areready for the servlet handling the "business transaction."

The AddMessageServlet

AddMessageServlet is responsible for adding a new message to one of the users, ineffect sending a text message from one user to another. This functionality will beinvoked from an HTML form within the message center.

Building the servlet follows the same process as that of building theMessageCenterLoginServlet. The method implementing the sending of themessage has two parameters: the username of the recipient of the message, and the

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 22 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 23: wesdynweb5-a4

text message to be sent. The originator of the message is retrieved from the sessionobject:

package com.ibm.tutorials.wssd;

import java.io.IOException;import javax.servlet.ServletException;

import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import javax.servlet.RequestDispatcher;import 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 moreHttpSession 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 messageUser messageReceiver = User.getUser(recipient);Message message = new Message(user.getName(), messageText);messageReceiver.addMessage(message);

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 23 of 40

Page 24: wesdynweb5-a4

}}

The back-end code is now ready. It is time to move on to building the presentationlayer.

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 24 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 25: wesdynweb5-a4

Section 5. Building the presentation layer: JSP

login.jsp and messageCenter.jsp

The presentation layer consists of a set of JSP files. JSP files are the perfect elementsfor implementing the messaging center screen generators because while the screensneed to be HTML pages, they are dynamically created based on the back-end entities.As a result of submissions from the HTML forms, methods within the servlets describedin Implementing the MessageCenterLoginServlet on page 21 and TheAddMessageServlet on page 22 panels are invoked.

The JSP files created in this section are as follows:

• login.jsp is responsible for generating the HTML form for capturing the usernameand invoking the MessageCenterLoginServlet

• messageCenter.jsp is responsible for displaying the messages sent to the userwho is currently logged in as an HTML table. Also generates a form allowing the userto send a message.

Building login.jsp

WebSphere Studio V5 has an editor for building JSP files that mimics the feel of HTMLbuilders. 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:

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 25 of 40

Page 26: wesdynweb5-a4

The New JSP File wizard can help you specify many of the JSP's attributes. While youcan click the Finish button on the first step of the wizard, you can also continue withthe other four screens in the wizard. Using the wizards, you can specify explicit init anddestroy method stubs, initialize parameters for the servlet that is automaticallygenerated from the JSP, attach style sheets, define the DTD used in the JSP(WebSphere Studio V5 supports XHTML), and specify the tag libraries to be used fromwithin the JSP -- the topic of the next panel. To proceed, click the Next button.

Importing tag libraries

The New JSP File wizard allows you to specify which tag libraries will be used fromwithin the JSP. Click the Add Tag Library... button. This opens up the next screen onwhich you can select the tag libraries you will use:

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 26 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 27: wesdynweb5-a4

WebSphere Studio V5 shows you a catalog of taglibs, including tag libraries from theApache Jakarta project, the JSTL core library and much more. You can also importadditional 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 usedwithin the JSP, but the default for the core tag library is the letter c. On the screen fromwhich you added the tag library, click Finish.

Now you're ready to start designing the JSP file. Use the central pane in the workbenchto design your page. You can drag and drop elements from the toolbar. You can alsoinsert elements from the Insert menu bar item.

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 27 of 40

Page 28: wesdynweb5-a4

Including a 'use bean' element

In order to build the login JSP page, the first thing you need to include is a use beanelement. The bean in the login.jsp page represents the error message that isdisplayed if, for example, you enter a user that does not exist. Insert the use beanelement using Insert JSP Bean tool by selecting it from the JSP menu item:

Set the properties of the bean using the property editor:

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 28 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 29: wesdynweb5-a4

The identifier of the bean throughout the page is errorMessage and the bean shouldbe retrieved from the request object (remember from theMessageCenterLoginServlet that the error message is placed usingrequest.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 messageusing a printing element from a taglib. Select JSP =>Insert Custom. Then pick out inthe right pane, click Insert and then Close and adjust the value to print out the errormessage variable. Note that you could also have chosen to use a c:out customelement with a value of ${param.errorMessage}, in which case the use beanelement would not have been necessary.

Adding static elements to the page

Finally, add the static elements to the page: add a horizontal rule and a form; add a textfield for entering the username (the field name should be username); and add asubmit button to the form. The resulting page in the designer looks as follows:

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 29 of 40

Page 30: wesdynweb5-a4

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" %><%@ pagelanguage="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, part 1

The messageCenter JSP is very similar to the login JSP. Start a new JSP file by rightclicking on the Web Content folder in the Navigator pane and selecting New =>JSPFile. Enter messageCenter.jsp as the JSP name, click Next, add the JSTL tagliband click Finish. Then move over to the designer and drag the following elements onto

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 30 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 31: wesdynweb5-a4

the canvas:

1. A use bean element for getting the User object from the session

2. Static text (simply type in the text you want to display, in our case the string"Welcome")

3. Property display element for displaying the username

4. Static text ("Your messages are as follows")

5. HTML table

Within the table you need to place a Java loop. Each iteration of the loop creates a newTR element with the message sender and text in TDs. The loop is created using theJSTL core tag library, which supports iteration. Select JSP =>Insert Custom..., whichopens the Insert Custom Tag wizard. The wizard displays all the taglibs in your JSPand the available custom tags. Select forEach for an iteration loop and click Insert.Iteration for this element should be on ${user.messages}.

6. HR element

7. A form for sending a new message

8. A text field for the recipient of the message (named recipient)

9. A text area for the message text (named messageText)

10. A submit button for the form

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 31 of 40

Page 32: wesdynweb5-a4

Building messageCenter.jsp, part 2

When you're done with the designer, the page should look as follows:

The JSP code is generated by WebSphere Studio V5:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><HTML><HEAD><%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %><%@ pagelanguage="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>messageCenter.jsp</TITLE></HEAD><BODY><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>

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 32 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 33: wesdynweb5-a4

</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 messagecenter. Before doing so rebuild the project, as shown in Doing a build on page 17 .

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 33 of 40

Page 34: wesdynweb5-a4

Section 6. Testing the message center

Starting the server

WebSphere Studio V5 comes with an embedded instance of the WebSphereApplication Server V5. This is called the WebSphere test environment withinWebSphere Studio V5. It means that you can publish your Web application and test itbefore deploying to a production WebSphere Application Server instance.

To test the application, right click on the login.jsp page and click Run on Server;leave the default selected WebSphere V5.0 test environment. The application will bepublished to the server and the test environment will be initialized. You will see manyprintouts on the console; the last two lines should be of the form:

[1/19/03 12:11:21:428 EST] 517915dc WsServerA WSVR0001I: Server server1 open for e-business

[1/19/03 12:11:27:897 EST] 62d255cc WebGroupI SRVE0180I: [MessagingCenter] [/MessagingCenter] [Servlet.LOG]: /login.jsp: init

The phrase "Server ... open for e-business" means that the WebSphere ApplicationServer environment has been successfully started.

An example message

The top right pane is a browser view that displays the login HTML (the HTML pagegenerated 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 messagesare 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 Joeas follows:

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 34 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 35: wesdynweb5-a4

In Joe's message center enter the text for a message to send to Jane and click SubmitQuery:

Now go back to the login page and login as Jane; Jane's message center should lookas follows:

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 35 of 40

Page 36: wesdynweb5-a4

Debugging the application, part 1

One of the really great things about WebSphere Studio V5 is that the WebSphere testenvironment is very tightly integrated. This means that you don't have to develop yourapplication, 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 integrateddevelopment environment using a single set of tools.

For example, suppose that an exception occurs when you run the application. You canadd a breakpoint by right clicking on the left border of the code and setting a breakpointas shown below:

You can also simply double click on the right of the pane. This sets a breakpoint in thecode, displayed as a green circle:

Debugging the application, part 2

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 36 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 37: wesdynweb5-a4

When running the application, the server will stop at the breakpoint within the ServerPerspective. Note that you have to run the server in debug mode (i.e., instead ofselecting 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 debug themethod using the debug view:

The Inspector

The Inspector is another useful tool. Suppose that once you have stopped at thebreakpoint, you want to know what string value is stored in the username variable.Double click on the variable to mark the variable, and then right click and pick theInspect entry. The top right pane now allows you to view the value of the markedvariable as follows (in our case the value is "Jane"):

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 37 of 40

Page 38: wesdynweb5-a4

Finally, remember that WebSphere Studio V5 is a very well integrated environment. Ifyou change code even within a running application, you can see the changes takeeffect immediately -- all within one environment.

Packaging

Now that you have tested the message center and feel comfortable with the Webapplication, you're ready to deploy it on a WebSphere Application Server. You need topackage your Web application in a Web Archive (WAR) file, and later import it into anexisting enterprise application using the WebSphere Server Application Assembly tool.To create a WAR file, right click on the Message Center folder and select Export toopen the export wizard. Then, select WAR File and click Next. Enter the name of thefile you want to use and click Finish. In addition, WebSphere Studio also creates anEAR that can be exported and deployed on a WebSphere Application Server withoutthe need for additional packaging tools.

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 38 of 40 Building dynamic Web sites with WebSphere Studio V5

Page 39: wesdynweb5-a4

Section 7. Summary

Summary

In this tutorial you learned how to use WebSphere Studio V5 to develop an end-to-endWeb application. Using both servlets and JSPs, the tutorial demonstrated the use ofWebSphere Studio V5 to develop a basic messaging center. Starting with the back-endJava code for managing users and messages, you then built a set of servlets and JSPfiles implementing messaging functionality and generating a presentation layer in theform of HTML pages. These HTML pages were dynamically generated based on thedata maintained by the Java objects. Once development was completed, you used theWebSphere Studio V5 server tools to test and debug your dynamic Web site. Finally,you learned how to package your Web application for deployment in a WebSphereApplication Server.

Resources

• Register to download WebSphere Studio V5.

• Download a trial edition of WebSphere Application Server for Developers Version 5.

• A tutorial on building Java HTTP servlets is available on developerWorks.

• An Intro to JavaServer Pages technology article is available on developerWorks.

• The Java Servlet technology home page includes the latest specification as well as areference servlet server implementation.

• The JavaServer Pages home page includes the latest specifications as well aspointers to custom tag libraries and other advanced JSP technologies.

• The DHTML school Web page includes resources, examples, and referencematerials.

• Find information about WebSphere Studio Family of Development tools on the IBMWebSphere Web site.

• 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 athttp://java.sun.com/products/jsp/taglibraries.html.

Feedback

Colophon

Presented by WebSphere Developer Domain www7b.software.ibm.com/wsdd/

Building dynamic Web sites with WebSphere Studio V5 Page 39 of 40

Page 40: wesdynweb5-a4

This tutorial was written entirely in XML, using the developerWorks Toot-O-Matic tutorialgenerator. The open source Toot-O-Matic tool is an XSLT stylesheet and several XSLTextension functions that convert an XML file into a number of HTML pages, a zip file, JPEGheading graphics, and two PDF files. Our ability to generate multiple text and binary formatsfrom a single source file illustrates the power and flexibility of XML. (It also saves ourproduction team a great deal of time and effort.)

You can get the source code for the Toot-O-Matic atwww6.software.ibm.com/dl/devworks/dw-tootomatic-p. The tutorial Building tutorials with theToot-O-Matic demonstrates how to use the Toot-O-Matic to create your own tutorials.developerWorks also hosts a forum devoted to the Toot-O-Matic; it's available atwww-105.ibm.com/developerworks/xml_df.nsf/AllViewTemplate?OpenForm&RestrictToCategory=11.We'd love to know what you think about the tool.

www7b.software.ibm.com/wsdd/ Presented by WebSphere Developer Domain

Page 40 of 40 Building dynamic Web sites with WebSphere Studio V5