Docsity

Understanding Servlets: Data Handling and Cookies, Study notes of Computer science

Toggle sidebar
bg1
1 Mrs. Chavan P.P.
Chapter 05
Servlets & JSP
Introduction
Servlets are small programs that execute on the server side of a Web
connection. Just as applets dynamically extend the functionality of a Web
browser, servlets dynamically extend the functionality of a Web server.
Servlets are generic extensions to Java-enabled servers. They are secure,
portable, and easy to use replacement for CGI. Servlet is a dynamically loaded
module that services requests from a Web server and executed within the Java
Virtual Machine. Because the servlet is running on the server side, it does not
depend on browser compatibility.
Servlet’s Job
• Read explicit data sent by client (form data)
• Read implicit data sent by client (request headers)
• Generate the results
• Send the explicit data back to client (HTML)
• Send the implicit data to client (status codes and response headers)
The Hypertext Transfer Protocol (HTTP)
HTTP is the protocol that allows web servers and browsers to exchange
data over the web. It is a request and response protocol. The client requests a
file and the server responds to the request. HTTP uses reliable TCP
connections—by default on TCP port 80. HTTP (currently at version 1.1 at the
time of this writing) was first defined in RFC 2068. It was then refined in RFC
2616, which can be found at http://www.w3c.org/Protocols/.
In HTTP, it's always the client who initiates a transaction by establishing a
connection and sending an HTTP request. The server is in no position to contact
a client or make a callback connection to the client. Either the client or the
server can prematurely terminate a connection. For example, when using a web
browser we can click the Stop button on our browser to stop the download
process of a file, effectively closing the HTTP connection with the web server.
HTTP Requests
An HTTP transaction begins with a request from the client browser and
ends with a response from the server. An HTTP request consists of three
components:
• Method——URI—Protocol/Version
• Request headers
• Entity body
pf3
pf4
pf5
pf8
pf9
pfa
pfd
pfe
pff
pf12
pf13
pf14
pf15
pf16
pf17
pf18
pf19
pf1a
pf1b
pf1c
pf1d
pf1e
pf1f
pf20
pf21
pf22
pf23
pf24
pf25
pf26
pf27
pf28
pf29
pf2a
pf2b
pf2c
pf2d
pf2e

Partial preview of the text

Download Understanding Servlets: Data Handling and Cookies and more Study notes Computer science in PDF only on Docsity!

Chapter 05

Servlets & JSP

Introduction

Servlets are small programs that execute on the server side of a Web connection. Just as applets dynamically extend the functionality of a Web browser, servlets dynamically extend the functionality of a Web server. Servlets are generic extensions to Java-enabled servers. They are secure, portable, and easy to use replacement for CGI. Servlet is a dynamically loaded module that services requests from a Web server and executed within the Java Virtual Machine. Because the servlet is running on the server side, it does not depend on browser compatibility. Servlet’s Job

  • Read explicit data sent by client (form data)
  • Read implicit data sent by client (request headers)
  • Generate the results
  • Send the explicit data back to client (HTML)
  • Send the implicit data to client (status codes and response headers)

The Hypertext Transfer Protocol (HTTP)

HTTP is the protocol that allows web servers and browsers to exchange data over the web. It is a request and response protocol. The client requests a file and the server responds to the request. HTTP uses reliable TCP connections—by default on TCP port 80. HTTP (currently at version 1.1 at the time of this writing) was first defined in RFC 2068. It was then refined in RFC 2616, which can be found at http://www.w3c.org/Protocols/. In HTTP, it's always the client who initiates a transaction by establishing a connection and sending an HTTP request. The server is in no position to contact a client or make a callback connection to the client. Either the client or the server can prematurely terminate a connection. For example, when using a web browser we can click the Stop button on our browser to stop the download process of a file, effectively closing the HTTP connection with the web server. HTTP Requests An HTTP transaction begins with a request from the client browser and ends with a response from the server. An HTTP request consists of three components:

  • Method——URI—Protocol/Version
  • Request headers
  • Entity body

An example of an HTTP request is the following: GET /servlet/default.jsp HTTP/1. Accept: text/plain; text/html Accept-Language: en-gb Connection: Keep-Alive Host: localhost Referer: http://localhost/ch8/SendDetails.htm User-Agent: Mozilla/4.0 (compatible; MSIE 4.01; Windows 98) Content-Length: 33 Content-Type: application/x-www-form- urlencoded Accept-Encoding: gzip, deflate LastName=Franks&FirstName=Michael The method—URI—protocol version appears as the first line of the request. GET /servlet/default.jsp HTTP/1. where GET is the request method, /servlet/default.jsp represents the URI and HTTP/1.1 the Protocol/Version section. The request method will be explained in more details in the next section, "HTTP request Methods." The URI specifies an Internet resource completely. A URI is usually interpreted as being relative to the server's root directory. Thus, it should always begin with a forward slash /. A URL is actually a type of URI (see http://www.ietf.org/rfc/rfc2396.txt). The Protocol version represents the version of the HTTP protocol being used. The request header contains useful information about the client environment and the entity body of the request. For example, it could contain the language the browser is set for, the length of the entity body, and so on. Each header is separated by a carriage return/linefeed (CRLF) sequence. Between the headers and the entity body, there is a blank line (CRLF) that is important to the HTTP request format. The CRLF tells the HTTP server where the entity body begins. In some Internet programming books, this CRLF is considered the fourth component of an HTTP request. In the previous HTTP request, the entity body is simply the following line: LastName=Franks&FirstName=Michael The entity body could easily become much longer in a typical HTTP request. Method Description GET GET is the simplest, and probably, most used HTTP method. GET simply retrieves the data identified by the URL. If the URL refers to a script (CGI, servlet, and so on), it returns the data produced by the script. HEAD The HEAD method provides the same functionality as GET, but HEAD only returns HTTP headers without the document body. POST Like GET, POST is also widely used. Typically, POST is used in HTML

Applications of Java Servlets

  • Building e-commerce store fronts o Servlet builds an online catalog based on the contents of a database o Customer places an order, which is processed by another servlet
  • Servlets as wrappers for legacy systems
  • Servlets interacting with EJB applications Java Servlet alternatives [Ref.1] ColdFusion. Allaire's ColdFusion provides HTML-like custom tags that can be used to perform a number of operations, especially querying a database. This technology had its glamorous time in the history of the World Wide Web as the main technology for web application programming. Its glorious time has since gone with the invention of other technologies. Server-side JavaScript (SSJS). SSJS is an extension of the JavaScript language, the scripting language that still rules client-side web programming. SSJS can access Java classes deployed at the server side using the LiveWire technology from Netscape. PHP. PHP is an exciting open-source technology that has matured in recent years. The technology provides easy web application development with its session management and includes some built-in functionality, such as file upload. The number of programmers embracing PHP as their technology of choice has risen sharply in recent years. Servlet. The servlet technology was introduced by Sun Microsystems in 1996. JavaServer Pages (JSP). JSP is an extension of the servlet technology. Active Server Pages (ASP). Microsoft's ASP employs scripting technologies that work in Windows platforms, even though there have been efforts to port this technology to other operating systems. Windows ASP works with the Internet Information Server web server. This technology will soon be replaced by Active Server Pages.NET. Active Server Pages.NET (ASP.NET). This technology is part of Microsoft's .NET initiative. Interestingly, the .NET Framework employs a runtime called the Common Language Runtime that is very similar to Java Virtual Machine and provides a vast class library available to all .NET languages and from ASP.NET pages. ASP.NET is an exciting technology. It introduced several new technologies including state management that does not depend on cookies or URL rewriting. The Benefits of Servlets
  • Efficiency : More efficient – uses lightweight java threads as opposed to individual processes.
  • Persistency : Servlets remain in memory. They can maintain state between requests.
  • Portability : Since servlets are written in Java, they are platform independent.
  • Robustness : Error handling, Garbage collector to prevent problems with memory leaks. Large class library – network, file, database, distributed object components, security, etc.
  • Extensibility : Creating new subclasses that suite your needs Inheritance, polymorphism, etc.
  • Security : Security provided by the server as well as the Java Security Manager. It eliminates problems associated with executing cgi scripts using operating system “shells”.
  • Powerful : Servlets can directly talk to web server and facilitates database connection pooling, session tracking etc.
  • Convenient : Parsing and decoding HTML form data, reading and setting HTTP headers, handling cookies, etc.
  • Rapid development cycle: As a Java technology, servlets have access to the rich Java library, which helps speed up the development process.
  • Widespread acceptance: Java is a widely accepted technology. This means that numerous vendors work on Java-based technologies. One of the advantages of this widespread acceptance is that we can easily find and purchase components that suit our needs, which saves precious development time. How a Servlet Works A servlet is loaded by the servlet container the first time the servlet is requested. The servlet then is forwarded the user request, processes it, and returns the response to the servlet container, which in turn sends the response back to the user. After that, the servlet stays in memory waiting for other requests—it will not be unloaded from the memory unless the servlet container sees a shortage of memory. Each time the servlet is requested, however, the servlet container compares the timestamp of the loaded servlet with the servlet class file. If the class file timestamp is more recent, the servlet is reloaded into memory. This way, we don't need to restart the servlet container every time we update our servlet. The Tomcat Servlet Container A number of servlet containers are available today these are listed below:
  • Apache Tomcat http://jakarta.apache.org/tomcat/
  • Allaire/Macromedia JRun http://www.macromedia.com/software/jrun/
  • New Atlanta ServletExec http://www.servletexec.com/
  • Gefion Software LiteWebServer http://www.gefionsoftware.com/LiteWebServer/
  • Caucho's Resin

PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("Servlet Testing"); out.println(""); out.println(""); out.println("Welcome to the Servlet Testing Center"); out.println(""); out.println(""); } } Now, save TestingServlet.java file to /bin directory of JDK.

  1. Compiling the source code For our servlet source code to compile, we need to include the path to the servlet-api.jar file in our CLASSPATH environment variable. The servlet-api.jar is located in the C:\Program Files\Apache Software Foundation\Tomcat 6.0 directory. Here, the drive name depends upon our selection while installation of Tomcat 6.0 on computer. So, compile the file using following way: javac TestingServlet.java - classpath "G:\Program Files\Apache Software Foundation\Tomcat 6.0\lib\servlet-api.jar" After successful compilation, we will get a class file named TestingServlet.class. Now, copy that class file into directory \classes under web-inf as shown in the following figure. All the servlet classes resides in this directory.
  2. Create the Deployment Descriptor A deployment descriptor is an optional component in a servlet application. The descriptor takes the form of an XML document called web.xml and must be located in the WEB-INF directory of the servlet application. When present, the deployment descriptor contains configuration settings specific to that application. In order to create the deployment descriptor, we now need to create or edit a web.xml file and place it under the WEB-INF directory. The web.xml for this example application must have the following content.

Testing TestingServlet

class> TestingServlet /servlets/servlet/TestingServlet

The web.xml file has one element—web-app. We should write all our servlets under . For each servlet, we have a element and we need the and elements. The is the name for our servlet, by which it is known Tomcat. The is the compiled file of your servlet without the .class extension. Location of servlet-api.jar file Location of web.xml file Location for storing .java and .class files We can also add multiple servlet names in our file using multiple servlet tags. The url-pattern suggests the url by which we are going to class our servlet in the web browser. Instead of doing this we can just modify the contents of web.xml by adding the names and mapping of our servlet code.

  1. Run Tomcat If Tomcat is not already running, we need to start it by selecting the option “monitor tomcat” from srart menu. We will find the icon of Apache Tomcat on the taskbar when it is running.
  2. Call Your Servlet from a Web Browser Now, we can call our servlet from a web browser. By default, Tomcat runs on port 8080. The URL for that servlet has the following format: http://domain-name/virtual-directory/servlet/servlet-name If we run the web browser from the same computer as Tomcat, you can replace the domain-name part with "localhost". In that case, the URL for your servlet is: http://localhost:8080/examples/servlets/servlet/TestingServlet Typing the URL in the Address or Location box of our web browser will give you the string "Welcome to the Servlet Testing Center,"

The javax.servlet package

The javax.servlet package contains seven interfaces, three classes, and two exceptions. The seven interfaces are as follows:

  • RequestDispatcher

Collection Fig. Servlet’s Life Cycle The init( ) method

  • It request for a servlet received by the servlet engine.
  • Checks to see if the servlet is already loaded.
  • If not, uses a class loader to get the required servlet class and instantiates it by calling the constructor method.
  • After the servlet is loaded, but before it services any requests, the init ( ) method is called.
  • Inside init( ), the resources used by the servlet are initialized. E.g: establishing database connection.
  • This method is called only once just before the servlet is placed into service.
  • The init( ) method takes a ServletConfig object as a parameter. Its signature is: public void init(ServletConfig config) throws ServletException
  • Most common way of doing this is to have it call the super.init( ) passing it the ServletConfig object. The service( ) method
  • The service( ) method handles all requests sent by a client.
  • It cannot start servicing requests until the init( ) method has been executed.
  • Only a single instance of the servlet is created and the servlet engine dispatches each request in a single thread.
  • The service( ) method is used only when extending GenericServlet class.
  • Since servlets are designed to operate in the HTTP environment, the HttpServlet class is extended.
  • The service(HttpServletRequest, HttpServletResponse) method examines the request and calls the appropriate doGet() or doPost() method.
  • A typical Http servlet includes overrides to one or more of these subsidiary methods rather than an override to service(). The destroy( ) method
  • This method signifies the end of a servlet’s life.
  • The resources allocated during init( ) are released.
  • Save persistent information that will be used the next time the servlet is loaded.
  • The servlet engine unloads the servlet.
  • Calling destroy( ) yourself will not acutally unload the servlet. Only the servlet engine can do this. Demonstrating the Life Cycle of a Servlet

The following program contains the code for a servlet named PrimitiveServlet, a very simple servlet that exists to demonstrate the life cycle of a servlet. The PrimitiveServlet class implements javax.servlet.Servlet (as all servlets must) and provides implementations for all the five methods of servlet. What it does is very simple. Each time any of the init, service, or destroy methods is called, the servlet writes the method's name to the console. import javax.servlet.*; import java.io.IOException; public class PrimitiveServlet implements Servlet { public void init(ServletConfig config) throws ServletException { System.out.println("init"); } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("service"); } public void destroy() { System.out.println("destroy"); } public String getServletInfo() { return null; } public ServletConfig getServletConfig() { return null; } } The web.xml File for PrimitiveServlet:

PrimitiveServlet PrimitiveServlet

We should then be able to call this servlet from our browser by typing the following URL: http://localhost:8080/examples/servlets/servlet/PrimitiveServlet The first time the servlet is called, the console displays these two lines:

METHOD="POST">

Author:

The RequestDemoServlet.java file: import javax.servlet.*; import java.util.Enumeration; import java.io.IOException; public class RequestDemoServlet implements Servlet { public void init(ServletConfig config) throws ServletException { } public void destroy() { } public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { System.out.println("Server Port: " + request.getServerPort()); System.out.println("Server Name: " + request.getServerName()); System.out.println("Protocol: " + request.getProtocol()); System.out.println("Character Encoding: " + request.getCharacterEncoding()); System.out.println("Content Type: " + request.getContentType()); System.out.println("Content Length: " + request.getContentLength()); System.out.println("Remote Address: " + request.getRemoteAddr()); System.out.println("Remote Host: " + request.getRemoteHost()); System.out.println("Scheme: " + request.getScheme()); Enumeration parameters = request.getParameterNames(); while (parameters.hasMoreElements()) { String parameterName = (String) parameters.nextElement(); System.out.println("Parameter Name: " + parameterName); System.out.println("Parameter Value: " + request.getParameter(parameterName)); } Enumeration attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); System.out.println("Attribute name: " + attribute); System.out.println("Attribute value: " + request.getAttribute(attribute)); } } public String getServletInfo() { return null;

public ServletConfig getServletConfig() { return null; } } The ServletResponse Interface The ServletResponse interface represents the response to the user. The most important method of this interface is getWriter, from which we can obtain a java.io.PrintWriter object that we can use to write HTML tags and other text to the user. The codes of the program given below offer an HTML file named index2.html and a servlet whose service method is overridden with code that outputs some HTML tags to the user. This servlet modifies the example below retrieves various information about the user. Instead of sending the information to the console, the service method sends it back to the user. index2.html

Sending a request

out.println("Parameter Name: " + parameterName); out.println("Parameter Value: " + request.getParameter(parameterName)); } Enumeration attributes = request.getAttributeNames(); while (attributes.hasMoreElements()) { String attribute = (String) attributes.nextElement(); out.println("Attribute name: " + attribute); out.println("Attribute value: " + request.getAttribute(attribute)); } out.println(""); out.println(""); } public String getServletInfo() { return null; } public ServletConfig getServletConfig() { return null; } }

GenericServlet

Till this point, we have been creating servlet classes that implement the javax.servlet.Servlet interface. Everything works fine, but there are two annoying things that we've probably noticed:

  1. We have to provide implementations for all five methods of the Servlet interface, even though most of the time we only need one. This makes your code look unnecessarily complicated.
  2. The ServletConfig object is passed to the init method. We need to preserve this object to use it from other methods. This is not difficult, but it means extra work. The javax.servlet package provides a wrapper class called GenericServlet that implements two important interfaces from the javax.servlet package: Servlet and ServletConfig, as well as the java.io.Serializable interface. The GenericServlet class provides implementations for all methods, most of which are blank. We can extend GenericServlet and override only methods that we need to use. Clearly, this looks like a better solution. The program given below called SimpleServlet that extends GenericServlet. The code provides the implementation of the service method that sends some output to the browser. Because the service method is the only method we need, only this method needs to appear in the class. Compared to all servlet classes that implement the javax.servlet.Servlet interface directly, SimpleServlet looks much cleaner and clearer. import javax.servlet.*; import java.io.IOException; import java.io.PrintWriter; public class SimpleServlet extends GenericServlet {

public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println(""); out.println("Extending GenericServlet"); out.println(""); out.println(""); out.println(""); out.println("Extending GenericServlet makes your code simpler."); out.println(""); out.println(""); } }

The HttpServlet Class

The HttpServlet class extends the javax.servlet.GenericServlet class. The HttpServlet class also adds a number of interesting methods to use. The most important are the six doxxx methods that get called when a related HTTP request method is used. The six methods are doPost, doPut, doGet, doDelete, doOptions and doTrace. Each doxxx method is invoked when a corresponding HTTP method is used. For instance, the doGet method is invoked when the servlet receives an HTTP request that was sent using the GET method. Of the six doxxx methods, the doPost and the doGet methods are the most frequently used. The doPost method is called when the browser sends an HTTP request using the POST method. The POST method is one of the two methods that can be used by an HTML form. Consider the following HTML form at the client side:

When the user clicks the Submit button to submit the form, the browser sends an HTTP request to the server using the POST method. The web server then passes this request to the Register servlet and the doPost method of the servlet is invoked. Using the POST method in a form, the parameter name/value pairs of the form are sent in the request body. For example, if we use the preceding form as an example and enter ‘Sunil’ as the value for firstName and ‘Go’ as the value for lastName, we will get the following result in the request body: firstName=Sunil

public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("The GET method"); out.println(""); out.println(""); out.println("The servlet has received a GET. "

  • "Now, click the button below."); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); out.println(""); } public void doPost( HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println(""); out.println(""); out.println("The POST method"); out.println(""); out.println(""); out.println("The servlet has received a POST. Thank you."); out.println(""); out.println(""); } } When the servlet is first called from a web browser by typing the URL to the servlet in the Address or Location box, GET is used as the request method. At the server side, the doGet method is invoked. The servlet sends a string saying "The servlet has received a GET. Now, click the button below." plus an HTML form. The output is shown in Figure below: The form sent to the browser uses the POST method. When the user clicks the button to submit the form, a POST request is sent to the server. The servlet then invokes the doPost method, sending a String saying, "The servlet has received a POST. Thank you," to the browser.

HttpServletRequest Interface

In addition to providing several more protocol-specific methods in the

HttpServlet class, the javax.servlet.http package also provides more sophisticated request and response interfaces. Obtaining HTTP Request Headers from HttpServletRequest The HTTP request that a client browser sends to the server includes an HTTP request header with important information, such as cookies and the referer. We can access these headers from the HttpServletRequest object passed to a doxxx method. The following example demonstrates how we can use the HttpServletRequest interface to obtain all the header names and sends the header name/value pairs to the browser. //Obtaining HTTP request Headers import javax.servlet.; import javax.servlet.http.; import java.io.; import java.util.; public class RegisterServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); Enumeration enumeration = request.getHeaderNames(); while(enumeration.hasMoreElements()) { String header = (String) enumeration.nextElement(); out.println(header + ": " + request.getHeader(header) + ""); } } } The RegisterServlet given above uses the getHeaderNames and the getHeader methods. The getHeaderNames is first called to obtain an Enumeration containing all the header names found in the client request. The value of each header then is retrieved by using the getHeader method, passing a header name. The output of the code depends on the client environment, such as the browser used and the operating system of the client's machine. For example, some browsers might send cookies to the server. Also, whether the servlet is requested by the user typing the URL in the Address/Location box or by clicking a hyperlink also accounts for the presence of an HTTP request header called referer. Obtaining the Query String from HttpServletRequest