Web Tech Java Servlet Update1


Published on

Published in: Technology
  • great
    Are you sure you want to  Yes  No
    Your message goes here
  • sir ye download hi nhi ho raha h link se
    koi aur format h kya download karne ka
    Are you sure you want to  Yes  No
    Your message goes here
  • innovative & remakable step in sharing & imparting knowledge among students thanks from it branch!!!
    Are you sure you want to  Yes  No
    Your message goes here
No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Web Tech Java Servlet Update1

  1. 1. An Introduction to Java Web Technology (Java Servlet) Presented At: JECRC, Faculty of E&T, Jodhpur National University, Jodhpur, Rajasthan India -342001
  2. 2. HTTP <ul><li>HTTP stands for HyperText Transport Protocol, and is the network protocol used over the web. It runs over TCP/IP. </li></ul><ul><li>HTTP uses a request/response model.Client sends an HTTP request, then the server gives back the HTTP response that the browser will display (depending on the content type of the answer). </li></ul><ul><li>If the response is an HTML file, then the HTML file is added to the HTTP response body. </li></ul><ul><li>An HTTP response includes : status code, the content-type (MIME type), and actual content of the response. </li></ul><ul><li>A MIME type tells the browser what kind of data the response is holding. </li></ul><ul><li>URL stands for Uniform Resource Locator: starts with a protocol, then a server name, optionally followed by a port number, then the path to the resource followed by the resource name. Parameters may appear at the end, separated from the rest by a ? . </li></ul>
  3. 3. HTTP METHODS Uploads a representation of the specified resource. PUT Converts the request connection to a transparent TCP/IP tunnel, usually to facilitate SSL-encrypted communication (HTTPS) through an unencrypted HTTP proxy. [3] CONNECT Returns the HTTP methods that the server supports for specified URL. This can be used to check the functionality of a web server by requesting '*' instead of a specific resource. OPTIONS Echoes back the received request, so that a client can see what intermediate servers are adding or changing in the request. TRACE Deletes the specified resource. DELETE Submits data to be processed (e.g., from an HTML form) to the identified resource. The data is included in the body of the request. POST means retrieve whatever data is identified by the URI GET Asks for the response identical to the one that would correspond to a GET request, but without the response body. This is useful for retrieving meta-information written in response headers, without having to transport the entire content. HEAD DESCRIPTION METHOD
  4. 4. HTTP METHODS HTTP servers are required to implement at least the GET and HEAD methods [4] and, whenever possible, also the OPTIONS method Safe methods Some methods (for example, HEAD, GET, OPTIONS and TRACE) are defined as safe , which means they are intended only for information retrieval and should not change the state of the server. Idempotent methods Some http methods are defined to be idempotent, meaning that multiple identical requests should have the same effect as a single request. Methods PUT, DELETE, GET, HEAD, OPTIONS and TRACE, being prescribed as safe, should also be idempotent. HTTP is a stateless protocol. By contrast, the POST method is not necessarily idempotent, and therefore sending an identical POST request multiple times may further affect state or cause further side effects.(like updating inserting records in database multiple times).
  5. 5. DIFFERENCE BETWEEN GET AND POST <ul><li>GET : </li></ul><ul><li>GET parameters are passed on the URL line, after a ? . The URL size is limited. </li></ul><ul><li>The parameters appear in the browser URL field, hence showing any password to the world... </li></ul><ul><li>GET is supposed to be used to GET things (only retrieval, no modification on the server). </li></ul><ul><li>GET processing must be idempotent. </li></ul><ul><li>A click on a hyperlink always sends a GET request. </li></ul><ul><li>GET is the default method used by HTML forms. Use the method=”POST” to change it. </li></ul><ul><li>POST : </li></ul><ul><li>POST has a body. </li></ul><ul><li>In POST requests, the parameters are passed in the body of the request, after the header. There is no size-limit. Parameters are not visible from the user. </li></ul><ul><li>POST is supposed to be used to send data to be processed. </li></ul><ul><li>POST may not be idempotent and is the only one . </li></ul><ul><li>IDEMPOTENT : Can do the same thing over and over again, with no negative side effect. </li></ul>
  6. 6. WHAT IS WEB CONTAINER? <ul><li>A Web application runs within a Web container of a Web server. The Web container provides the runtime environment through components that provide naming context and life cycle management. Some Web servers may also provide additional services such as security and concurrency control. </li></ul><ul><li>Web applications are composed of web components and other data such as HTML pages. Web components can be servlets, JSP pages created with the JavaServer Pages™ technology, web filters, and web event listeners. These components typically execute in a web server and may respond to HTTP requests from web clients. Servlets, JSP pages, and filters may be used to generate HTML pages that are an application’s user interface. </li></ul>
  7. 7. WHAT IS JAVA SERVLET? <ul><li>Servlets are Java classes that process the request dynamically and generate response independent of the protocol. Servlets are defined in Java Servlet API specification. Latest Servlet API specification available is 2.5. </li></ul><ul><li>Servlets are server side Java programs which extends the functionality of web server. Servlet are protocol independent that means it can be used virtually with any protocol to process the request and generate the response. However in practice Servlets are used to process the HTTP requests and generate the HTML response. </li></ul>
  8. 8. STRUCTURE OF A WEB APPLICATION <ul><li>Web Applications use a standard directory structure defined in the Servlet specification. When developing web applications on J2EE platform, you must follow this structure so that application can be deployed in any J2EE compliant web server. </li></ul><ul><li>A web application has the directory structure as shown in figure. </li></ul><ul><li>The root directory of the application is called the document root. Root directory is mapped to the context path. </li></ul><ul><li>Root directory contains a directory named WEB-INF. Anything under the root directory excepting the WEB-INF directory is publically available, and can be accessed by URL from browser. </li></ul><ul><li>WEB-INF directory is a private area of the web application, any files under WEB-INF directory cannot be accessed directly from browser by specifying the URL like http://somesite/WEB-INF/someresource.html. Web container will not serve the content of this directory. However the content of the WEB-INF directory is accessible by the classes within the application. </li></ul>
  9. 9. WEB-INF DIRECTORY <ul><li>WEB-INF directory contains </li></ul><ul><li>WEB-INF/web.xml deployment descriptor </li></ul><ul><li>WEB-INF/classes directory </li></ul><ul><li>WEB-INF/lib directory </li></ul><ul><li>CLASSES- directory is used to store compiled servlet and other classes of the application. </li></ul><ul><li>LIB - directory is used to store the jar files. If application has any bundled jar files, or if application uses any third party libraries such as log4j which is packaged in jar file, than these jar files should be placed in lib directory. </li></ul><ul><li>All unpacked classes and resources in the /WEB-INF/classes directory, plus classes and resources in JAR files under the /WEB-INF/lib directory, are made visible to the containing web application. </li></ul>
  10. 10. SERVLET LIFE CYCLE <ul><li>Servlets are managed components. They are managed by web container. Of the various responsibilities of web container, servlet life cycle management is the most important one. </li></ul><ul><li>A servlet is managed through a well defined life cycle that defines how it is loaded, instantiated ad initialized, handles requests from clients and how it is taken out of service. </li></ul><ul><li>The servlet life cycle methods are defined in the javax.servlet.Servlet interface of the Servlet API that all Servlets must implement directly or indirectly by extending GenericServlet or HttpServlet abstract classes. Most of the servlet you develop will implement it by extending HttpServlet class. </li></ul><ul><li>The servlet life cycle methods defined in Servlet interface are init(), service() and destroy() . </li></ul><ul><li>The signature of this methods are shown below. </li></ul><ul><li>public void init (ServletConfig config) throws ServletException </li></ul><ul><li>public void service (ServletRequest req, ServletResponse res) throws ServletException, IOException </li></ul><ul><li>public void destroy () </li></ul>
  12. 12. SERVLET LIFE CYCLE - STEPS <ul><li>The servlet life cycle consists of four steps, instantiation, initialization, request handling and end of service. </li></ul><ul><li>Loading and instantiation </li></ul><ul><li>During this step, web container loads the servlet class and creates a new instance of the servlet. The container can create a servlet instance at container startup or it can delay it until the servlet is needed to service a request. </li></ul><ul><li>Initialization </li></ul><ul><li>During initialization stage of the Servlet life cycle, the web container initializes the servlet instance by calling the init() method. The container passes an object implementing the ServletConfig interface via the init() method. This configuration object allows the servlet to access name-value initialization parameters from the web application’s deployment descriptor (web.xml) file. The container guarantees that the init() method will be called before the service() method is called. </li></ul><ul><li>The init() method is typically used to perform servlet initialization, creating or loading objects that are used by the servlet in the handling of its requests. </li></ul><ul><li>The init() method is commonly used to perform one time activity. One of the most common use of init() method is to setup the database connection or connection pool. </li></ul>
  13. 13. SERVLET LIFE CYCLE - STEPS <ul><li>Request handling </li></ul><ul><li>After a servlet is properly initialized, it is ready to handle the client requests. If the container has a request for the servlet, it calls the servlet instance’s service() method. The request and response information is wrapped in ServletRequest and ServletResponse objects respectively, which are then passed to the servlet's service() method. In the case of an HTTP request, the objects provided by the container are of types HttpServletRequest and HttpServletResponse. </li></ul><ul><li>Service() method is responsible for processing the incoming requests and generating the response. </li></ul><ul><li>End of service </li></ul><ul><li>When the servlet container determines that a servlet should be removed from service, it calls the destroy () method of the Servlet  instance to allow the servlet to release any resources it is using. The servlet container can destroy a servlet because it wants to conserve some memory or server itself is shutting down. </li></ul><ul><li>Destroy() method is used to release any resources it is using. The  most common use of destroy() method is to close the database connections. </li></ul>
  14. 14. SETTING UP SERVLET DEVELOPMENT ENVIRONMENT <ul><li>List of required softwares: </li></ul><ul><li>JAVA 1.5 or 1.6 </li></ul><ul><li>Tomcat 5.5.16 </li></ul><ul><li>First of all you need the Java software development kit 1.5 or 1.6 (JAVA SDK) installed. </li></ul><ul><li>Checking if JAVA is already installed in your system </li></ul>
  15. 15. SETTING UP SERVLET DEVELOPMENT ENVIRONMENT <ul><li>Set up the JAVA_HOME environment variable </li></ul><ul><li>Once the JAVA SDK is installed follow this step to set the JAVA_HOME environment variable. If JAVA_HOME variable is already set, you can skip this step. </li></ul>
  17. 17. SETTING UP SERVLET DEVELOPMENT ENVIRONMENT In the variable name filed, enter JAVA_HOME. Specify the path to root directory of JAVA installation in variable value field and click OK button. Now JAVA_HOME will appear under user variables. Next you need to add bin directory under the root directory of JAVA installation in PATH environment variable.Select the PATH variable from System variables and click on Edit button. Add: ;%JAVA_HOME%in; at the end of variable value field and click OK button.
  18. 18. INSTALLING TOMCAT Tomcat is an opensource web container. it is also web container reference implementation. Download the latest version of tomcat from this URL . Download the jakarta-tomcat-5.0.28.tar.gz and extract it to the directory of your choice. Note: This directory is referred as TOMCAT_HOME in other tutorials. That’s all, tomcat is installed. Starting and shutting down Tomcat To start the tomcat server, open the command prompt, change the directory to TOMCAT HOME/bin and run the startup.bat file. It will start the server. >startup To shut down the tomcat server, run the shutdown.bat file. It will stop the server. >shutdown Verifying Tomcat installation To verify that tomcat is installed properly, start the server as explained above, open the web browser and access the following URL. http://localhost:8080/index.jsp It should show the tomcat welcome page, if tomcat is installed properly and server is running.
  19. 19. INSTALLING TOMCAT Setting up the CLASSPATH Now you need to create a new environment variable CLASSPATH if it is not already set. We need to add the servlet-api.jar into the CLASSPATH to compile the Servlets. Follow the same steps as you did to create the JAVA_HOME variable. Create a new variable CLASSPATH under system variables. Add TOMCAT_HOME/lib/servlet-api.jar in variable value field. Note: here TOMCAT_HOME refers to the tomcat installation directory.
  20. 20. SERVLET API CLASSES AND INTERFACES <ul><li>Servlet API is specified in two packages: javax.servlet and javax.servlet.http . The classes and interfaces in javax.servlet are protocol independent, while the classes and interface in javax.servlet.http deals with specialized HTTP Servlets. </li></ul><ul><li>Some of the classes and interfaces in the javax.servlet.http package extend those specified in javax.servlet package. </li></ul><ul><li>The javax.servlet package </li></ul><ul><li>The javax.servlet package defines the contract between container and the servlet class. It provides the flexibility to container vendor to implement the API the way they want so long as they follow the specification. To the developers, it provides the library to develop the servlet based applications. </li></ul><ul><li>the javax.servlet Interfaces </li></ul><ul><li>The javax.servlet package is composed of 14 interfaces. </li></ul><ul><li>Servlet interface </li></ul><ul><li>The Servlet Interface is the central abstraction of the Java Servlet API. It defines the life cycle methods of a servlet. All the servlet implementations must implement it either directly or indirectly by extending a class which implements the Servlet interface. The two classes in the servlet API that implement the Servlet interface are GenericServlet and HttpServlet. For most purposes, developers will extend HttpServlet to implement their Servlets while implementing web applications employing the HTTP protocol. </li></ul>
  21. 21. SERVLET API CLASSES AND INTERFACES <ul><li>ServletRequest interface </li></ul><ul><li>ServletRequest interface provides an abstraction of client request.  </li></ul><ul><li>The object of ServletRequest is used to obtain the client request information such as request parameters, content type and length, locale of the client, request protocol etc. </li></ul><ul><li>Developers don’t need to implement this interface. The web container provides the implementation this interface.  The web container creates an instance of the implementation class and passes it as an argument when calling the service() method. </li></ul><ul><li>ServletResponse interface </li></ul><ul><li>The ServletResponse interface assists a servlet in sending a response to the client. </li></ul><ul><li>Developers don’t need to implement this interface. Servlet container creates the ServletResponse object and passes it as an argument to the servlet’s service() method. </li></ul>
  22. 22. SERVLET API CLASSES AND INTERFACES <ul><li>ServletConfig interface </li></ul><ul><li>The servlet container uses a ServletConfig object to pass initialization information to the servlet. </li></ul><ul><li>ServletConfig object is most commonly used to read the initialization parameters. </li></ul><ul><li>Servlet intialialization parameters are specified in deployment descriptor (web.xml) file. </li></ul><ul><li>Servlet container passes the ServletConfig object as an argument when calling servlet’s init() method. </li></ul><ul><li>ServletContext interface </li></ul><ul><li>ServletContext object is used to communicate with the servlet container. </li></ul><ul><li>There is only one ServletContext object per web application (per JVM). </li></ul><ul><li>This is initialized when the web application is started and destroyed only when the web application is being shutdown. </li></ul><ul><li>ServletContext object is most commonly used to obtain the MIME type of a file, dispatching a request, writing to server’s log file, share the data across application, obtain URL references to resources etc </li></ul>
  23. 23. SERVLET API CLASSES AND INTERFACES <ul><li>SingleThreadModel Interface </li></ul><ul><li>SingleThreadModel is a marker interface. It is used to ensure that servlet handle only one request at a time. </li></ul><ul><li>Servlets can implement SingleThreadModel interface to inform the container that it should make sure that only one thread is executing the servlet’s service() method at any given moment. </li></ul><ul><li>RequestDispatcher Interface </li></ul><ul><li>The RequestDispatcher interface is used to dispatch requests to other resources such a servlet, HTML file or a JSP file. </li></ul><ul><li>Filter Interface </li></ul><ul><li>Filter interface declares life cycle methods of a filter. The life cycle methods include, init() doFilter() and destroy(). </li></ul><ul><li>FilterChain Interface </li></ul><ul><li>The FilterChain object provides the filter with a handle to invoke the rest of the filter chain. Each filter gets access to a FilterChain object when its doFilter() method is invoked. Using this object, the filter can invoke the next filter in the chain. </li></ul>
  24. 24. SERVLET API CLASSES AND INTERFACES <ul><li>FilterConfig interface </li></ul><ul><li>The FilterConfig interface is similar to ServletConfig interface. It is used to get the initialization parameters. </li></ul><ul><li>ServletContextAttributeListner </li></ul><ul><li>Implementation of this interface receives notification whenever an attribute is added, removed or replaced in ServletContext. To receive the notifications, the implementation class must be configured in the deployment descriptor (web.xml file). </li></ul><ul><li>ServletContextListner Interface </li></ul><ul><li>Implementation of this interface receives notification when the context is created and destroyed. </li></ul><ul><li>ServletRequestAttributeListner Interface </li></ul><ul><li>Implementation of this interface receives notification whenever an attribute is added, removed or replaced in ServletRequest. </li></ul><ul><li>ServletRequestListner Interface </li></ul><ul><li>Implementation of this interface receives notification whenever the request is coming in and out of scope. A request is defined as coming into scope when it is about to enter the first servlet or filter in each web application, as going out of scope when it exits the last servlet or the first filter in the chain. </li></ul>
  25. 25. SERVLET API CLASSES AND INTERFACES <ul><li>The javax.servlet Classes </li></ul><ul><li>The javax.servlet package contains 9 classes. </li></ul><ul><li>GenericServlet class </li></ul><ul><li>The GenericServlet abstract class defines the generic protocol independent servlet. It can be extended to develop our own protocol-based servlet. </li></ul><ul><li>ServletContextEvent class </li></ul><ul><li>This is the event class for notifications about changes to the servlet context of a web application. </li></ul><ul><li>ServletInputStream class </li></ul><ul><li>Provides an input stream for reading binary data from a client request. </li></ul><ul><li>ServletOutputStream class </li></ul><ul><li>Provides an output stream for sending binary data to the client. </li></ul><ul><li>javax.servlet Exception classes </li></ul><ul><li>The javax.servlet package defines 2 exception classes. </li></ul><ul><li>ServletException class </li></ul><ul><li>Defines a general exception a servlet can throw when it encounters difficulty. </li></ul><ul><li>UnavailableException class </li></ul><ul><li>Defines an exception that a servlet or filter throws to indicate that it is permanently or temporarily unavailable. </li></ul>
  26. 26. Understanding the GenericServlet class <ul><li>GenericServlet class defines a generic protocol independent servlet.  It is protocol independent in the sense it can be extended to provide implementation of any protocol like FTP, SMTP etc.  </li></ul><ul><li>Servlet API comes with HttpServlet class which implements HTTP protocol.  </li></ul><ul><li>Generally when developing web application, you will never need to write a servlet that extends GenericServlet. Most of the Servlets in your application will extend HttpServlet class to handle web requests. </li></ul><ul><li>GenericServlet class provides implementation of Servlet Interface. This is an abstract class, all the subclasses must implement service () method. </li></ul><ul><li>Public abstract class GenericServlet implements Servlet,ServletConfig,Serializable </li></ul><ul><li>In addition to those methods defined in Servlet Interface, GenericServlet defines following additional methods. </li></ul><ul><li>Public void init () Public void log (String message ) Public void log (String message , Throwable t ) </li></ul>
  27. 27. Understanding the GenericServlet class <ul><li>Initializing the Servlet </li></ul><ul><li>Public void init( ServletConfig config ) Public void init () </li></ul><ul><li>Public void init(ServletConfig config) method is an implementation of init(ServletConfig config) method defined in Servlet interface, it stores the ServletConfig object in private transient instance variable.  </li></ul><ul><li>getServletConfig() method can be used to get the reference of this object. If you override  this method, you should include a class to super.init(config) method. Alternatively, you can override no-argument init() method. </li></ul><ul><li>Handling requests </li></ul><ul><li>Public abstract void service (ServletRequest request , ServletResponse response ) </li></ul><ul><li>This is an abstract method, and you must override this method in your subclass to handle requests. All the code related to request processing and response generation goes here. </li></ul><ul><li>Destroying the Servlet </li></ul><ul><li>Public void destroy () </li></ul><ul><li>This method provides default implementation of destroy () method defined in the Servlet interface. You can override this method in your subclasses to do some cleanup tasks when servlet is taken out of service. </li></ul>
  28. 28. Understanding the GenericServlet class <ul><li>Accessing the environment </li></ul><ul><li>GenericServlet class also implements ServletConfig interface so all the methods of ServletConfig interface can be called directly without first obtaining reference to ServletConfig instance. </li></ul><ul><li>Public   String getInitParameter (String name ) : used to obtaing value of servlet initialization parameter. </li></ul><ul><li>public String getInitParameterNames () : returns names of all initialization parameters. </li></ul><ul><li>Public ServletContext  getServletContext () : returns reference to ServletContext object. </li></ul><ul><li>String getServletName () : used to obtain name of the servlet. </li></ul><ul><li>Writing to server log file </li></ul><ul><li>Public void log(String message ) Public void log(String message , Throwable t) </li></ul><ul><li>GenericServlet class provides two utility methods for writing to server log file. log(String message) method writes servlet name and message to web containers log file. the other method log(string message, Throwable t), writes servlet name, string message and the exception stack trace of the given Throwable exception to web containers log file. </li></ul>
  29. 29. GenericServlet Example <ul><li>import java.io.IOException; </li></ul><ul><li>import java.io.PrintWriter; </li></ul><ul><li>import javax.servlet.GenericServlet; </li></ul><ul><li>import javax.servlet.ServletException; </li></ul><ul><li>import javax.servlet.ServletRequest; </li></ul><ul><li>import javax.servlet.ServletResponse; </li></ul><ul><li>public class GenericServletExample extends GenericServlet { </li></ul><ul><li>public void init () { log ( &quot;inside init() method&quot; ); } </li></ul><ul><li>public void service(ServletRequest request , ServletResponse response ) throws ServletException, IOException { log ( &quot;Handling request&quot; ); response. setContentType ( &quot;text/html&quot; ); PrintWriter out = response. getWriter (); out. write ( &quot;<html><head><title>GenericServle example</title></head>&quot; ); out. write ( &quot;<body><h1>GenericServlet: Hallo world </h1></body></html>&quot; ); out. close (); </li></ul><ul><li>} </li></ul>
  30. 30. GenericServlet Example <ul><li>public void destroy () { log( &quot;inside destroy() method&quot; ); } </li></ul><ul><li>} </li></ul><ul><li>-------------------------------------------------------------------------- </li></ul><ul><li>Web.xml deployment descriptor </li></ul><ul><li><?xml version =&quot;1.0&quot; encoding =&quot;ISO-8859-1&quot;?> </li></ul><ul><li><web-app xmlns =&quot;http://java.sun.com/xml/ns/javaee&quot; xmlns:xsi =&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation =&quot;http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd&quot; version =&quot;2.5&quot;> <servlet> <servlet-name>GenericServlet</servlet-name> <servlet-class>com.jsptube.servlet.GenericServletExample</servlet-class> </servlet> <servlet-mapping> <servlet-name>GenericServlet</servlet-name> <url-pattern>/exampleservlet</url-pattern> </servlet-mapping> </web-app> </li></ul>
  31. 31. A VERY SIMPLE SERVLET EXAMPLE <ul><li>What is covered in this Servlet example </li></ul><ul><li>How to write the servlet class. </li></ul><ul><li>How to compile the Servlet class. </li></ul><ul><li>How to extract the HTML form parameters from HttpServletRequest. </li></ul><ul><li>web.xml deployment descriptor file. </li></ul><ul><li>How to create the war (web application archive) file. </li></ul><ul><li>How to deploy and run the sample web application in tomcat web container. </li></ul><ul><li>This is a very simple web application containing a HTML file and a servlet. The HTML document has a form which allows the user to enter the name, when the form is submitted application displays the welcome message to the user. </li></ul>
  32. 32. A VERY SIMPLE SERVLET EXAMPLE <ul><li>Create the HTML file. </li></ul><ul><li>Copy the following code into form.html file and save it under servlet-example/pages directory. </li></ul><ul><li><html> <head> <title>The servlet example </title> </head> <body> <h1>A simple web application</h1> <form method =&quot;POST&quot; action =&quot;/WelcomeServlet&quot;> <label for =&quot;name&quot;>Enter your name </label> <input type =&quot;text&quot; id =&quot;name&quot; name =&quot;name&quot;/><br><br> <input type =&quot;submit&quot; value =&quot;Submit Form&quot;/> <input type =&quot;reset&quot; value =&quot;Reset Form&quot;/> </form> </body> </li></ul><ul><li></html> </li></ul>
  33. 33. A VERY SIMPLE SERVLET EXAMPLE <ul><li>The welcome Servlet class </li></ul><ul><li>import java.io.IOException; import java.io.PrintWriter; import javax.servlet.ServletConfig; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class WelcomeServlet extends HttpServlet { @Override public void init (ServletConfig config) throws ServletException { super .ini t(config); } </li></ul><ul><li>protected void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* Get the value of form parameter */ String name = request. getParameter (&quot;name&quot;); String welcomeMessage = &quot;Welcome &quot;+name; /* Set the content type(MIME Type) of the response.*/ response. setContentType (&quot;text/html&quot;); PrintWriter out = response. getWriter (); </li></ul>
  34. 34. A VERY SIMPLE SERVLET EXAMPLE <ul><li>/* * Write the HTML to the response */ out. println (&quot;<html>&quot;); out. println (&quot;<head>&quot;); out. println (&quot;<title> A very simple servlet example</title>&quot;); out. println (&quot;</head>&quot;); out. println (&quot;<body>&quot;); out. println (&quot;<h1>&quot;+welcomeMessage+&quot;</h1>&quot;); out. println (&quot;<a href=&quot;/servletexample/pages/form.html&quot;>&quot;+&quot;Click here to go back to input page &quot;+&quot;</a>&quot;); out. println (&quot;</body>&quot;); out. println (&quot;</html>&quot;); out. close (); </li></ul><ul><li>} public void destroy () { } </li></ul><ul><li>} </li></ul><ul><li>Compile the WelcomeServlet.java using the following command. </li></ul><ul><li>>javac WelcomeServlet.java </li></ul><ul><li>It will create the file WelcomeServlet.class in the same directory. Copy the class file to classes directory. All the Servlets and other classes used in a web application must be kept under WEB-INF/classes directory. </li></ul><ul><li>Note:  to compile a servlet you need to have servlet-api.jar file in the class path. </li></ul>
  35. 35. A VERY SIMPLE SERVLET EXAMPLE <ul><li>The deployment descriptor (web.xml) file. </li></ul><ul><li>Copy the following code into web.xml file and save it directly under servlet-example/WEB-INF directory. </li></ul><ul><li><web-app version=&quot;2.4&quot; xmlns =&quot;http://java.sun.com/xml/ns/j2ee&quot; xmlns:xsi =&quot;http://www.w3.org/2001/XMLSchema-instance&quot; xsi:schemaLocation =&quot;http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd&quot;> <servlet> <servlet-name>WelcomeServlet</servlet-name> <servlet-class>jsptube.tutorials.servletexample.WelcomeServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>WelcomeServlet</servlet-name> <url-pattern>/WelcomeServlet</url-pattern> </servlet-mapping> <welcome-file-list> <welcome-file> /pages/form.html </welcome-file> </welcome-file-list> </li></ul><ul><li></web-app> </li></ul>
  36. 36. A VERY SIMPLE SERVLET EXAMPLE <ul><li>Create the WAR (Web application archive) file. </li></ul><ul><li>Web applications are packaged into a WAR (web application archive). There are many different ways to create a WAR file. You can use jar command, ant or an IDE like Eclipse. This tutorial explains how to create the WAR file using jar tool. </li></ul><ul><li>Open the command prompt and change the directory to the servlet-example directory, and execute the following command. </li></ul><ul><li>>jar cvf servletexample.war * </li></ul><ul><li>This command packs all the contents under servlet-example directory, including subdirectories, into an archive file called servletexample.war. We used following command-line options: </li></ul><ul><li>-c option to create new WAR file. </li></ul><ul><li>-v option to generate verbose output. </li></ul><ul><li>-f option to specify target WAR file name. </li></ul><ul><li>You can use following command to view the content of servletexample.war file. </li></ul><ul><li>>Jar –tvf servletexample.war. </li></ul><ul><li>This command lists the content of the WAR file. </li></ul>
  37. 37. A VERY SIMPLE SERVLET EXAMPLE <ul><li>Deploying the application to tomcat web container. </li></ul><ul><li>Deployment steps are different for different J2EE servers. This tutorial explains how to deploy the sample web application to tomcat web container. If you are using any other J2EE server, consult the documentation of the server. </li></ul><ul><li>A web application can be deployed in tomcat server simply by copying the war file to <TOMCAT_HOME>/webapp directory. Copy servletexample.war to <TOMCAT_HOME>/webapp directory.  That’s it! You have successfully deployed the application to tomcat web server. Once you start the server, tomcat will extract the war file into the directory with the same name as the war file. </li></ul><ul><li>To start the server, open the command prompt and change the directory to <TOMCAT_HOME/bin> directory and run the startup.bat file. </li></ul><ul><li>Our sample application can be accessed at http://localhost:8080/servletexample/. If tomcat server is running on port other than 8080 than you need to change the URL accordingly. </li></ul><ul><li>If the application has been deployed properly, you should see the screen similar to below when you open the application in browser. </li></ul>
  40. 40. A VERY SIMPLE SERVLET EXAMPLE <ul><li>How the application works. </li></ul><ul><li>When you access the application by navigating to URL http://localhost:8080/servletexample/ </li></ul><ul><li>the web server serves the form.html file. </li></ul><ul><li>“ pagesform.html” file is specified as welcome file in web.xml file so web server serves this file by default. </li></ul><ul><li>When you fill the form field and click on submit form button, browser sends the HTTP POST request with name parameter. </li></ul><ul><li>Based on the servlet mapping in web.xml, the web container delegates the request to WelcomeServlet class. </li></ul><ul><li>When the request is received by WelcomeServlet it performs following tasks. </li></ul><ul><li>Extract the name parameter from HttpServletRequest object. </li></ul><ul><li>Generate the welcome message. </li></ul><ul><li>Generate the HTML document and write the response to HttpServletResponse object. </li></ul><ul><li>Browser receives the HTML document as response and displays in browser window. </li></ul><ul><li>The next step is to understand the code. </li></ul>
  41. 41. Handling Form Data using Java Servlet
  42. 42. ADVANTAGES OF JAVA SERVLET <ul><li>Portability </li></ul><ul><li>Powerful </li></ul><ul><li>Efficiency </li></ul><ul><li>Safety </li></ul><ul><li>Integration </li></ul><ul><li>Extensibilty </li></ul><ul><li>Inexpensive </li></ul>
  43. 43. ADVANTAGES OF JAVA SERVLET OVER CGI <ul><li>Platform Independence Servlets are written entirely in java so these are platform independent. Servlets can run on any Servlet enabled web server. For example if you develop an web application in windows machine running Java web server , you can easily run the same on apache web server (if Apache Serve is installed) without modification or compilation of code. Platform independency of servlets provide a great advantages over alternatives of servlets. </li></ul><ul><li>Performance Due to interpreted nature of java, programs written in java are slow. But the java servlets runs very fast. These are due to the way servlets run on web server. For any program initialization takes significant amount of time. But in case of servlets initialization takes place first time it receives a request and remains in memory till times out or server shut downs. After servlet is loaded, to handle a new request it simply creates a new thread and runs service method of servlet. In comparison to traditional CGI scripts which creates a new process to serve the request.  </li></ul><ul><li>Extensibility Java Servlets are developed in java which is robust, well-designed and object oriented language which can be extended or polymorphed into new objects. So the java servlets take all these advantages and can be extended from existing class to provide the ideal solutions. </li></ul><ul><li>Safety Java provides very good safety features like memory management, exception handling etc. Servlets inherits all these features and emerged as a very powerful web server extension. </li></ul><ul><li>Secure Servlets are server side components, so it inherits the security provided by the web server. Servlets are also benefited with Java Security Manager. </li></ul>
  44. 44. INTRO TO SERVER SIDE PROGRAMMING <ul><li>Advantages of Server Side Programs </li></ul><ul><li>All programs reside in one machine called the Server. Any number of remote machines (called clients) can access the server programs. </li></ul><ul><li>New functionalities to existing programs can be added at the server side which the clients’ can advantage without having to change anything from their side. </li></ul><ul><li>Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about clients’ hardware or software capabilities. </li></ul><ul><li>Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by service side applications. </li></ul><ul><li>They are portable and possess the capability to generate dynamic and user-based content (e.g. displaying transaction information of credit card or debit card depending on user’s choice). </li></ul>
  45. 45. INTRO TO SERVER SIDE PROGRAMMING <ul><li>Types of Server Side Programs </li></ul><ul><li>Active Server Pages (ASP) </li></ul><ul><li>Java Servlets </li></ul><ul><li>Java Server Pages (JSPs) </li></ul><ul><li>Enterprise Java Beans (EJBs) </li></ul><ul><li>PHP </li></ul><ul><li>To summarize, the objective of server side programs is to centrally manage all programs relating to a particular application (e.g. Banking, Insurance, e-shopping, etc). Clients with bare minimum requirement (e.g. Pentium II, Windows XP Professional, MS Internet Explorer and an internet connection) can experience the power and performance of a Server (e.g. IBM Mainframe, Unix Server , etc) from a remote location without having to compromise on security or speed. More importantly, server programs are not only portable but also possess the capability to generate dynamic responses based on user’s request.   </li></ul>
  46. 46. WRITING SIMPLE HELLOWORLD SERVLET import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  HelloWorld  extends  HttpServlet{     public void  doGet(HttpServletRequest request, HttpServletResponse response)                                    throws  ServletException,IOException{     response.setContentType(&quot;text/html&quot;);     PrintWriter pw = response.getWriter();     pw.println(&quot;<html>&quot;);     pw.println(&quot;<head><title>Hello World</title></title>&quot;);     pw.println(&quot;<body>&quot;);     pw.println(&quot;<h1>Hello World</h1>&quot;);     pw.println(&quot;</body></html>&quot;);   } }
  47. 47. WRITING SIMPLE HELLOWORLD SERVLET web.xml file for this program: <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> <!--<!DOCTYPE web-app  PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&quot;  &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;> --> <web-app>  <servlet>    <servlet-name>Hello</servlet-name>   <servlet- class >HelloWorld</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Hello</servlet-name>  <url-pattern>/HelloWorld</url-pattern>  </servlet-mapping> </web-app>
  49. 49. WRITING SIMPLE DISPLAYINGDATE SERVLET import  java.io.*; import  java.util.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  DisplayingDate  extends  HttpServlet{      public void  doGet(HttpServletRequest request, HttpServletResponse                     response)  throws  ServletException, IOException{      PrintWriter pw = response.getWriter();      Date today =  new  Date();      pw.println( &quot;<html>&quot; + &quot;<body><h1>Today Date is</h1>&quot; );      pw.println( &quot;<b>&quot; + today+ &quot;</b></body>&quot; +  &quot;</html>&quot; );    } }
  50. 50. WRITING SIMPLE DISPLAYINGDATE SERVLET <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> <!--<!DOCTYPE web-app  PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&quot;  &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;> --> <web-app>  <servlet>   <servlet-name>Hello</servlet-name>   <servlet- class >DateDisplay</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Hello</servlet-name>  <url-pattern>/DateDisplay</url-pattern>  </servlet-mapping> </web-app>
  53. 53. SIMPLE COUNTING IN SERVLET import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  SimpleCounter  extends  HttpServlet{    int  counter = 0;    public void  doGet(HttpServletRequest request, HttpServletResponse response)                          throws  ServletException, IOException {     response.setContentType(&quot;text/html&quot;);     PrintWriter pw = response.getWriter();     counter++;     pw.println(&quot;At present the value of the counter is &quot; + counter);   } }
  54. 54. GETTING SERVER INFORMATION import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  SnoopingServerServlet  extends  HttpServlet{    protected void  doGet(HttpServletRequest request, HttpServletResponse response)                                    throws  ServletException, IOException {     PrintWriter pw = response.getWriter();     pw.println(&quot;The server name is &quot; + request.getServerName() + &quot;<br>&quot;);     pw.println(&quot;The server port number is &quot; + request.getServerPort()+ &quot;<br>&quot;);     pw.println(&quot;The protocol is &quot; + request.getProtocol()+ &quot;<br>&quot;);     pw.println(&quot;The scheme used is &quot; + request.getScheme());   } }
  55. 55. GETTING HEADER INFORMATION import  java.io.*; import  java.util.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  HeaderServlet  extends  HttpServlet{    protected void  doGet(HttpServletRequest request, HttpServletResponse response)                                 throws  ServletException, IOException {     PrintWriter pw = response.getWriter();     pw.println(&quot;Request Headers are&quot;);     Enumeration enumeration = request.getHeaderNames();      while (enumeration.hasMoreElements()){       String headerName = (String)enumeration.nextElement();       Enumeration headerValues = request.getHeaders(headerName);        if  (headerValues !=  null ){          while  (headerValues.hasMoreElements()){           String values = (String) headerValues.nextElement();           pw.println(headerName + &quot;: &quot; + values);         }       }     }   } }
  57. 57. READING INITIALIZATION PARAMETER In this example we are going to retreive the init paramater values which we have given in the web.xml file. Whenever the container makes a servlet it always reads it deployment descriptor file i.e. web.xml. Container creates name/value pairs for the ServletConfig object.  Once the parameters are in ServletConfig they will never be read again by the Container. The main job of the ServletConfig object is to give the init parameters.
  58. 58. READING INITIALIZATION PARAMETER import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; import  java.util.*; public class  InitServlet  extends  HttpServlet {    public void  doGet(HttpServletRequest request, HttpServletResponse response)                                   throws  ServletException, IOException {     PrintWriter pw = response.getWriter();     pw.print(&quot;Init Parameters are : &quot;);     Enumeration enumeration = getServletConfig().getInitParameterNames();      while (enumeration.hasMoreElements()){       pw.print(enumeration.nextElement() + &quot; &quot;);       }     pw.println(&quot; The email address is &quot; + getServletConfig().getInitParameter(&quot;AdminEmail&quot;));     pw.println(&quot;The address is &quot; + getServletConfig().getInitParameter(&quot;Address&quot;));     pw.println(&quot;The phone no is &quot; + getServletConfig().getInitParameter(&quot;PhoneNo&quot;));   } }
  59. 59. READING INITIALIZATION PARAMETER <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> <!DOCTYPE web-app  PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&quot;  &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;> <web-app><servlet>  <init-param> <param-name>AdminEmail</param-name>  <param-value>zulfiqar_mca@yahoo.co.in</param-value>  </init-param>  <init-param> <param-name>Address</param-name>  <param-value>Okhla</param-value>  </init-param>   <init-param> <param-name>PhoneNo</param-name>  <param-value>9911217074</param-value>  </init-param>    <servlet-name>Zulfiqar</servlet-name>   <servlet- class >InitServlet</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Zulfiqar</servlet-name>  <url-pattern>/InitServlet</url-pattern>  </servlet-mapping> </web-app>
  61. 61. PASSING PARAMETER USING HTML FORM <html> <head> <title>New Page 1</title> </head> <body> <h2>Login</h2> <p>Please enter your username and password</p> <form method=&quot;GET&quot; action=&quot;/htmlform/LoginServlet&quot;>   <p> Username  <input type=&quot;text&quot; name=&quot;username&quot; size=&quot;20&quot;></p>   <p> Password  <input type=&quot;text&quot; name=&quot;password&quot; size=&quot;20&quot;></p>   <p><input type=&quot;submit&quot; value=&quot;Submit&quot; name=&quot;B1&quot;></p> </form> <p>&nbsp;</p> </body> </html>
  62. 62. PASSING PARAMETER USING HTML FORM import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  LoginServlet  extends  HttpServlet{    public void  doGet(HttpServletRequest request, HttpServletResponse response)                                    throws  ServletException, IOException {     response.setContentType(&quot;text/html&quot;);     PrintWriter out = response.getWriter();     String name = request.getParameter(&quot;username&quot;);     String pass = request.getParameter(&quot;password&quot;);     out.println(&quot;<html>&quot;);     out.println(&quot;<body>&quot;);     out.println(&quot;Thanks  Mr.&quot; + &quot;  &quot; + name + &quot;  &quot; + &quot;for visiting roseindia<br>&quot; );     out.println(&quot;Now you can see your password : &quot; + &quot;  &quot; + pass + &quot;<br>&quot;);     out.println(&quot;</body></html>&quot;);   } }
  63. 63. PASSING PARAMETER USING HTML FORM <?xml version=&quot;1.0&quot; encoding=&quot;ISO-8859-1&quot;?> <!--<!DOCTYPE web-app  PUBLIC &quot;-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN&quot;  &quot;http://java.sun.com/dtd/web-app_2_3.dtd&quot;> --> <web-app>  <servlet>   <servlet-name>Hello</servlet-name>   <servlet- class >LoginServlet</servlet- class >  </servlet>  <servlet-mapping>  <servlet-name>Hello</servlet-name>  <url-pattern>/LoginServlet</url-pattern>  </servlet-mapping> </web-app>
  65. 65. MULTIPLE VALUES FOR A SINGLE PARAMETER <!DOCTYPE HTML PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot;> <html> <head> <title>Insert title here</title> </head> <body> <form method = &quot;post&quot; action = &quot;/GetParameterServlet/GetParameterValues&quot;> <p>Which of the whisky you like most</p> <input type = &quot;checkbox&quot; name =&quot;whisky&quot; value = &quot;RoyalChallenge&quot;>RoyalChallenge.<br> <input type = &quot;checkbox&quot; name =&quot;whisky&quot; value = &quot;RoyalStag&quot;>RoyalStag.<br> <input type = &quot;checkbox&quot; name =&quot;whisky&quot; value = &quot;Bagpiper&quot;>Bagpiper.<br> <input type =&quot;submit&quot; name= &quot;submit&quot;> </form> </body> </html>
  66. 66. MULTIPLE VALUES FOR A SINGLE PARAMETER <ul><li>import  java.io.*; import  javax.servlet.*; import  javax.servlet.http.*; public class  GetParameterValues  extends  HttpServlet{    protected void  doPost(HttpServletRequest request, HttpServletResponse response)                          throws  ServletException, IOException {     response.setContentType(&quot;text/html&quot;);     PrintWriter pw = response.getWriter();     String[] whisky = request.getParameterValues(&quot;whisky&quot;);      for ( int  i=0; i<whisky.length; i++){       pw.println(&quot;<br>whisky : &quot; + whisky[i]);     }   } } </li></ul>
  68. 68. Thank You!! Please don’t forget to write your review comments on http://slideshare.net/vikramsingh.v85