11

Click here to load reader

Unit5 servlets

Embed Size (px)

Citation preview

Page 1: Unit5 servlets

Servlets 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.

Use & Advantages of ServletConsider a request for a static Web page.

A user enters a Uniform Resource Locator (URL) to a browser. The browser generates an HTTP request to the appropriate Web server. The Web server maps this request to a specific file. That file is returned in an HTTP response to

the browser. The HTTP header in the response indicates the type of the content.

Now consider dynamic content. Assume that an online bookstore uses a database to store information about its business, including book prices, availability, orders, and so forth. It wants to make this information accessible to customers via Web pages. The contents of those Web pages must be dynamically generated, to reflect the latest information in the database.In the early days of the Web, a server could dynamically construct a page by creating a separate process to handle each client request. The process would open connections to one or more databases in order to obtain the necessary information. It communicated with the Web server via an interface known as the Common Gateway Interface (CGI). CGI allowed the separate process to read data from the HTTP request and write data to the HTTP response. A variety of different languages were used to build CGI programs, including C, C++, and Perl. However, CGI suffered serious performance problems. Creating a separate process for each client request was expensive, in terms of processor and memory resources. It was also expensive to open and close database connections for each client request. In addition, the CGI programs were not platform-independent. Therefore, other techniques were introduced, including servlets.Servlets offer several advantages over CGI:

Performance is significantly better. Servlets execute within the address space of a Web server. Creating a separate process to handle each client request isn't necessary.

Servlets are platform-independent, because they are written in Java. Several Web servers, from vendors such as Sun, Netscape, and Microsoft, offer the Servlets API. Programs developed for this API can be moved to any of these environments without recompilation.

The Java Security Manager on the server enforces a set of restrictions to protect the resources on a server machine.

The full functionality of the Java class libraries is available to a servlet. It can communicate with applets, databases, or other software via the sockets and RMI mechanisms that you have seen already.

The Life Cycle of a Servlet Three methods are central to the life cycle of a servlet: init ( ), service ( ), and destroy ( ). They are implemented by every servlet and are invoked at specific times by the server.

First, assume that a user enters a Uniform Resource Locator (URL) to a Web browser. The browser then generates an HTTP request for this URL and sends it to the appropriate server.

Second, this HTTP request is received by the Web server. The server maps this request to a particular servlet. The servlet is dynamically retrieved and loaded into the address space of the server.

Third, the server invokes the init ( ) method of the servlet. This method is invoked only when the servlet is first loaded into memory. Initialization parameters can be passed to the servlet so that it may configure itself.

Page 2: Unit5 servlets

Fourth, the server invokes the servlet's service ( ) method, which is called to process the HTTP request. The servlet can read data that has been provided in the HTTP request, and may also formulate an HTTP response for the client. The servlet remains in the server's address space and is available to process any other HTTP requests received from clients. The service ( ) method is called for each HTTP request.

Finally, the server may decide to unload the servlet from its memory. The algorithms by which this determination is made are specific to each server. The server calls destroy () method to relinquish any resources, such as file handles that are allocated for the servlet. Important data may be saved to a persistent store. The memory allocated for the servlet and its objects can then be garbage-collected.

Using Tomcat for Servlet DeploymentTo create servlets, download a servlet development environment. The one currently recommended by Sun is Tomcat which supports the servlet specification. Tomcat is an open source product maintained by Jakarta Project of the Apache Software Foundation. It contains the class libraries; documentation and run-time support which are needed to create and test servlet.Follow the instructions to install the Tomcat on your machine. The default location for Tomcat is C:\Program Files\Apache Software Foundation\Set the classpath of the servlet-api.jar file in the variable CLASSPATH inside the environment variable by using the following steps: For Windows XP,  Go to Start->Control Panel->System->Advanced->Environment Variables->New button and Set values: Variable Name:  CLASSPATH Variable Value:  C:\Program Files\Java\Tomcat 6.0\lib\servlet-api.jarServlet-api.jar file contains the classes and interfaces that are needed to build servlet.

Start and Stop TomcatTo start Tomcat, select Start Tomcat in the Start| Programs Menu, or run startup.bat from theC:\Program Files\Apache Software Foundation\ Tomcat 6.0\bin\directory. To stop Tomcat, select Stop Tomcat in the Start| Programs Menu, or run shutdown.bat.

Web Application Directory StructureDirectory ContainsC:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\myApps This is the root directory of the web application. All JSP and XHTML files are stored here.C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\myApps\WEB-INF This directory contains all resources related to the application that are not in the document root of the application. This is where your web application deployment descriptor (web.xml) is located. Note that the WEB-INF directory is not part of the public document. No files contained in this directory can be served directly to a client.

Page 3: Unit5 servlets

C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\myApps\WEB-INF\classes This directory is where servlet and utility classes are located.C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps\ myApps\WEB-INF\lib This directory contains Java Archive files that the web application depends upon.

A Simple Servlet (Imp) The basic steps for building and testing a simple servlet are the following:

Create a java source file and a web.xml file in a Tomcat directory structure.  Compile the java source file, put the compiled file (.class file) in the classes’ folder of your

application and deploy the directory of your application in the webapps folder inside the tomcat directory.

Start the tomcat server, open a browser window and type the URL http://localhost:8080/directory (folder name of your application) name/servlet name and press enter.

Create and Compile the Servlet Source CodeTo begin, create a file named HelloServlet.java that contains the following program:import java.io.*;import javax.servlet.*;public class HelloServlet extends GenericServlet {public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("<B>Hello!");pw.close();}}First, the program imports the javax.servlet package, which contains the classes and interfaces required to build servlets. Next, the program defines HelloServlet as a subclass of GenericServlet. The GenericServlet class provides functionality that makes it easy to handle requests and responses.Inside HelloServet, the service( ) method (which is inherited from GenericServlet) is overridden. This method handles requests from a client. Notice that the first argument is a ServletRequest object. This enables a servlet to read data that is provided via the client request. The second argument is a ServletResponse object. This enables a servlet to formulate a response for the client. The call to setContentType( ) establishes the MIME type of the HTTP response. The MIME type text/html indicates that the browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter. Anything written to this stream is sent to the client as part of the HTTP response. Then, println( ) is used to write some simple HTML source code as the HTTP response.Compile this source code and place the HelloServlet.class file in the Tomcat class files directory as described previously.

Create Deployment Descriptor (web.xml)A deployment descriptor is an optional component in a servlet application, taking the form of an XML document called web.xml. The descriptor must be located in the WEB-INF directory of the servlet application. When present, the deployment descriptor contains configuration settings specific to that application.For this step, create a web.xml file and place it under the WEB-INF directory under myApp. The web.xml for this example application must have the following content.<?xml version="1.0" encoding="ISO-8859-1"?><web-app>

Page 4: Unit5 servlets

<servlet> <servlet-name>Testing</servlet-name> <servlet-class>HelloServlet</servlet-class> </servlet><servlet-mapping> <servlet-name>Testing</servlet-name> <servlet-class>/TestingServlet</servlet-class> </servlet-mapping></web-app>

Start TomcatAs explained above.

Start a Web Browser and Request the ServletStart a Web browser and enter the URL shown here:http://localhost:8080/directory name (myApps)/TestingServlet and press enter.Alternatively, you may enter the URL shown here:http:// 127.0.0.1:8080/ directory name (myApps)/TestingServletThis can be done because 127.0.0.1 is defined as the IP address of the local machine.The output of the servlet in the browser display area should contain the string Hello! In bold type.

The Servlet APITwo packages contain the code that is required to build servlets: javax.servlet and javax.servlet.http. They constitute the Servlet API. These packages are not part of the Java core packages. Therefore, they are not included in the Java Development Kit (JDK). Download Tomcat to obtain their functionality.

The javax.servlet PackageThe javax.servlet package contains a number of interfaces and classes that establish the framework in which servlets operate. The most significant of these is Servlet. All servlets must implement this interface or extend a class that implements the interface. The following table summarizes the interfaces that are provided in this package.Interface DescriptionServlet Declares life cycle methods for a servlet.ServletConfig Allows servlets to get initialization parameters.ServletContext Enables servlets to log events and access information about their

environment.ServletRequest Used to read data from a client request.ServletResponse Used to write data to a client response.SingleThreadModel Indicates that the servlet is thread safe.

The following table summarizes the classes that are provided in this package:Class DescriptionGenericServlet Implements the Servlet and ServletConfig interfaces.ServletInputStream Provides an input stream for reading requests from a client.ServletOutputStream Provides an output stream for writing responses to a client.ServletException Indicates that a servlet error occurred.UnavailableException Indicates that a servlet is permanently or temporarily

unavailable.

The javax.servlet.http Package

Page 5: Unit5 servlets

The javax.servlet.http package contains several interfaces and classes that are commonly used by servlet developers. The following table summarizes the interfaces that are provided in this package:Interface DescriptionHttpServletRequest Enables servlets to read data from an HTTP request.HttpServletResponse Enables servlets to write data to an HTTP response.HttpSession Allows session data to be read and written.HttpSessionBindingListener Informs an object that it is bound to or unbound from a session.HttpSessionContext Allows sessions to be managed.The following table summarizes the classes that are provided in this package. The most important of these is HttpServlet.Class DescriptionCookie Allows state information to be stored on a client machine.HttpServlet Provides methods to handle HTTP requests and responses.HttpSessionBindingEvent Indicates when a listener is bound to or unbound from a session value.HttpUtils Declares utility methods for servlets.

Handling HTTP Requests and ResponsesThe HttpServlet class provides specialized methods that handle the various types of HTTP requests. A servlet developer typically overrides one of these methods. These methods are doDelete ( ), doGet ( ), doOptions ( ), doPost ( ), doPut ( ), and doTrace ( ).However, the GET and POST methods are commonly used when handling form input.

Handling HTTP GET RequestsThis section develops a servlet that handles an HTTP GET request. The servlet is invoked when a form on a Web page is submitted. The example contains two files: ColorGet.htm defines a Web page, and ColorGetServlet.java defines a servlet.ColorGet.htm defines a form that contains a select element and a submit button. Notice that the action parameter of the form tag specifies a URL. The URL identifies a servlet to process the HTTP GET request.<html><body><form name="Form1" method=”get” action="Servlet1"><b><center>color:<center><b><select name="color" ><option value="Red">Red</option><option value="Green">Green</option></select><input type=submit value="Submit"></form></body></html>The source code for ColorGetServlet.java is shown in the following listing. The doGet( ) method is overridden to process any HTTP GET requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class ColorGetServlet extends HttpServlet {public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color");response.setContentType("text/html");

Page 6: Unit5 servlets

PrintWriter pw = response.getWriter();pw.println("<B><center>The selected color is: ");pw.println(color);pw.close(); }}Compile the servlet and perform the following steps:

1. Start Tomcat2. Display the Web page in the browser3. Select a color and submit the web page

Parameters for an HTTP GET request are included as part of the URL that is sent to the Web server. Assume that the user selects the red option and submits the form. The URL sent from the browser to the server is the following: http://localhost:8080/servler/ColorGetServlet?color=RedThe characters to the right of the question mark are known as the query string.Deployment Descriptor should be created as discussed in the previous section.

Handling HTTP POST RequestsThis section develops a servlet that handles an HTTP POST request. The servlet is invoked when a form on a Web page is submitted. The example contains two files: ColorPost.htm defines a Web page, and ColorPostServlet.java defines a servlet. ColorPost.htm is identical to ColorGet.htm except that the method parameter for the form tag explicitly specifies that the POST method should be used, and the action parameter for the form tag specifies a different servlet.<html><body><form name="Form2" method="post" action="servlet2"><b><center>color:<center><b><select name="color" ><option value="Red">Red</option><option value="Green">Green</option></select><input type=submit value="Submit"></form></body></html>The source code for ColorPostServlet.java is shown in the following listing. The doPost( ) method is overridden to process any HTTP POST requests that are sent to this servlet. It uses the getParameter( ) method of HttpServletRequest to obtain the selection that was made by the user. A response is then formulated.import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class ColorPostServlet extends HttpServlet {public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String color = request.getParameter("color");response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("<B>The selected color is: ");pw.println(color);pw.close();}}Compile the servlet and perform the following steps:

1. Start Tomcat 2. Display the Web page in the browser3. Select a color and submit the web page

An HTTP POST request are not included as part of the URL that is sent to the Web server. In this example, the URL sent from the browser to the server is the following:http://localhost:8080/servler/ColorGetServlet

Page 7: Unit5 servlets

The parameter names and values are sent in the body of the HTTP request.Deployment Descriptor should be created as discussed in the previous section.

Difference between Get and Post Method GET is the simplest HTTP method, and it is used to ask the server to get a resource and send it back. That resource might be an HTML page, a JPEG, a PDF, etc. The point of GET is to get something back from the server.

POST is a more powerful request. With POST, we can request something and at the same time send form data to the server. There are the following differences between Get & Post Methods:

Visibility - GET request is sent via the URL string (appended to the URI with a question-mark as separator), which is visible whereas POST request is encapsulated in the body of the HTTP request and can't be seen.

Length - Since, GET request goes via URL, so it has a limitation for its length. POST request has not such limitation because it becomes a part of the body of the HTTP request.

Performance - GET request is comparatively faster as it's relatively simpler to create a GET request and the time spent in the encapsulation of the POST request in the HTTP body is saved in this case.

Type of Data - GET request is sent via URL string and URL can be text-only, so GET can carry only text data whereas POST has no such restriction and it can carry both text as well as binary data.

Caching/Bookmarking - A GET request is nothing but an URL hence it can be cached as well as Bookmarked. A POST request can’t be bookmarked.

FORM Default - GET is the default method of the HTML FORM element. To submit a FORM using POST method, we need to specify the method attribute and give it the value "POST".

Security IssuesUntrusted applets are constrained to operate in a "sandbox." They cannot perform operations that are potentially dangerous to a user's machine. This includes reading and writing files, opening sockets to arbitrary machines, calling native methods, and creating new processes. Other restrictions also apply.Similar constraints also exist for untrusted servlets. Code that is loaded from a remote machine is untrusted. However, trusted servlets, those loaded from the local machine, are not limited in this manner.

Questions: 1) What are the servlets? Describe the uses and advantages of servlets. (Imp)2) Describe the life cycle of servlets and discuss the servlet API and security issues in servlets.

(M. Imp)3) Write down the introduction to servlet and explain the servlet with a suitable example. (Imp)4) Write a short note on Tomcat Server.5) What is the difference between GenericServlet and HttpServlet. (M. Imp)6) What is the Difference between Get and Post? (Imp)