Thursday, July 11, 2013

Java Servlet for Beginner

Few of my students always get confused when they even hear about different web based technologies. And they feel of themselves as they will never be able to become a good programmer or web-app developer as they don't even heard the basic technologies involved in the web application development. Reason can be varies probably the universities they are studying at are not filled with well trained faculty.
So before jumping into servlet you must be aware of first few things:
  1. Client-Side Scripting
  2. Server-Side Scripting
  3. Request & Response
  4. WebServer
  5. Servlet Container
Client-Side Scripting

Client-side scripting generally refers to the class of computer programs on the web that are executed client-side, by the user's web browser instead of involving a web-server or servlet container. Example:javascript is a client side scripting language. If you ever use alert("abc"); then it will simply ask browser to show a dialog with the message "abc".

Server-Side Scription
Server side scripting means that all of the code is executed on the server before the data is passed to the user's browser.Example:JSP, Servlet, PHP and many other languages that are server side. Once you will ask out.write("abc"); browser will request server to parse then statement and generate a response on server and return that response to browser.

Request & Response
Request, which your computer sends to the web server contains all sorts of (potentially) interesting information in order to fetch or transform into detailed information about the information passed.Example: http://www.google.comResponse, which server return with transformed information against a  requests.Example: Google Search Page displayed on your browser

WebServer:
The term web server can refer to either the hardware (the computer) or the software (the computer application) that helps to deliver web content that can be accessed through the Internet.Example of Application WebServers: Apache Web Server (PHP) IIS(ASP) Apache Tomcat(JSP/Servlet)

Servlet Container:

To deploy and run a servlet, a web container must be used. A web container (also known as a servlet container) is essentially the component of a web server. A web container is responsible for managing the lifecycle of servlets, mapping a URL to a particular servlet and ensuring that the URL requester has the correct access rights.

Till now probably you must be clear to the terms that we have used in the above diagram. Now before getting into the coding of servlet I would like to drag it more and make you understood to the core lifecycle of servlet. That what is the difference in java class and a servlet and how basically they get into existence and  expires.


In java we have a main method which we consider as an entry point into our application while on the other hand in servlet we have init method that will be executed at first and after init() it calls to service methods:

doGet():Ask to get the thinking to get in requested URL
doPost():Same as GET method with extra information send in
body part.
doHead():Only header part of response without any body section.
doTrace():Ask for loop back of request message.(For testing)
doPut():say to put the enclosed info in requested URL.
doDelete():sat to delete the info in requested URL.
doOption():ask for list of option in requested URL needed.
But, here we will only proceed with doGet method. After completion of service method finally the servlet end up with it's life by executing destroy() method. For a quick overview servlet executes as:

init()---->  doGet()/doPost()/doDelete()...  ---->destroy()

CODING


import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;


Before coding we need to import the files that we will be using in our servlet. Here, the red marked imports are for servlet. 

public class FirstServlet extends HttpServlet {


Our all servlets must extend HttpServlet and HttpServlet itself extends from GenericServlet. GenericServlet contains init() and destroy() methods while HttpServlet class contains all the methods of service i.e. doGet, doPost and etc. So, our FirstServlet have access to all the methods of GenericServlet and HttpServlet.

Note:
A java servlet class can contain any kind of java code the JDK can compile, a java servlet class needs to be compiled prior to using it; it must use servlet-api.jar
If you will not override the method init(), destory() then the default methods will be executed. As it's our first servlet so we better avoid too much coding and simply overriding HttpServlet's doGet

      public void doGet(HttpServletRequest request,   HttpServletResponse response)
throws IOExceptionServletException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>First servlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("It works...<hr>");
            out.println("</body>");
            out.println("</html>");
      }



This servlet will display "First servlet" in title of the browser and will print "It works..." at browser.

Complete Servlet Code:
package com.kiosk;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {
      public void doGet(HttpServletRequest request, HttpServletResponse response)
                  throws IOException, ServletException {
            response.setContentType("text/html");
            PrintWriter out = response.getWriter();
            out.println("<html>");
            out.println("<head>");
            out.println("<title>First servlet</title>");
            out.println("</head>");
            out.println("<body>");
            out.println("It works...<hr>");
            out.println("</body>");
            out.println("</html>");
      }
}



 Now we have only done with the code of servlet. But, we need to execute it in contain and in order to do this we must need to tell the container that this is our servlet and will be deployed on this container. I think before getting into the configuration of servlet into servlet container we must need to tell you about the installation of webserver and a bit about it's directory structure.

Here we have choosen Apache Tomcat for our servlet execution but some other containers are also available in market from which you may choose. Apache tomcat can be downloaded from the following  URL http://tomcat.apache.org/download-70.cgi, I had 64 Bit OS so have chosen 64 Bit Archive 

How to Install Tocmat:

Download the binary zip distribution in a local folder (we will use c:\server in the rest of the guide)
2. Set the environment variables 
JAVA_HOME=path_to_JDK_installation_folder
CATALINA_HOME=path_to_tomcat_installation_folder either as Windows system variables or in the files
startup.bat and shutdown.bat from the bin directory

Example: place the following lines in the beginning of startup.bat and shutdown.bat:
set JAVA_HOME=c:\jdk1.6.0
set CATALINA_HOME=c:\apache-tomcat-6.0.20

Tomcat Directory Structure

bin – contains executable files for controlling the server (start, shut down etc.)
conf – contains configuration files; most important server.xml for configuring the server and web.xml a general configuration file for web applications
lib – libraries (jars) used by tomcat and deployed web applications
logs – log files
temp – temporary files
webapps – contains the web applications deployed
work – contains files created by tomcat during running (e.g. it crates a servlet from each jsp file)

Starting & Shutting Down Tomcat
start Tomcat from a cmd prompter (window):
  c:\apache-tomcat-6.0.20\bin\startup.bat
verify startup by pointing a browser to the url http://localhost:8080
shutting down Tomcat from a cmd prompter (window):
   c:\apache-tomcat-6.0.20\bin\shutdown.bat

Now we are able to start our servlet and it's time to get back to the servlet that we have developed and integrate it with the container to make it executable.

Build a directory structure of your servlet application in this way:
\--firstservlet 

    \--src

         --com

            \--kiosk

                \--classes   

    \--WEB-INF



Copy your servlet into firstservlet/src/com/kiosk/.

And now it's time to create an integration file which is here a deployment descriptor.

Deployment Descriptor
deployment descriptor (DD) refers to a configuration file for an artifact that is deployed to some container/engine.

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"

xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee

http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">


 <servlet>

  <servlet-name>FirstServlet</servlet-name>

  <servlet-class>com.kiosk.FirstServlet</servlet-class>

 </servlet>


 <servlet-mapping>

  <servlet-name>First Servlet</servlet-name>

  <url-pattern>/frs</url-pattern>

 </servlet-mapping>

</web-app>


servlet-name is the alias name for the FirstServlet classurl-pattern is the url path you type in browser address bar

Compilation

In order to compile your servlet you need to execute the following command on your command prompt.
javac src/com/kiosk/FirstServlet.java -classpath "C:\Java\j2ee\lib\javaee.jar" -d classes

The “javaee.jar” is required for http servlet and packaged with J2EE SDK. In addition, all compiled classes will put in “classes” folder automatically

Now it's time to manually deploy your application in tomcat by going into tomcat folder and create the directory structure as follows:
\--apache-tomcat-6.0.20
     \--webapps       
         \--firstservlet
             \--WEB-INF (Do not change this folder name)                   
                 \--classes   
                      \--com                           
                         \--kiosk



Now copy the files that we have created into the tomcat folder structure that we have created, here only two files we have created web.xml and FirstServlet.java but we will copy into the folder web.xml and FirstServlet.class
\--apache-tomcat-6.0.20
     \--webapps       
         \--firstservlet               
            \--WEB-INF
                \--web.xml  
             \--classes   
                 \--com   
                     \--kiosk
                         \--FirstServlet.class
This is it. Now start tomcat   using c:\apache-tomcat-6.0.20\bin\startup.bat and test your application using following URL:
http://localhost:8080/firstservlet/frs




No comments:

Post a Comment