Servlet Roles in Web Applications

 < Free Open Study > 



We build web applications that consist of a number of servlets (and additional resources) that together function as an application.

Later in this section we will look at some example scenarios of how web applications use servlets in business today, and through the book we will see code examples of servlet use. In this section we will take a broad look at some of the roles that servlets can perform for us in our web applications.

Client requests may occur at irregular and unpredictable intervals, but the servlet will respond to the requests on demand. The servlet container provides the service of listening for requests and wrapping the client request and responses up in special Request and Response objects, but once it receives a request for the servlet, it invokes the servlet and passes it the Request and Response objects. Then the servlet processes the request and passes the client back a response.

However a servlet on its own is often of limited use, and a collection of related servlets form components of the web application. Alternatively we may have a single servlet that is the front door to the application, with this servlet delegating the request (based on the type of the request or other relevant criteria) to an appropriate handler that processes the request. In any case a good, object-oriented web application design is important for developing maintainable and extendable web applications.

Consider the following simple scenario. We want to build a simple, web-based reservations system for a hotel. Core functions of this system will be the ability to search the hotel bookings for availability and to pay for, and reserve rooms in advance. This is an ideal candidate for a servlet-based web application, as we would not consider exposing the reservations database directly on the web.

The reservations web application will consist of a number of servlets that process client requests through the database. Keeping it simple, we may use just three servlets in the application at first, together with a static HTML site (for information).

Our first servlet would be a search servlet that would be responsible for responding to client form-based searches. Information on room availability and rates for given search criteria, such as date and room type, are returned from the search. This servlet is an information servlet that searches for data, but does not change the data on the database. The servlet processes the request as follows:

  1. It extracts the relevant request parameters and uses them to build a database query

  2. Then it connects to the database and executes the query, receiving a result set from the database

  3. Finally it presents the results returned in a manner agreeable to the client (often a well-formatted HTML table)

The second servlet would be a reservation servlet. The purpose of this is to allow the client to reserve an available room. This will update the database in the process of processing the request and reserving the room. The process would be as follows:

  1. The servlet receives the request, and first checks that the information required is supplied (name, dates, and so on)

  2. Then it would verify on the database that the room(s) requested are still available, and if so reserve them

  3. Finally it would confirm to the client the provisional reservation of the room, pending payment

The final servlet in our reservations web application would be a payment servlet. This processes the client's payment details and updates the reservations database with the result. The steps involved here would be:

  1. It receives the request from the client to pay for the room

  2. It checks that the payment is for a valid reservation

  3. If the reservation is still holding, it would process the payment by contacting the credit card company's system to process the payment details

  4. Assuming that the payment was successful, this servlet would update the database and confirm the reservation

  5. Finally it would inform the client that the payment was accepted and that the booking has been confirmed

The above scenario illustrates that a group of servlets can form the basis for a complete web application that fulfils the requirements of an enterprise application.

You should note that Java servlet-based web applications are naturally inclined to be at least three tier applications. Since servlets operate on the request-response model, by definition there is a client and so we have two tiers at a minimum; servlet-based applications will usually need to exchange data with an additional tier too. This additional tier may be the EJB tier, or the database/enterprise information system tier.

Typical Servlet-based Applications

To round off the chapter, we are going to discuss some typical application scenarios where servlets play an integral role within the application.

The range of potential business applications that can use servlets is immense. Almost any application could be written (or rewritten) to include servlets. Their strength, compared with alternate technologies, is their communication over the Internet (or intranet) using HTTP (or any other suitable protocol such as FTP or SMTP). Given security and firewall considerations, for many applications, HTTP is almost the only protocol available. Using HTTP also allows us to communicate with many other resources, such as web and database servers and other enterprise information systems and applications.

Servlets are ideal for client web browser (HTML over HTTP) based applications, and any other text-based communication is well supported. XML and WML communications are such examples. Emerging web services technologies will be well-placed to leverage servlets in the web tier of their applications.

However, traditional thinking about client-server programming and Internet or web development needs to broaden its perspective to look at the range of uses for servlet and J2EE technologies. Servlets are not just for HTML web applications. They are also useful for our deployed Java applications, perhaps deployed using Web Start type of technologies using JNLP (Java Network Launch Protocol).

Servlets can also be used in business applications to upload more data than just the request parameters. We can exchange the HTTP input parameters for a servlet input stream to read in serialized Java objects, files, text, or other relevant data from the client. Servlets are ideal for HTTP tunneling, which is client-server communication over HTTP due to firewall restrictions (often firewall protection restricts almost all communication except over HTTP). In tunneling we wrap an alternate protocol request in an HTTP request to bypass firewall limitations. While this may sound a little dubious, this does have many legitimate uses, such as streaming data and wrapping RMI requests.

Servlets are also ideal for connecting J2ME client devices and applications, and WAP/WML cell phones and such devices. Developments over the last few years in cell phone technology have seen the first text-based WML, and now Java applications are moving onto these devices. In Japan DoCoMo broke new ground by making Java widely available on the cell phone, and other markets, such as the US, are doing the same. Placing servlets on the web tier of mobile applications makes a strong match, as mobile devices require light clients, with processing pushed onto the server. Research in this area is strong with major investments, and forecasts indicate huge growth in cell and wireless devices over the next few years.

About two thirds of distributed enterprise applications being developed in Java within the broader spectrum of J2EE use only the web container with servlets on the middle tiers to process client requests, so servlets have an important role to play in distributed applications.

An E-Commerce Scenario

Consider a company that wants to get involved in an online supermarket. This could be a subsidiary of a distributor or wholesaler company. The company could have two enterprise critical web/J2EE applications:

  • On the e-store front we see the business-to-consumer model in action to interact with customers

  • In the backend we see a business-to-business model used to manage orders to suppliers and coordinate grocery deliveries to customers

On the business-to-consumer side, the customer uses a web browser to view the online store and make their order. The order process servlet application receives the client order and passes it onto the order manager J2EE application. The order manager application receives client orders from the order process servlet, or its own order servlet, and adds the details of the order to the database. It also checks stock levels in the database and sends XML-based orders to suppliers for any items that will need restocking. It processes the delivery schedule as well for the manager client application. To do all this the order manager application has two servlets, one to process orders and one to deal with the manager application. This scheme is illustrated in the figure below:

click to expand

Consider the order process:

  1. The client starts the process by placing the order

  2. The web application's OrderProcessServlet receives and checks the client credit, and then forwards it to the order manager application

  3. The receiving servlet then stores the order in the database and orders any supplies required

  4. The order is then acknowledged back to the client

  5. If the supplier acknowledges the order, the order manager application sets and confirms the order delivery date to the client by e-mail

The servlets' role in this application is critical to the e-store's success. They are responsible for managing orders, getting the database stock levels checked (task delegated to an EJB) and, if necessary, ordering a restock of low supplies online from a supplier. The processing involved in this scenario is not excessively complex, but it is responsible for managing the stock levels, which is a critical task in itself. The rules for what levels are considered low and requiring a reorder would be encapsulated within the EJB, but the OrderManagerServlet is then responsible for sending the restock request if necessary.

The business-to-consumer aspect is dependent upon the OrderProcessServlet for receiving order requests and processing them. The business-to-business side of the company that predated the new e-store manages stock levels and orders, which are key components of this business' model.

The role of the servlet in this scenario is to act as the web interface to the consumer. This is very much a client-driven process and the servlets process their requests, manage (or delegate) the processing logic, and return to the client a web-based HTML response.

A Consumer-to-Business-to-Consumer Scenario

We can look at an e-business site that is set up to act as an intermediary between vendors and purchasers. It provides a place for members of the public to sell goods, either at a fixed price, or by auction to other members of the public. The site provides a sales notice board and can manage auctions by processing bids. It also provides a personalized service by displaying tailored pages, based on the customer's registration preferences.

It uses a HTML interface for the client side, and servlets on the server side to process requests, with a database to store user information, sales and auction data. If we are involved in designing this, we need to consider the user base (total volume) and peak usage. We also need to design the application with a margin of error for these figures, which in reality means that we have to look at the upside to the figures if the website is successful. We need to be most concerned about peak usage, as this is where any bottlenecks in code or scalability problems will be shown.

For the purposes of this example we will assume that this sales and auction e-business is going to plug into a online portal aimed at a specific local town, which will allow us to tailor the site for local preferences. The portal can provide us with some data in regards to the scale of usage and interest.

Given the scale and reliability required (we can't have the site falling over in the middle of all of our auctions), we need to consider running our web application on a clustered server set-up. This should provide us with both scalability and reliability, by allowing us some fail-over protection.

From a security point of view, we will register participants with personal data and personal preferences, so passwords sent to a servlet over HTTPS may be considered sufficient for this portion. For the payments process we may use a more secure format of security for processing transactions, or alternatively we could place this section on a separate server (clustered for reliability), which may use higher security and encryption (possibly an applet interface communicating with a servlet over HTTPS, so that we can increase encryption). This will process credit card payments for auctions and other sales.

We may also have a separate database for payments processing, again more for security's sake since we can increase our protection around this database. Again, for the payments processing web application the role of servlets will be to receive and process the customer payment details. The main application will have details of sales made and dates processed, but does not need credit card and other payments details. This type of design will help improve security and improve consumer confidence in our systems.

Here's a diagram showing this scheme:

click to expand

Remember that while diagrammatically the Payments and Sales Auction web applications are separately located, we may in practice cluster them across the same web containers. This is essentially a security decision.

We'll take a look at the servlets that could be involved in the process. It is important at this stage to understand that these servlets relate to specific processes between the client and our application, and in the final design may be implemented differently.

Firstly we have two applications - the payments processing application and the main application. The payments processing application will have one PaymentServlet to process payment details. The main application has a number of roles to fulfill:

  • Registration to process user registrations

  • Post Item to accept items for sale or auction

  • Search to allow users to search the sales and auctions

  • List to allow users to list and navigate categorized sales and auctions (this will have some similarities to the Search role as it will search on category, but may have a different presentation)

  • Bid to process user bids on an action; this will inform the vendor by e-mail of bids if required

  • Purchase to process item sales; this will also inform the vendor (and copy the purchaser) of the sale by e-mail

  • Administration to allow a user to view their history (bids/purchases, sales etc.)

These roles will be allocated to a number of servlets (and a couple of JSP pages):

  • RegistrationServlet

  • PostItemServlet

  • SearchJSP and ListJSP to present the output (in different ways) for the SearchServlet

  • BidJSP and PurchaseJSP to present the result of a bid or purchase handled by the OfferServlet

  • AdministrationServlet

Each of these will interact with the database via JDBC. The following diagram details the initial content for our applications, concentrating on the servlet web container layer:

click to expand

We may develop and use EJBs to encapsulate the business logic involved in the processing of the interactions and transaction, but as we are concentrating on the servlet side we have not detailed these on the diagram.

From the user's perspective the site has to be dynamic and constantly updated with information about auctions and sales of interest to the user. Within this web application, the servlets provide the flexibility and dynamism to allow the site to adapt to events (auctions and sales) created by the users.

The primary role of the servlets in the application is to interface with clients and process their requests. However, we also have a number of specific tasks or roles that the servlets perform, although they perform little processing of data. They act as a bridge between the client and the database. The servlets present the database data in a meaningful way, while updating the database as well when required.

A Modern Interface to a Legacy System Scenario

Lets take a look at a system that will provide an user interface application to a legacy system. Many firms still have a strong reliance on legacy systems for their core business processes. Therefore programmers are often asked to bridge the gap and create systems that can interface with them

We can use servlets to do this, together with EJBs and the Connector API, as we described earlier in the chapter. The EJBs manage the business logic and access to the legacy system. The connector technology standardizes legacy and enterprise information system access through a standard API, in a similar way to how JDBC provides a standardized access API for databases. The servlet's role in this scenario is to act as a bridge between the client and the EJBs, transforming the requests from the client into a format that the EJBs can process, and translating the EJB's response into a format suitable for the client.

For example, consider a stock control system that runs on a legacy system. We need to create an application that can manage stock, allowing the user to change stock levels and other associated stock control functions. Additionally, users also want to be able to use a PDA type of device in the stock room to update the system when they connect back into the network. The advantage of using Java at the client end is that we can perform automated software updates, so once a new release is available, users immediately have access to it. We can also build a client for the PDA using J2ME, and we could build a workstation version for the J2SE client. The J2ME version downloads data and then allows the user to disconnect from the system and work on the stock floor updating the system. Once complete, the user can connect the PDA back into the network and update the system.

The clients will connect to the legacy system through a J2EE web application running servlets. The servlets receive requests and call on the EJBs to process the request. The EJBs use the Connector API to access and update data on the legacy application. The diagram below illustrates this:

click to expand

Obviously there would be other issues to sort out, such as locking/protecting the data that the stockroom staff are updating, and the application could incorporate this. Also caching of the data by the servlet for reuse rather than having to retrieve it for each request may be appropriate, depending on the response times.

In the Order Manager web application we will have one servlet to process all requests. We will use a RequestHandlerFactory class that will be responsible for mapping each request to the appropriate RequestHandler that will be able to process the request. The RequestHandler will interpret the request and wrap it appropriately for the EJB to process. The EJB then connects to the legacy Stock Management system and performs updates and access information as required. Using this system we can create accessible user interfaces to the legacy system that we can use on the stockroom computers and on PDA devices on the floor.

For the clients we can use XML over HTTP to enhance data, or we could serialize the data in Java objects. If we were going to be exchanging large files of information continuously we might consider using a different protocol like FTP, but data compression may be easier (using java.util.zip.ZipOutputStream). There would be other alternatives to XML or serialization (perhaps straight text or CSV), but these would probably be the frontrunners. If it was possible that other systems may want to connect to our web application it may be a better choice to use or include XML to ensure maximum flexibility.

XML also allows for XML-RPC or remote procedure calls over XML. We could incorporate a strong element of flexibility for client requests, by implementing the ability to allow clients to query the legacy EIS using XML-RPC calls to the servlet. This is moving towards implementing a web services scenario which we will look at next.

Thus we see that the servlet's role is limited in this scenario. It is really just the interlink between the client and the EJB-to-legacy system. In this case, most of the processing will probably occur on the legacy system. In fact there could already be a more limited legacy system application that this application is updating or replacing.

A Web Services Scenario

Distributed web applications have been around for a long time, but they have recently evolved into web services that expose functions (or methods) for remote execution across the web. This means that, using web technologies and infrastructure (for example HTTP), we can set up an application to receive (or transmit) function requests, complete with parameters, and receive a response as a result. Chapter 14 looks a web services in more detail.

One way to implement a web service is to expose a servlet to XML-RPCs (remote procedure calls) that request the servlet to provide information in the response, corresponding to the procedure called and the parameters passed into the call.

Consider the scenario where we have a distributed Hotel booking operation that stores data in geographic servers roughly corresponding to continents. It does this for optimal performance, since most requests to this data comes from within the continent that it is located. However for long distance requests, from a client of another continental server, our local server exposes the data by setting up a web application using servlets to process XML-RPC requests.

The web application that we develop looks like the following diagram:

click to expand

At the backend EIS tier we have a database, and also a Legacy Booking Application that is still in use for certain hotels.

On the web tier we place our HotelBookApp, which is a servlet-based web application. This application has servlets that are designed to receive XML-RPC requests. These XML-RPC requests allow other servers and/or clients to query the North American data using defined procedures.

The client tier of the application consists of North American travel agent users of the Java TravelAgentApplication, and our other servers that receive requests for information or bookings for North America.

Essentially this application set-up is mirrored (but in reverse) on the other continental servers with the other servers providing access to their data through XML based web services.

The servlet's role in this application is to receive and interpret the XML-RPC requests. They then have to map the request to the database or legacy booking application that performs the request, and once the servlet receives the response, it returns this as a response to the XML-RPC request. The servlet provides the web services to its own client application, and also to other servers. In turn, this application's servlet may make a similar XML-RPC request to the other continental web applications if it receives a request for information relevant to that region.

From the programmers point of view, the servlets are standard servlets, probably running over HTTP (but not necessarily), perhaps using XML parsers a little more than many other web applications, but this is all part of the web service aspect.



 < Free Open Study > 



Professional Java Servlets 2.3
Professional Java Servlets 2.3
ISBN: 186100561X
EAN: 2147483647
Year: 2006
Pages: 130

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net