Monday 7 October 2013

My first servlet application (a)

Creating servlet programming:  using Command Prompt


set up:
Prerequisite:
1. Download any server (Ex: Tomcat, Weblogic,..)
    How to download Tomcat Server
2. Download the jar files and configure
    servlet-api.jar
3. JDK 7
4. Eclipse IDE for Java EE Developers (Juno 4.2)
5. import javax.servlet and javax.servlet.http packages

Table of Content:

1. Create Dynamic Web Project
2. Create Servlet class
3. Deploy the servlet
4. Run and test the servlet

  1. install jdk from http://java.sun.com
  2. install Apache Tomcat from htt://tomcat.apache.org
  3. Eclipse IDE for java EE Developers
  4. Set up the following environment variables
(a) TOMCAT Home: Directory where Tomcat is installed (e.g: c:\Tomcat)
  1. (b) JAVA_Home: Directory where Java is installed (e.g: c:\Java\jdk1.6.0_06)
  2. (c) Add Java_Home \bin directory to CLASSPATH (E.G: c:\java\jdk1.6.0_06\bin)
  3. Put servlet-api.jar in classpath
My first servlet apps

  1. servlet class – business logic
  2. web.xml - configuration file (every web app should follow web.xml file, this is the place where the first server check when the request comes from the client . So when the request comes from the client server goes to this web.xml configuration file checks for that particular request tries to see the match if it finds the match
  1. web.xml - configuration file (every web app should follow web.xml file, this is the place where the server first check when the request comes from the client . So when the request comes from the client server goes to this web.xml configuration file checks for that particular request tries to see the match if it finds the match
  1. web. Jar file :
we have the servlet class , we have the web.xml what you need to do? In order to deploy your application into webserver is : build a jar file out of your classes , html configuration file all those things. So we need to build a jar, including the servlet class and web.xml
  1. Deploy:
  • Once you build a jar, you deploy into the web server.
  1. Execute:
  • Once you deploy the application into the web server
  • application is ready and you can simply go ahead and enter the url and execute your web application 

Now lets have a look in detail

1. first thing is writing your servlet class.

So first servlet application is I'm simply going to print text “hello World” on the screen so when the user enter the url result of that text would be displayed on the web page

  • I want to make it first application so simple because I would like to do concentrate more on the other things like how do you get all the pieces together and how do you build your jar files , how do you deploy it and I would like to concentrate more on how the code flows between different methods of the class and which order so all those different things about the servlet and web application on the whole so thats the reason I could not put much business logic.
    Just see I have written this code for the servlet and the web.xml file ahead .

    package com.rajservlet.servlets;

    import java.io.IOException;
    import java.io.PrintWriter;
    //these are a part of servlet api jar files, these are the servlet packages.
    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;

    public class HelloWorldServlet extends HttpServlet // implements javax.servlet.Servlet //no need this interface now
    {
    public HelloWorldServlet()
    {
    super();
    System.out.println(“in HelloWorld Constructor”);
    }
    public void init()
    {
     System.out.println(“In Hello World Init”);
    }
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
      System.out.println(“In Hellow World service()”);
      If(“GET”.equalsIgnoreCase(request.getMethod())
      {
        doGet(request, response);
      }
      else if(“POST”, equalsIgnoreCase(request.getMethod()))
      {
        doPost(request, response);
      }
     }

    Protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
      System.out.println(“in HelloWordl doGet”);
    }
     Response.setContentType(“text/html”);
     PrintWriter out=response.getWriter();
      out.println(“<html>”);
      out.pritnln(“<body>”);
      out.println(“hello World”);
      out.println(“</body>”);
      out.println(“</html>”);
     }
     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
    {
     System.out.println(“In Hello World doPost()”);
     }
    This is servlet code my servlet is in my package called com.rajservlet.servlet package
  • This is our first “hello world “ servlet,
    ·         My servlet in the package called “com.rajservlet.servlets” package
    ·         We know that in order to write a servlet we need to extend HttpServlet class since we have already imported
    ·         implements javax.servlet.Servlet //no need this interface now: bcoz we know that the HttpServlet extends Generic servlet which inturn implements the Servlet interface .
    ·         So you are Hello World servlet will indirectly be implementing the Servlet interface so we do not write explicitly to implements servlets there
    ·         So once I do the “extends” HttpServlet on the class my class (ie: HelloWorldServlet) has got some features now and those special features are nothing but servlet features or servlet behavior
    ·         I have written all the call back methods in this class during the session init() method, doGet(), doPost(), destroy().
    ·         We have discussed earlier that we don’t need constructor to be declared in a servlet , so practically in real time we don’t put in a constructor  in your servlet because you will not be do anything in the constructor as well. All the initialization code will be in the init() method and jvm will put the default constructor in your servlet class so I simply put “System.out.println() is there in the constructor .
    ·         Next the init() method , this is the place where all your initialization takes place so if you have to perform initialization like getting connection to the database or any other stuff you want to perform in a servlet class , you know that for every request comes in the servlet , the service() method is called which is in turn calles doGet() or doPost() method but the init() method is only calls once when the servlet is loaded so only one time initialization stuff you put in the init() method

    ·         Next service(HttpServletRequest request, HttpServletResponse response) method  it takes the parameters  HttpServletRequest request and HttpServletResponse response throws servlet exception and IOException

    ·         Here one thing please make a note down when do you develop your servlet application in real time  you do not write the service() method as well  in fact you take the default implementation provided by the HttpServlet.
    ·         Again I just put here this service()method so that you will know the flow and when this method is called  and I just tried to emulate (follow) logic which could have been written in the HttpServlet so the HttpServlet class has similar logic but apart from this there will be a lot of other code as of now at this point of time I would …doGet() and doPost() because that is the place I am going to write my business logic so I simply capture the type of method passed by the user so I used request.getMethod()to determine what type of the request the user has sent, if the type is GET, then I call the doGet() method  which passes request and response objects .
    ·         If the type is POST, then I simply call the doPost() method passing the request and response objects.
    ·         So only thing is this service() method is going to do is taking the request, check the type of request, if it is “GET” call the doGet() method , if the type of request is “POST” , call the doPost() method.
    ·         Because it is first call we do not provide any method type it take the GET by default because there  is most specific method provided the default is GET so my doGet() method should be called now so that is the reason I put all the business logic in the doGet() method which again this doGet() method again take the HttpRequest and HttpResponse the parameters and I simply give a print statements here that is “In Hello World in doGet()”
    ·         One thing setContentType() , means setting the content type is to text or html so this is going to tell the client that the type of response I’m sending back to the client is of type html, if you would have been sending pdf document to the client , simply set “application/pdf”. I sent this content type to the response sent back to the client .
    Here I’ m creating PrintWriter object will be displayed on my servlet application.

HelloWorld servlet program

YOu may like the following posts: