Download as pdf or txt
Download as pdf or txt
You are on page 1of 33

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Introduction to Servlets

Servlets are server side programs written in Java. The Servlet initialization code is executed only once Separate threads in the server handle each request Platform independent: Write once, run anywhere

Advantages of Servlets: 1. Portability: As servlets are written in java and follow well known standardized APIs they are highly portable across operating systems and server implementation. We can develop a servlet on Windows machine and later we can deploy the same in any other operating system like UNIX server. 2. Powerful: Servlets can share data among each other; they even make the database connection pools easy to implements. They can maintain the session by using the session tracking mechanism which helps them to maintain information from request to request. 3. Efficiency: Once the servlet is loaded in the server, it remains as a single object instance. There will only be N threads but only a single copy of the servlet class. Multiple threads handle the requests, so we can say servlets are highly efficient in terms of the load usage. 4. Safety: Javas automatic garbage collection and lack of pointers means that servlets are generally safe from memory management problems. And also they can handle the errors easily, due to Javas exception handling mechanism. 5. Integration: Servlets can be easily integrated into the server. Many free web servers are available for personal use or for commercial purpose. Introduction to Web Server & Application Server

WEB SERVER It is generally the combination of computer and the program installed on it. Web server helps to deliver the content that can be accessed through the internet. But this doesnt support the business logic component (EJB). In Java language perspective the components that are supported are Servlets and JSP.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

APPLICATION SERVER It exposes the business logic to clients applications through various protocols including HTTP. In most of the cases, the server exposes the business logic through a component API, such as the EJB (Enterprise Java Bean) component model found on J2EE (Java 2 Platform, Enterprise Edition) application servers. Moreover, the application server manages its own resources like: security, transaction processing, resource pooling and messaging.

CONTAINER Servlets dont have the main () method. Theyre under the control of another java application called a Container. It provides the following features for the servlet.

Request

WEB CONTAINER

Loads the Servlet class Instantiates the Servlet

First Client Request

Initializes the Servlet Instance

Passes Request to the Servlet Instance

Response

Sends Response

Imagine if there is no Container, then we have to implement the following. Create a thread manager Security Implementation Filters for logging data record Memory management Connection status i.e. Successful/Failure notification Garbage collection responsibilities

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

SERVLET API

Interfaces
Servlet ServletConfig Serializable

Generic Servlet

Built-inClasses

HttpServlet

User defined
UserDefinedServlet

Class

High Level Design of Servlet Class Hierarchy

The container manages a servlet by invoking various life cycle methods which are defined in the Servlet API. It is a collection of classes and interfaces which are packaged in the javax.servlet and javax.servlet.http packages. The Servlet Class Hierarchy The Servlet interface is the root interface of the servlet class hierarchy. The GenericServlet class of the Servlet API implements the Servlet interface. In addition to this, the GenericServlet class implements the ServletConfig interface of the Servlet API and the Serializable interface of the standard java.io package. The object of the ServletConfig interface is used to pass on the configuration information when a servlet is initialized. To develop a servlet that communicates using HTTP, you need to extend the HttpServlet class in your servlet. The HttpServlet class extends the GenericServlet class and provides built-in HTTP functionality.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

The javax.servlet.Servlet Interface The Servlet interface of the javax.servlet package defines methods that the web container calls to manage the servlet life cycle. The following are the various methods of this interface. 1. destroy (): Cleans up whatever resources are being held (e.g., memory, file handles, threads) and makes sure that any persistent state is synchronized with the servlet's current in-memory state. 2. getServletConfig (): Returns a servlet config object, which contains any initialization parameters and startup configuration for this servlet. 3. getServletInfo (): Returns a string containing information about the servlet, such as its author, version, and copyright. 4. init (ServletConfig): Initializes the servlet. 5. service (ServletRequest, ServletResponse): Carries out a single request from the client.

The javax.servlet.ServletConfig Interface A servlet configuration object used by a servlet container to pass information to a servlet during initialization. Initialization parameters are name value pairs that you can use to pass information to a servlet. For example, you can specify a JDBC URL as initialization parameter of the servlet.

1. getInitParameter (java.lang.String name): Returns a String containing the value of the named initialization parameter, or null if the parameter does not exist. 2. getInitParameterNames (): Returns the names of the servlet's initialization parameters as an Enumeration of String objects, or an empty Enumeration if the servlet has no initialization parameters. 3. getServletContext (): Returns a reference to the ServletContext in which the caller is executing. 4. getServletName (): Returns the name of this servlet instance.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

The Servlet Life Cycle Methods The web container invokes the init (), service () and destroy () methods of a servlet during its life cycle. The sequence in which the web container invokes them is as follows. 1. The Web container loads the servlet class and creates one or more instances of the servlet class 2. The Web container invokes the init () method of the servlet instance during initialization of the servlet. The init () method is invoked only once in the servlet life cycle. 3. The Web container invokes the service () method to allow a servlet to process a client request. 4. The service () method processes the request and returns the response back to the Web container. 5. The servlet then waits to receive and process subsequent requests as explained in steps 3 and 4. 6. The Web container calls the destroy () method before removing the servlet instance from the service. The destroy () method is also invoked only once in a servlet life cycle.

Note: The Web container calls the service () method, it passes an object of the ServletRequest (contains the request information from the client) interface and an object of the type ServletResponse (contains the information returned by the servlet to the client) interface. *** The service () method dispatches a client request to one of the request handler methods of the HttpServlet interface, such as doGet (), doPost (), etc. The request handler methods accept the objects of the HttpServletRequest and HttpServletResponse as parameters from the service () method.

The doGet () method The doGet () method processes client request, which is sent by the client, using the HTTP GET method. The data sent using the GET method is appended as a query string to the URL. You can specify the HTTP method type in an HTML form by using the METHOD attribute of the FORM tag.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

The doPost () method The doPost () method handles the requests in a servlet, which are sent by the client, using the HTTP POST method. Unlike the GET method, the POST request sends the data as part of the HTTP request body. As a result, the data sent does not appear as a part of the URL. The destroy () method The destroy () method marks the end of the life cycle of a servlet. The Web container calls the destroy () method when: 1. The time periods specified for the servlet has elapsed. 2. The Web container needs to release servlet instances to conserve memory. 3. The Web container is about to shut down.

How to run a Servlet using the NetBeans IDE For the procedure on how to install the NetBeans IDE, go through the pdf document Software Installation Guide for the Servlets Session. The following are the steps to create a Servlet using the NetBeans IDE.

Open the NetBeans 6.9.1 IDE, by double clicking on the shortcut icon which can be seen on the desktop after the installation. Then you should get a welcome screen like this.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Now click on the File New Project.

Now select Java Web Web Application. And click on Next.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

In the C: directory create a folder with the name C:\ Java Project. Click on Browse, select that folder and click on Open. Give the Project Name as Training Project.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Now click on the Next button. The following screen should be displayed.

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Make sure that the Server: Apache Tomcat 6.0.26 and Java EE Version: J2EE 1.4.

10

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Click on Next. The following screen should be displayed.

Now click on Finish. After clicking Finish you should get the following screen.

11

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

As we are not using JSP for this training, we are going to delete the JSP page which comes as a default view. For this right click on the index.jsp as highlighted below and select Delete. When asked for confirmation click on Yes.

After doing that, your IDE should look like this.

12

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Now we have to add a Servlet to this Project. For that Right Click on the Training Project New Servlet.

13

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

When Servlet is selected, the following window appears.

Now give the following values for the respective labels. Class Name: FirstServlet Package: com.cgi.training

14

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Now click on Next button.

15

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Note: The Servlet Name is the name given to this particular Servlet. And URL Pattern label corresponds to the pattern through which you want to invoke this particular Servlet in the web browser after deploying it.

And now click on Finish. The following screen should appear.

16

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Now Right Click on the Training Project New HTML.

17

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Give the HTML File Name: welcome

18

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

And click on Finish. The following screen should appear.

19

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

To the welcome.html add the following lines of code.


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>Welcome Page</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form method="GET" action="/TrainingProject/FirstServlet"> Name <input type="text" name="username" size="20"><br> City <input type="text" name="password" size="20"><br><br> <input type="submit" value="Submit" name="B1"> </form> </body> </html> Now Save it using File Save.

20

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Open FirstServlet.java and add the following code to the doGet (...) method. Here we are adding this code to the doGet (...) method, because in the HTML we are using the method attribute as GET.

String name= request.getParameter("username"); String city= request.getParameter("city"); PrintWriter out = response.getWriter(); out.println("Welcome to Hyderabad "+name+" from "+city+ "."); After adding the above code, the code window should look like this.

21

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

And finally save the FirstServlet.java file by pressing Ctrl+s.

Now open the web.xml file.

Double click on this

The screen as shown below should open.

22

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Now click on the XML button to open the XML View.

This one

23

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

The following screen should be seen.

Here we have to make only one change i.e. Change the <welcome-file>welcome.html</welcome-file>. And finally save the web.xml file by pressing Ctrl+s. After making this change the web.xml should like as shown below.

24

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Now we are ready to deploy this servlet. For that Right Click on the TrainingProject Run.

Select this

If everything is fine, we should get the following window.

25

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Enter Name: Lokesh (Anything can be entered over here) City: Tirupati (Anything can be entered over here)

26

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011 And click on Submit. If our servlet is compiled and deployed successfully, you should get the following output screen.

The overall process flow for this particular program is given in the following flow chart.

27

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Using Multiple Values for a Single Parameter The design part for this particular program will be as per the following flow chart. As

In this program we have used the checkbox which will have the same name but with different values. Now in the Servlet that is working like a controller will retrieve the vales we have entered in the html form by the method getParameterValues () which returns the array of String. The output will be displayed to you by the PrintWriter object. The following is the code for MultipleValues.html: <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>MultipleValues</title> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> </head> <body> <form method = "post" action = "/TrainingProject/SecondServlet"> <p>Which variety of Choclates do you like the most: <input type = "checkbox" name ="choclate" value = "5 Star">5 Star<br> <input type = "checkbox" name ="choclate" value = "Snickers">Snickers<br> <input type = "checkbox" name ="choclate" value = "Dairy Milk">Dairy Milk<br> <input type = "checkbox" name ="choclate" value = "Kit Kat">Kit Kat<br> <input type = "checkbox" name ="choclate" value = "Temptations">Temptations<br>

28

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011 <input type ="submit" name= "submit"> </form> </body> </html> Code for SecondServlet.java: Add this code inside the processRequest(...) method of this class. PrintWriter pw = response.getWriter(); String[] choclate= request.getParameterValues("choclate"); pw.println("Your favourite varities are:"); for(int i=0; i<choclate.length; i++) pw.println("<br>" + choclate[i]); Now save this and run the application. If it is successful you should get the following window, when you type the corresponding URL in the Internet Explorer.

And when clicked on Submit Query you should get the following output.

29

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Integrating Java Script with a Servlet The following is the process flow chart for this process. As you can see, validateForm() is a JavaScript function which makes sure that both of the fields are entered with some data. If not it will alert the user till some data is entered, then only the request is sent to the Servlet.

30

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

Code for JavaScriptValidation.html file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>JavaScriptValidation</title> <SCRIPT type="text/javascript" LANGUAGE="JavaScript"> function validateForm() { var x=document.forms["form1"]["username"].value var y=document.forms["form1"]["city"].value if (x==null || x=="" || y==null || y=="") { alert("None of the field can be left blank"); return false; } } </SCRIPT> </head> <body>

<form name="form1" action="/TrainingProject/FirstServlet" onsubmit="return validateForm()" method="get"> Name <input type="text" name="username" size="20"><br> City <input type="text" name="city" size="20"><br><br> <input type="submit" value="Submit"> </form>

</body> </html> Note: Here we are using the same FirstServlet.java file, so no need to develop any servlet for this example.

31

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

INTER SERVLET COMMUNICATION RequestDispatcher: Defines an object that receives requests from the client and sends them to any resource (such as a Servlet, HTML file, or JSP file) on the server. The Servlet container creates the RequestDispatcher object, which is used as a wrapper around a server resource located at a particular path or given by a particular name. void forward (ServletRequest request, ServletResponse response): Forwards a request from a Servlet to another resource (Servlet, JSP file, or HTML file) on the server. void include (ServletRequest request, ServletResponse response): Includes the content of a resource (Servlet, JSP page, HTML file) in the response.

sendRedirect: Sends a temporary redirect response to the client using the specified redirect location URL. This method can accept relative URLs; the Servlet container must convert the relative URL to an absolute URL before sending the response to the client. If the location is relative without a leading '/' the container interprets it as relative to the current request URI. If the location is relative with a leading '/' the container interprets it as relative to the Servlet container root.

What is the difference between Request Dispatchers forward (ServletRequest request, ServletResponse response) method and HttpServletResponse's sendRedirect (String location) method? Answer: The forward method of RequestDispatcher will forward the ServletRequest and ServletResponse that it is passed to the path that was specified in getRequestDispatcher(String path). The response will not be sent back to the client and so the client will not know about this change of resource on the server. This method is useful for communicating between server resources, (servlet to servlet). Because the request and response are forwarded to another resource all request parameters are maintained and available for use. Since the client does not know about this forward on the server, no history of it will be stored on the client, so using the back and forward buttons will not work. This method is faster than using sendRedirect as no network round trip to the server and back is required.

32

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

Servlets Training Session, CGI, Hyderabad Date: 14 MAR 2011 15 MAR 2011

An example using forward: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { RequestDispatcher rd = request.getRequestDispatcher("pathToResource"); rd.forward(request, response); }

The sendRedirect(String path) method of HttpServletResponse will tell the client that it should send a request to the specified path. So the client will build a new request and submit it to the server, because a new request is being submitted all previous parameters stored in the request will be unavailable. The client's history will be updated so the forward and back buttons will work. This method is useful for redirecting to pages on other servers and domains. An example using sendRedirect: protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.sendRedirect("pathToResource"); }

33

By: Lokesh Kumar (Email: Lokesh.merugupala@cgi.com)

You might also like