Introduction to Server-Side Technologies

Similar documents
Servlet Fudamentals. Celsina Bignoli

Servlets by Example. Joe Howse 7 June 2011

Session 8. Introduction to Servlets. Semester Project

JAVA SERVLET. Server-side Programming INTRODUCTION

Java Servlets. Preparing your System

Servlets1. What are Servlets? Where are they? Their job. Servlet container. Only Http?

Web based Applications, Tomcat and Servlets - Lab 3 -

ServletConfig Interface

Session 9. Introduction to Servlets. Lecture Objectives

Advanced Internet Technology Lab # 4 Servlets

Servlet Basics. Agenda

Java Enterprise Edition. Java EE Oct Dec 2016 EFREI/M1 Jacques André Augustin Page 1

The Basic Web Server CGI. CGI: Illustration. Web based Applications, Tomcat and Servlets - Lab 3 - CMPUT 391 Database Management Systems 4

Introduction to Servlets. After which you will doget it

This tutorial will teach you how to use Java Servlets to develop your web based applications in simple and easy steps.

Servlets. An extension of a web server runs inside a servlet container

&' () - #-& -#-!& 2 - % (3" 3 !!! + #%!%,)& ! "# * +,

Using Java servlets to generate dynamic WAP content

Kamnoetvidya Science Academy. Object Oriented Programming using Java. Ferdin Joe John Joseph. Java Session

SSC - Web applications and development Introduction and Java Servlet (I)

Enterprise Java Unit 1- Chapter 4 Prof. Sujata Rizal Servlet API and Lifecycle

Introduction. Literature: Steelman & Murach, Murach s Java Servlets and JSP. Mike Murach & Associates Inc, 2003

Introduction. This course Software Architecture with Java will discuss the following topics:

Servlets and JSP (Java Server Pages)

HttpServlet ( Class ) -- we will extend this class to handle GET / PUT HTTP requests

INTRODUCTION TO SERVLETS AND WEB CONTAINERS. Actions in Accord with All the Laws of Nature

2. Follow the installation directions and install the server on ccc. 3. We will call the root of your installation as $TOMCAT_DIR

sessionx Desarrollo de Aplicaciones en Red A few more words about CGI CGI Servlet & JSP José Rafael Rojano Cáceres

Introduction to Java Servlets. SWE 432 Design and Implementation of Software for the Web

SERVLETS INTERVIEW QUESTIONS

UNIT-V. Web Servers: Tomcat Server Installation:

servlets and Java JSP murach s (Chapter 2) TRAINING & REFERENCE Mike Murach & Associates Andrea Steelman Joel Murach

Database Applications Recitation 6. Project 3: CMUQFlix CMUQ s Movies Recommendation System

To follow the Deitel publishing program, sign-up now for the DEITEL BUZZ ON-

In servlet, form parsing is handled automatically. You call request.getparameter to get the value of a form parameter.

AJP. CHAPTER 5: SERVLET -20 marks

Servlet and JSP Review

Servlets Basic Operations

Accessing EJB in Web applications

CIS 455 / 555: Internet and Web Systems

Tutorial: Developing a Simple Hello World Portlet

Handout 31 Web Design & Development

Chapter 10 Servlets and Java Server Pages

Welcome To PhillyJUG. 6:30-7:00 pm - Network, eat, find a seat 7:00-7:15 pm - Brief announcements 7:15-8:30 pm - Tom Janofsky's presentation

Advanced Web Technology

CE212 Web Application Programming Part 3

Servlet. 1.1 Web. 1.2 Servlet. HTML CGI Common Gateway Interface Web CGI CGI. Java Applet JavaScript Web. Java CGI Servlet. Java. Apache Tomcat Jetty

Berner Fachhochschule Haute cole spcialise bernoise Berne University of Applied Sciences 2

Servlets Pearson Education, Inc. All rights reserved.

The Structure and Components of

Customizing ArcIMS Using the Java Connector and Python

CIS 3952 [Part 2] Java Servlets and JSP tutorial

Lecture Notes On J2EE

LAB 1 PREPARED BY : DR. AJUNE WANIS ISMAIL FACULTY OF COMPUTING UNIVERSITI TEKNOLOGI MALAYSIA

Advanced Internet Technology Lab # 5 Handling Client Requests

CSC309: Introduction to Web Programming. Lecture 8

INTERNET PROGRAMMING TEST-3 SCHEME OF EVALUATION 1.A 3 LIFE CYCLE METHODS - 3M 1.B HTML FORM CREATION - 2 M

Module 4: SERVLET and JSP

Structure of a webapplication

SDN Community Contribution

3. The pool should be added now. You can start Weblogic server and see if there s any error message.

CHAPTER 2: A FAST INTRODUCTION TO BASIC SERVLET PROGRAMMING

Université Antonine - Baabda

Chettinad College of Engineering and Technology CHETTINAD COLLEGE OF ENGINEERING AND TECHNOLOGY DEPARTMENT OF COMPUTER SCIENCE AND TECHNOLOGY

Lab session Google Application Engine - GAE. Navid Nikaein

Database Systems Lab. 11. JSP I 충남대학교컴퓨터공학과 데이타베이스시스템연구실

Chapter 17. Web-Application Development

JavaServer Pages (JSP)

Supplement IV.E: Tutorial for Tomcat For Introduction to Java Programming By Y. Daniel Liang

Handling the Client Request: HTTP Request Headers

Enterprise Java Technologies (Part 1 of 3) Component Architecture. Overview of Java EE. Java Servlets

CSC309: Introduction to Web Programming. Lecture 10

WWW Architecture I. Software Architecture VO/KU ( / ) Roman Kern. KTI, TU Graz

CS433 Technology Overview

Web Based Solutions. Gerry Seidman. IAM Consulting

PRODUCT DOCUMENTATION. Installing and Implementing Enterprise Contact Center Chat RELEASE 5.1

COMP9321 Web Application Engineering

Servlet for Json or CSV (or XML) A servlet serving either Json or CSV (or XML) based on GET parameter - This version uses org.json

Introdução a Servlets

COMP9321 Web Application Engineering

First Servlets. Chapter. Topics in This Chapter

Server Side Internet Programming

A Servlet-Based Search Engine. Introduction

HTTP. HTTP HTML Parsing. Java

JSP. Common patterns

Getting started with Winstone. Minimal servlet container

Writing Servlets and JSPs p. 1 Writing a Servlet p. 1 Writing a JSP p. 7 Compiling a Servlet p. 10 Packaging Servlets and JSPs p.

Backend. (Very) Simple server examples

Java4570: Session Tracking using Cookies *

Topics Augmenting Application.cfm with Filters. What a filter can do. What s a filter? What s it got to do with. Isn t it a java thing?

Topics. Advanced Java Programming. Quick HTTP refresher. Quick HTTP refresher. Web server can return:

A.1 JSP A.2 JSP JSP JSP. MyDate.jsp page contenttype="text/html; charset=windows-31j" import="java.util.calendar" %>

Session 8. Reading and Reference. en.wikipedia.org/wiki/list_of_http_headers. en.wikipedia.org/wiki/http_status_codes

Implementation Architecture

Unit 4 - Servlet. Servlet. Advantage of Servlet

Generating the Server Response: HTTP Response Headers

Web Application Architecture (based J2EE 1.4 Tutorial)

CS506 Web Design & Development Final Term Solved MCQs with Reference

Java.. servlets and. murach's TRAINING & REFERENCE 2ND EDITION. Joel Murach Andrea Steelman. IlB MIKE MURACH & ASSOCIATES, INC.

Configuring Tomcat for a Web Application

Transcription:

Introduction to Java Servlets Table of Contents Introduction to Server-Side Technologies Dynamic Generation of Web Pages Basic Technology Behind Dynamic Web Pages Getting Started with Java Servlets Installing Apache Tomcat Compiling and Deploying Java Servlets in Tomcat Template Servlet Structure Hello World Servlet Handling Requests with Servlets HTTP Request Headers Handling HTML forms Bibliography Introduction to Server-Side Technologies Dynamic Generation of Web Pages Web-based information systems support remote access to Web pages. The Web pages served by such systems come in two flavours. Either they can be static Web pages that are stored and served as files on the server file system, or they can be generated dynamically on the server side. The dynamic Web pages may be generated as a response to a search query, database query, or purchase request submitted by a user of the system. Generally, there are few reasons for dynamic generation of Web pages [HallBrown2003]: Web pages are based on user queries, e.g. result pages of search engines, shopping carts in online shops, and so on. The data managed by the system changes often, e.g. wheather forecast sites, news tickers, and similar. Web pages are based on data from a database system, e.g. students data from university databases, online flight reservation, etc. There exist a number of server-side technologies for dynamic generation of Web pages. The basic server-side technology is CGI (Common Gateway Interface). It is actaully a standardized specification [CGI1995] of communication between a Web server and external programs. Thus, an external CGI program runs directly on the server side and generates a dynamic Web page. The Web server invokes the external program by passing parameters to it (e.g. user query). The generated Web page is passed back from the external CGI program to the Web server, which in turn forwards the page to the user. All

the communication between the Web server and external program is carried using the standard input and output streams. The simplicity of the CGI specification and the fact that CGI programs can be written in any programming language lead to a widespread of CGI-based applications. However, CGI programs have a number of serious drwabacks. The major drawback of CGI programs is the performance issue. Since CGI programs are external programs, the operating system starts a new process for each request to a CGI program. This of course bring the performance costs. Further, there is no possibility for a CGI program to keep database connections open over a number of requests. For each request a new database connection must be established, which leads to significant performance costs in database centric applications. Sun's answer to the CGI technology are Java servlets. Java servlets are Java programs running on the side of a Web server and producing dynamic Web pages. Similar to the CGI specification the Java Servlet Specification [JavaServlet2003] standardized how Java programs run and communicate with a Web server to produce dynamic Web pages. The result of the specification is the Java Servlet Application programming interface (API), which is a Java library with classes needed to write Java servlets that produce dynamic Web pages. The current version of the Java servlet Specification and Java Servlet API is 2.3. The version 2.4 has currently the status of a proposed draft. The reference implementation of the Java Servlet Specification is Apache Tomcat [Tomcat1999]. The version 4.1.27 of Tomcat implements the Java Servlet Specification 2.3. Actually, Tomcat is a so-called servlet engine, which is a Java program that provides an execution context for a number of Java servlets, which run within separate Java threads inside the Tomcat process. Tomcat provides all the communicational functions between servletsand Web server, as specified in the Java Servlet Specification. Java servlets have a number od advantages over traditional CGI technologies for generating dynaimc content on the Web. These advantages include [HallBrown2003]: Efficiency. As mentioned before, for each request for a CGI program the operating system starts a new process to handle that request. In the case of Java servlets, there is only one process, that of the servlet engine. Each Java servlet is just a thread running within the context of the servlet engine process. Of course, starting and stopping a thread costs a lot less in terms of performance than starting and stopping of an operating system process. Especially, if the execution time is small. Java servlets are also more efiicient in terms of memory usage. Thus, in the case of multiple synchronous requests for a single servlet the servlet code is loaded only once and multiple threads are started with the same code. Contrary to that for multiple requests for a CGI program, the operating system must load the code as many times as there are requests. Finally, servlets can keep track of consecutive requests, and store some internal data that help improving performance. For instance, servlets can keep database connections open and thus reduce greatly costs of establishing a connection with a database with each new request.

High capability. Servlets can share their data, which makes it possible to implement database connection pools, thus greatly reducing costs of establishing database connections, not only within one servlets but among a number of servlets. Further, servlets can keep information from one request to another, making it possible to easy track user's session, cache results from previous computations, and so on. Finally, servlets can talk directly to the Web server and access its data stored in standard places. Portability. Servlets are Java programs written using a standardized API. Thus, servlets written for one platform may be easily ported to another without no need for changing them. Servlet engines are available for all major platforms and all major Web server products. Java software libraries. Since servlets are Java programs they can use the standard Java API or any other Java library available. Thus, libraries for manipulating connections with database managment systems (JDBC libraries), libraries for manipulating digital images, Java XML libraries, etc. are all accessible in Java servlets. Basic Technology Behind Dynamic Web Pages The Web utilizes a classical client-server architecture. Thus, a Web client sends a request over the Internet to a Web server asking it for a specific Web page. To address a Web page the client specify its Uniforme Resource Locator (URL) to the server. Communication between the client and the server is carried out by means of HyperText Transfer Protocol (HTTP). HTTP is a simple text-based protocol. An HTTP request in its simple case can consist of a single request line containing only GET keyword together with the URL of a Web page. As the answer to this simple request the server will respond by sending the requested page back to the client. In the general case, an HTTP request consists of: Request line, which contains an HTTP method (usually GET or POST) and a URL. GET method just retrieves the data from the server, whereas POST method implies that the client sends data to the server. A number of HTTP headers, which set properties of connection between the client and server. For example, Accept header specifies which MIME types are preferred by the client, Accept-Language header specifies which language is preferred by the client if the server has versions of the requested page in different languages, User-Agant specifies type of the client (browser), and so on. All HTTP headers are optional, except Content-Length header, which is required for POST method to specify how much data is sent from the client to the server. Content, that is data sent by the client to the server in the case of POST method. Mostly, dynamic Web pages are generated in accordance with parameters sent by users to a Web server. For instance, to submit a search query to a search engine users type in their serach terms in an HTML form and press the submit button to send the data. HTTP utilizes two possibities to send such parameters from the client to the server:

With GET method parameters are encoded in the URL included in the request line. Parameters are submitted as key-value pairs connected with equal '=' sign. Multiple paramaters are separated with ampersand '&' sign. Spaces are encoded as plus '+' sign, and special characters are encoded as a hexidecimal value preceeded with percentage '%' sign. The encoded parameters are preceeded with a question mark '?' sign and attached to the original URL. A typical example of encoding user parameters in URL looks as follows. Example 1. Encoding Parameters in URL http://www.google.at/search?q=java+servlets&ie=utf-8&oe=utf- 8&hl=de&btnG=Google+Suche&meta= With the above URL parameters for a search query are sent to the Google search engine. The parameters come in key-value pairs: q=java Servlets, ie=utf-8, oe=utf-8, hl=de, btng=google Suche, and meta parameter has no value. Since the length of a URL is limited to 1024 bytes this method allows only limited number of parameters to be transmitted. With POST method parameters are sent as the content of the request. The length of the content is specified as a special Content-Length HTTP header. POST method allows sending of binary data as content, or even mixed binary and text data as content. This is very often used for uploading binary data, such as digital images, compressed files, etc. to the server. On the client side POST method is usually applied within HTML forms. Here is a typical example of such an HTML form. Example 2. POST Method with HTML Form <form action ="http:coronet.iicm.edu//form" method="post"> First Name: <input type="text" name="name" size="20" maxlength="50"> Second Name: <input type = "text" name = "second_name" size = "20" maxlength = "50"> Matrikel Number: <input type = "text" name = "nr" size = "20" maxlength = "50"> Study Field: <select name="study_field"> <option value="f874">telematics <option value="f860">technical Mathematics <option value="f033523">software Development <option value="f033211">telematics Bachelor <option value="f033221">geomatics </select> <input type="submit" value="register"> </form>

Thus, parameters sent to the server are name, second_name, nr, and study_field. Getting Started with Java Servlets Installing Apache Tomcat The first step in working with Java servlets is installing the software, so-called servlet engine, that implements the Java Servlet Specification and provides the Java Servlet API. The reference implementation of servlet engine is Apache Tomcat [Tomcat1999]. The current version of Apache Tomcat is 4.1.27. Apache Tomcat is an open source software product released under Apache Software Licence [Apache2000]. Installing Apache Tomcat is quite simple. Firstly, the appropriate version for the operating system must be downloaded. All Apache Tomcat versions might be obtained as source files, or as precompiled binary files. Building the system from source files requires some additional software, which can be obtained from the Apache Java Web site [Jakarta2003]. The complete instructions for buliding and installing Apache Tomcat from the source files can be found on Apache Tomcat Web site. On the other hand, installing the binary version of the system can be accomplished in only few steps. For both Linux and Windows operating systems a similar installation procedure might be applied. Here the Linux procedure is explained, to install the system on Windows some small modifications are needed (e.g. *.bat files instead of *.sh files, c:\tomcat instead of /tomcat, etc.). Decompress the downloaded binary archive into a directory in your file system, lets say in "/tomcat" directory. Change to /tomcat/bin directory and make the start and stop scripts (startup.sh and shutdown.sh) executable. Invoke the start and stop scripts to start/stop the system. Example 3. Installing Tomcat on a Linux machine #installation in directory /tomcat cd /tomcat tar xzf <path-to-tomcat-binary-archive>/jakarta-tomcat-4.1.27.tar.gz cd jakarta-tomcat-4.1.27 #make scripts executable chmod +x bin/*.sh #start tomcat (windows: use bin/startap.bat) bin/startup.sh #stop tomcat (windows: use bin/shutdown.bat) bin/shutdown.sh

There is a Windows installer version available for Windows operating system. To install the system with this binary distribution just double click on the downloaded executable archive and follow the instructions on the screen. A nice feature of this distribution for Windows XP/2000/NT operating system is that the system is automatically installed as a Windows service, which may be controlled from the Managment Console available in Control Panel. Once when the system is running it can be accessed with a standard Web browser under http://localhost:8080, or http://<hostname>:8080 Compiling and Deploying Java Servlets in Tomcat Since Java servlets are typical Java programs to compile them you must use a standard Java compiler. The CLASSPATH environment variable must include the Java Servlet API, which comes with Apache Tomcat. The library is stored under the common/lib/servlet.jar in the Tomcat installation directory (e.g. /tomcat/common/lib/servlet.jar). After compiling all necessery Java source files servlets need to be deployed in Tomcat. Apache Tomcat works with so-called Web applications. A Web application is a collection of one or more servlets combined with external Java libraries, static resources such as digital images, static HTML pages, etc. to provide a specific functionality. For instance, online shopping application might be realises as a Tomcat Web application. Each Tomcat Web application has the same predefined structure: All Web applications are stored as directories under the webapps directory (e.g. /tomcat/webapps) directory of the Tomcat installation. Web application name is identical with the name of its directory, e.g. a Web application called "onlineshop" is stored in the directory called online-shop (e.g. /tomcat/webapps/onlineshop) and it is accesible via http://localhost:8080/online-shop, or http://<hostname>:8080/online-shop. Static resources of a Web application (e.g. HTML pages, images, etc.) are stored in the Web application directory. There is a special subdirectory called WEB-INF of the Web application directory, e.g. /tomcat/webapps/online-shop/web-inf. The WEB-INF directory contains two subdirectories: classes (e.g. /tomcat/webapps/online-shop/web-inf/classes) and lib (e.g. /tomcat/webapps/web-inf/online-shop/lib) directory. The first of these two subdirectories contains all Java class files required to run a particular Web application. The lib directory contains external Java libraries (e.g. Java archive - jar files) needed to run the Web application. For example, if the Web application connects to a database managment system, the Java library (JDBC driver) needed to establish the connection is placed in the lib directory. There is a special file called web.xml in the WEB-INF directory. This file includes all configuration directives for a particular Web application, in the form of key-value parameters that are paased to a servlet when it is initialized. For

example, the username and password for a user of the backend database managment system might be defined in the web.xml file. Further, in this file the typical description of all Java servlets from a particular Web application is provided. This description includes the unique servlet name, name of the Java servlet class, and a number od additional servlet attributes, such as URL mapping for the servlet, and so on. Example 4. Template Structure of Tomcat Web Application -tomcat -webapps -online-shop -WEB-INF -web.xml -lib -*.jar (e.g. mysqlconnector.jar) -classes -*.class (e.g. ShopingCartServlet.class) -*.htm (e.g. navigation.html) -*.gif, *.jpg (e.g. shopping_cart.jpg) Example 5. Typical web.xml file <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <servlet> <servlet-name>shopping Cart</servlet-name> <description>keeps track of items that user bought</description> <servlet-class>shoppingcartservlet</servlet-class> <init-param> <param-name>database-username</param-name> <param-value>dhelic</param-value> </init-param> </servlet> <servlet-mapping>

<servlet-name>shopping Cart</servlet-name> <url-pattern>basket</url-pattern> </servlet-mapping> </web-app> Template Servlet Structure The Java Servlet API [JavaServletAPI2003] a number of Java classes which are used for developing of Java servlets. This API consists of two Java packages: javax.servlet and javax.servlet.http. The first package contains Java classes and interfaces which implement a generic servlet behavior, whereas the second javax.servlet.http package provides Java classes and interfaces that handle more specific servlet behaviour in an HTTP based environment. Thus, the most of the time programmers work with the classes from the second package. These two packages provide an object-oriented abstraction of the underlying networking technology. For example, to handle HTTP GET method programmers only need to implement a method in a Java class, to obtain parameters sent by a user they call methods on a high-level Java object representing the request sent by the user, and so on. A Java servlet is a normal Java class which is defined as a subclass of the abstract class HttpServlet from the javax.servlet.http package. The abstract HttpServlet class has a number of public methods, each of them corresponding to an HTTP method, such as GET or POST method. A subclass of the Http Servlet class must implement at least one of these methods to handle the corresponding HTTP method. Here are some of the most important methods from the public interface of the HttpServlet class: doget() method, for handling HTTP GET requests dopost() method, for handling HTTP POST requests dodelete() method, for handling HTTP DELETE requests doput() method, for handling HTTP PUT requests Usually, for generation of dynamic Web pages doget() and/or dopost() methods are implemented. These methods are called by the servlet engine whenever an HTTP request with the corresponding HTTP method is issued to the server. Normally, the servlet engine handles only a single instance of a particular Java servlet. For each new request to this servlet the sevlet engine starts a new thread and invokes the corresponding method of the servlet within the execution context of the new thread. In the most simple case a Java servlet only implements doget() method. Thus, we can create a template servlet structure, which can be used for a rapid devlopment of Java servlets. The following code can be used as such template servlet. Example 6. Template Servlet * Template Servlet

* import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.ioexception; import java.io.printwriter; public class TemplateServlet extends HttpServlet{ //--------------------------------------------------------------------- - * Handles HTTP GET method. * @param request HTTP request * @param response HTTP response * @exception ServletException * @exception IOException public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException{ // Use "request" to read incoming parameters, e.g. request.getparameter("query"); // Use "response" to write HTTP headers PrintWriter writer = response.getwriter(); // Use "writer" to send response to the client Two new classes appeared in the above example: HttpServletRequest and HttpSercletResponse class. These two classes provide an abstraction of the HTTP request and response, respectivelly. Thus, they provide methods to obtain parameters submitted by users (e.g. getparameter(name) method of the HttpServletRequest class), to write response to the client (e.g. getwriter() method of the HttpServletResponse class that returns a writer stream for writing response to the client), and similar. Hello World Servlet As the next example that does something useful (e.g. prints HelloWorld with today's date in browser ;=)) we will implement the famous Hello World example. Of course, we will reuse the above template servlet structure and extend it to implemt our desired functionality.

Example 7. Hello World Servlet * Hello World Servlet * import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.ioexception; import java.io.printwriter; import java.util.date; public class HelloWorldServlet extends HttpServlet{ //--------------------------------------------------------------------- - * Handles HTTP GET method. Sends "HelloWorld" as response to the client. * @param request HTTP request * @param response HTTP response * @exception ServletException * @exception IOException public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException{ String hello = "Hello World"; response.setcontenttype("text/html"); // set mime type of the response PrintWriter writer = response.getwriter(); writer.println("<html>"); writer.println("\t<head>"); writer.println("\t\t<link rel = \"stylesheet\" type = \"text/css\" href = \"style.css\">"); writer.println("\t\t<title>" + hello + "</title>"); writer.println("\t</head>"); writer.println("\t<body>"); writer.println(hello + " (" + (new Date()) + ")"); writer.println("\t</body>"); writer.println("</html>"); The Hello World example is accessible online at http://coronet.iicm.edu/mmisservlets/helloworld. The source code is also avaliable onlne: HelloWorldServlet.java.

The first thing we do in the Hello World example is that we set type of the response. To do so we invoke response.setcontenttype() method and provide a mime type as a string argument (e.g. "text/html"). This method sets a corresponding header in the HTTP response, so that the client (e.g. Web browser) knows what kind of data it gets. In our case that data is of course an HTML page. Finally, in the Hello World example we obtain the writer stream of the response object and write our HTML page to that stream. Writing an HTML page to the writer stream requires writing all HTML tags that constitute a valid HTML page to the writer. The first thing to notice in the Hello World example is that writing a servlet is usually related with writing a (possibly) large number of writer.println() statements to produce a valid HTML. Moreover, if we have a number of servlets, or a number of methods that write out HTML we usually end up with a lot of repeating writer.println() statements (e.g. writing document head, style sheet elements, ect.). To simplify the above process the so-called Element Construction Set [ECS2003] was developed within the scope of Apache Jakarta Project [Jakarta2003]. The Element Construction Set supports generation of HTML without need for numerous writer.println() statements. To make your servlets aware of the Element Construction Set you need to add the Java library implementing the Element Construction Set into the lib directory of your web application WEB-INF directory (e.g. /tomcat/webapps/hello/web- INF/lib). The Element Construction Set (ECS) might be obtained from the http://jakarta.apache.org/ecs/. Example 8. Hello World Servlet with ECS * Hello World Servlet with ECS * import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import org.apache.ecs.document; import org.apache.ecs.doctype; import org.apache.ecs.doctype.html40strict; import org.apache.ecs.html.body; import org.apache.ecs.html.head; import org.apache.ecs.html.title; import org.apache.ecs.html.link; import java.io.ioexception; import java.io.printwriter; import java.util.date;

public class ECSHelloWorldServlet extends HttpServlet{ //--------------------------------------------------------------------- - * Handles HTTP GET method. Sends "HelloWorld" as response to the client. * @param request HTTP request * @param response HTTP response * @exception ServletException * @exception IOException public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException{ String hello = "Hello World"; response.setcontenttype("text/html"); PrintWriter writer = response.getwriter(); Document document = new Document(); document.setdoctype(new Doctype.Html40Strict()); Title title = new Title(hello); document.settitle(title); Head head = document.gethead(); Body body = document.getbody(); Link link = new Link(); link.setrel("stylesheet"); link.settype("text/css"); link.sethref("style.css"); head.addelement(link); body.addelement(hello + " (" + (new Date()) + ")"); document.output(writer); The Hello World with ECS example is accessible online at http://coronet.iicm.edu/mmisservlets/ecshelloworld. The source code is also avaliable onlne: ECSHelloWorldServlet.java. In the new Hello World example we first need to import all the ECS specific classes, such as Document, Doctype.Html40Strict, Body, Title, Link, etc. In the doget() method we don't write directly to the writer stream, but rather create the response as an instance of the Document class, and add elements to that object. Thus, first we add a head element, which contains a title and a link element for a style sheet. At the next step, we add a body element containing our "Hello World" string together with the current date. Finally, we dump the document to the writer stream, thus sending the response to the client. At the first glance the ECS example does not look shorter or even simpler (we need also to learn how to use different ECS classes) than the first Hello World example, but the

Hello World example is actually to simple to really see the difference between a servlet with and without ECS. In larger projects, however, the ECS for sure pays off, since you can easily share ECS elements between methods or even between servlets, thus making it possible to reuse huge number of repeating HTML elements. For example, a link element that specifies a style sheet can be easily shared between methods and servlets, and most probably you will need only one link element (i.e. you need only one style sheet for a number of Web pages) for the whole application. Handling Requests with Servlets HTTP Request Headers Usually, each HTTP request contains a number of HTTP headers. The client sets HTTP headers to inform server about its communication preferences, about length of the content submitted, authorization information, cookies, and similar. The HttpServletRequest class represents a Java abstraction of HTTP request, thus providing high-level methods for investigating HTTP headers. The getheader() method accepts as an argument the name of a header and returns its value if the header was submittes by the client. If the header was not included in the client's request then this method returns null. The method getheadernames() returns an iterator over all header names that were submitted by the client. The next example prints out all HTTP request headers submitted by the client. Example 9. Printing HTTP Request Headers * HTTP Headers * import org.apache.ecs.document; import org.apache.ecs.doctype; import org.apache.ecs.doctype.html40strict; import org.apache.ecs.html.body; import org.apache.ecs.html.head; import org.apache.ecs.html.title; import org.apache.ecs.html.link; import org.apache.ecs.html.table; import org.apache.ecs.html.tr; import org.apache.ecs.html.th; import org.apache.ecs.html.td; import org.apache.ecs.html.p; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.ioexception; import java.io.printwriter;

import java.util.date; import java.util.enumeration; public class HeaderServlet extends HttpServlet{ //--------------------------------------------------------------------- - * Handles HTTP GET method. Prints HTTP headers in an HTML table. * @param HttpServletRequest request * @param HttpServletResponse response * @exception ServletException * @exception IOException public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException{ response.setcontenttype("text/html"); PrintWriter writer = response.getwriter(); Document document = new Document(); document.setdoctype(new Doctype.Html40Strict()); Title title = new Title("Header Servlet"); document.settitle(title); Head head = document.gethead(); Body body = document.getbody(); Link link = new Link(); link.setrel("stylesheet"); link.settype("text/css"); link.sethref("style.css"); head.addelement(link); Table table = new Table(); // print headers in a table TR table_header = new TR(true); table_header.addelement((new TH(true)).addElement("Key")); table_header.addelement((new TH(true)).addElement("Value")); table.addelement(table_header); Enumeration parameters = request.getheadernames(); while(parameters.hasmoreelements()){ String key = (String) parameters.nextelement(); String value = request.getheader(key); TR table_row = new TR(true); table_row.addelement((new TD(true)).addElement(key)); table_row.addelement((new TD(true)).addElement(value)); table.addelement(table_row); P paragraph = new P(); paragraph.setneedclosingtag(true); paragraph.addelement("http Headers"); body.addelement(paragraph); body.addelement(table);

document.output(writer); //--------------------------------------------------------------------- - * Handles HTTP POST method. Just invokes goget() method. * @param HttpServletRequest request * @param HttpServletResponse response * @exception ServletException * @exception IOException public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException{ doget(request, response); This example is accessible online at http://coronet.iicm.edu/mmis-servlets/header. The source code is also avaliable onlne: HeaderServlet.java. In the above example we handle also the POST method. However, in the dopost() method we just invoke the doget() method passing parameters that we obtained for the POST request. This can be seen as a standard approach for handling these two methods. Thus, we only implement one of these methods and redirect the other to the implemented method. Of course, we need to take care about some specific issues of POST method, such as processing the data submitted with the POST request. The HttpServletRequest class provides also a number of methods that allow programmers to retrieve information about the context in which a servlet is running, as well as the context of the current request. These methods are further compatible with CGI environement variables, which are the part of the CGI specification. For example, these methods include: getauthtype() for retrieving the type of authorization if an authorization header was supplied. getcontentlength(), which gets the length of the content supplied with the POST method. The same information might be obtained by getheader("content- LENGTH") method, but since this information is very often needed this special method was implemented. getcontenttype(), gets type of the data submitted with the POST method. Again, this information might be obtained through HTTP headers as well. getremoteaddr(), the IP address of the client. getremotehost(), the domain name of the client. getremoteuser(), the username if an authorization header was supplied with the request.

getservername(), the domain name where servlet is running. getserverport(), the port on which the server is listening. getserverprotocol(), the name and version of protocol that is used for the request. For complete list of the methods provided by the HttpServletRequest class consult the Java Servlet API documentation at http://java.sun.com/products/servlet/2.3/javadoc/index.html. Handling HTML forms HTML forms are often used to allow users to submit data to the server. For instance, to submit a search query to a search engine users type in their search terms in a text field provided by an HTML form. In an online reservation application users wotk with HTML forms to choose their preferable day of travel, travel conditions, and so on. Regarding the HTTP method used to submit the data, these HTML parameters are encoded as URLs (in the case of GET method), or they are submited as the request content (in the case of POST method). Usually, decoding parameters on the server side in the case of CGI programs needed to be accomplished by programmers. These was one of the most tedious part of CGI programming, and one of the reasons for the Java Servlet API developers to include this in the Servlet API. Thus, the HttpServlet Request class provides higl level methods which programmers can call to obtain the parameters submitted by users. Therby the HTTP method used for the request is totally abstracted in the API, thus allowing programmers to obtain parameters in the same way (i.e., by calling the same methods) regardless of the HTTP method used in the request. There are three methods in the HttpServletRequest class to obtain the request parameters: getparameter(), which takes as an argument the name of the parameter from HTML form. This method returns a String if the parameter with the specified name exists, otherwise null is returned. Generally, a parameter submitted by a user might have multiple values. In that case this method returns the first value for this parameter. getparametervalues(), which takes as an argument the name of the parameter from HTML form. This method returns an array of Strings if the parameter with the specified name exists, otherwise null is returned. getparameternames(), which returns an iterator over the names of all parameters submitted by a user. Thus, we might use this method to firstly get all names of parameters, and then we can call other two methods to obtain values of parameters. The next example provides a Java servlet that handles the parameters submitted by a user. For the front-end of this example we have a simple HTML form, which is a registration form that allows students to register for a university course. In this example we use the GET method to submit the data.

Example 10. HTML for Students Registration (GET Method) <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/tr/html4/loose.dtd"> <html> <head> <title>form example</title> <meta http-equiv = "Content-type" content = "text/html; charset=iso-8859-1"> <link rel = "stylesheet" type = "text/css" href = "style.css"> </head> <body> <h2>registration for MMIS</h2> <form action ="/mmis-servlets/form" method="get"> Name: <p> <input type = "text" name = "name" size = "20" maxlength = "50"> </p> Second Name: <p> <input type = "text" name = "second_name" size = "20" maxlength = "50"> </p> Matrikel Number: <p> <input type = "text" name = "nr" size = "20" maxlength = "50"> </p> Study Field: <p> <select name = "study_field"> <option value = "F874">Telematics <option value = "F860">Technical Mathematics <option value = "F033523">Software Development <option value = "F033211">Telematics Bachelor <option value = "F033221">Geomatics </select> </p> <p> <input type = "submit" value = "Register"> </p> </form> </body> </html> This HTML form is accessible online at http://coronet.iicm.edu/mmis/examples/java/form/form_get.html.

For submitting the data with the POST method we need to modify the form element of the GET example. The rest of the HTML form is same as before. Example 11. HTML for Students Registration (POST Method)...... <form action ="/mmis-servlets/form" method="post"> The POST HTML form is accessible online at http://coronet.iicm.edu/mmis/examples/java/form/form_post.html. Finally, we have the Java Servlet that handles the HTML forms. As mentioned in the example above, both of HTTP methods are handled with one and the same Java servlet, where requests including POST method are simple forwarded to the doget() method. Example 12. Java Servlet Handling HTML Forms * Handles parameters submitted by users * import org.apache.ecs.document; import org.apache.ecs.doctype; import org.apache.ecs.doctype.html40strict; import org.apache.ecs.html.body; import org.apache.ecs.html.head; import org.apache.ecs.html.title; import org.apache.ecs.html.link; import org.apache.ecs.html.table; import org.apache.ecs.html.tr; import org.apache.ecs.html.th; import org.apache.ecs.html.td; import org.apache.ecs.html.p; import javax.servlet.servletexception; import javax.servlet.http.httpservlet; import javax.servlet.http.httpservletrequest; import javax.servlet.http.httpservletresponse; import javax.servlet.http.httpsession; import java.io.ioexception; import java.io.printwriter; import java.util.date; import java.util.enumeration; public class FormServlet extends HttpServlet{

//--------------------------------------------------------------------- - * Handles HTTP GET method. Prints user parameters in an HTML table. * @param HttpServletRequest request * @param HttpServletResponse response * @exception ServletException * @exception IOException public void doget(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException{ response.setcontenttype("text/html"); PrintWriter writer = response.getwriter(); Document document = new Document(); document.setdoctype(new Doctype.Html40Strict()); Title title = new Title("Form Servlet"); document.settitle(title); Head head = document.gethead(); Body body = document.getbody(); Link link = new Link(); link.setrel("stylesheet"); link.settype("text/css"); link.sethref("style.css"); head.addelement(link); Table table = new Table(); TR table_header = new TR(true); table_header.addelement((new TH(true)).addElement("Key")); table_header.addelement((new TH(true)).addElement("Value")); table.addelement(table_header); Enumeration parameters = request.getparameternames(); while(parameters.hasmoreelements()){ String key = (String) parameters.nextelement(); String value = request.getparameter(key); TR table_row = new TR(true); table_row.addelement((new TD(true)).addElement(key)); table_row.addelement((new TD(true)).addElement(value)); table.addelement(table_row); P paragraph = new P(); paragraph.setneedclosingtag(true); paragraph.addelement("form Variables"); body.addelement(paragraph); body.addelement(table); document.output(writer); //--------------------------------------------------------------------- -

* Handles HTTP POST method. Just invokes goget() method. * @param HttpServletRequest request * @param HttpServletResponse response * @exception ServletException * @exception IOException public void dopost(httpservletrequest request, HttpServletResponse response) throws ServletException, IOException{ doget(request, response); The source code of this example is avaliable onlne: FormServlet.java. Bibliography Books [HallBrown2003] Marty Hall and Larry Browni. Copyright 1999 Marty Hall. 0130092290. Sun Microsystems Press and Prentice Hall PTR. Core Servlets and Java Server Pages. Online Resources [CGI1995] The CGI Specification, Version 1.1. http://hoohoo.ncsa.uiuc.edu/cgi/interface.html. [JavaServlet2003] The Java Servlet Specification, Version 2.3. http://java.sun.com/products/servlet/download.html. [JavaServletAPI2003] The Java Servlet API, Version 2.3. http://java.sun.com/products/servlet/2.3/javadoc/index.html. [Tomcat1999] Apache Tomcat. http://jakarta.apache.org/tomcat/index.html. [Apache2000] Apache Software Licences. http://www.apache.org/licenses/. [Jakarta2003] Apache Jakarta Project. http://jakarta.apache.org/. [ECS2003] Element Construction Set. http://jakarta.apache.org/ecs/.