+ All Categories
Home > Documents > ServLet Tutorials

ServLet Tutorials

Date post: 02-Jun-2018
Category:
Upload: deepakdit
View: 236 times
Download: 0 times
Share this document with a friend

of 36

Transcript
  • 8/10/2019 ServLet Tutorials

    1/36

    Servlet Filters

    Servlet Filters are Java classes that can be used in Servlet Programming for the following purposes:

    To intercept requests from a client before they access a resource at back end.

    To manipulate responses from server before they are sent back to the client.

    There are are various types of filters suggested by the specifications:

    Authentication Filters. Data compression Filters.

    Encryption Filters.

    Filters that trigger resource access events.

    Image Conversion Filters.

    Logging and Auditing Filters. MIME-TYPE Chain Filters.

    Tokenizing Filters .

    XSL/T Filters That Transform XML Content.

    Filters are deployed in the deployment descriptor file web.xml and then map to either servlet names or URL patterns inyour application's deployment descriptor.

    When the web container starts up your web application, it creates an instance of each filter that you have declared in thedeployment descriptor. The filters execute in the order that they are declared in the deployment descriptor.

    Servlet Filter Methods:

    A filter is simply a Java class that implements the javax.servlet.Filter interface. The javax.servlet.Filter interface definesthree methods:

    S.N. Method & Description

    1public void doFilter (ServletRequest, ServletResponse, FilterChain)This method is called by the container each time a request/response pair is passed through the chain due to a clientrequest for a resource at the end of the chain.

    2public void init(FilterConfig filterConfig)This method is called by the web container to indicate to a filter that it is being placed into service.

    3public void destroy()This method is called by the web container to indicate to a filter that it is being taken out of service.

    Servlet Filter Example:

    Following is the Servlet Filter Example that would print the clients IP address and current date time. This example wouldgive you basic understanding of Servlet Filter, but you can write more sophisticated filter applications using the sameconcept:

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

    // Implements Filter classpublic class LogFilter implements Filter {

    public void init(FilterConfig config)

  • 8/10/2019 ServLet Tutorials

    2/36

    throws ServletException{// Get init parameterString testParam = config.getInitParameter("test-param");

    //Print the init parameterSystem.out.println("Test Param: " + testParam);

    }public void doFilter(ServletRequest request,

    ServletResponse response,FilterChain chain)throws java.io.IOException, ServletException {

    // Get the IP address of client machine.String ipAddress = request.getRemoteAddr();

    // Log the IP address and current timestamp.System.out.println("IP "+ ipAddress + ", Time "

    + new Date().toString());

    // Pass request back down the filter chainchain.doFilter(request,response);

    }public void destroy( ){

    /* Called before the Filter instance is removedfrom service by the web container*/

    }

    }

    Compile LogFilter.javain usual way and put your class file in /webapps/ROOT/WEB-INF/classes.

    Servlet Filter Mapping in Web.xml:

    Filters are defined and then mapped to a URL or Servlet, in much the same way as Servlet is defined and then mapped to aURL pattern. Create the following entry for filter tag in the deployment descriptor file web.xml

    LogFilterLogFilter

    test-paramInitialization Paramter

    LogFilter/*

    The above filter would apply to all the servlets because we specified /*in our configuration. You can specicy a particularservlet path if you want to apply filter on few servlets only.

    Now try to call any servlet in usual way and you would see generated log in your web server log. You can use Log4Jlogger to log above log in a separate file.

    Using Multiple Filters:

    Your web application may define several different filters with a specific purpose. Consider, you define two filtersAuthenFilterandLogFilter. Rest of the process would remain as explained above except you need to create a different

    mapping as mentioned below:

  • 8/10/2019 ServLet Tutorials

    3/36

    LogFilterLogFilter

    test-paramInitialization Paramter

    AuthenFilterAuthenFilter

    test-paramInitialization Paramter

    LogFilter/*

    AuthenFilter/*

    Filters Application Order:

    The order of filter-mapping elements in web.xml determines the order in which the web container applies the filter to the

    servlet. To reverse the order of the filter, you just need to reverse the filter-mapping elements in the web.xml file.

    For example, above example would apply LogFilter first and then it would apply AuthenFilter to any servlet but thefollowing example would reverse the order:

    AuthenFilter/*

    LogFilter/*

    Servlet Exception

    When a servlet throws an exception, the web container searches the configurations in web.xmlthat use the exception-type

    element for a match with the thrown exception type.

    You would have to use the error-pageelement in web.xml to specify the invocation of servlets in response to certainexceptionsor HTTP status codes.

    web.xml Configuration:

    Consider, you have anErrorHandlerservlet which would be called whenever there is any defined exception or error.Following would be the entry created in web.xml.

    ErrorHandlerErrorHandler

  • 8/10/2019 ServLet Tutorials

    4/36

    ErrorHandler/ErrorHandler

    404/ErrorHandler

    403/ErrorHandler

    javax.servlet.ServletException

    /ErrorHandler

    java.io.IOException/ErrorHandler

    If you want to have a generic Error Handler for all the exceptions then you should define following error-page instead ofdefining separate error-page elements for every exception:

    java.lang.Throwable/ErrorHandler

    Following are the points to be noted about above web.xml for Exception Handling:

    The servlet ErrorHandler is defined in usual way as any other servlet and configured in web.xml. If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), then ErrorHandler servlet

    would be called.

    If the web application throws either ServletExceptionorIOException, then the web container invokes the/ErrorHandler servlet.

    You can define different Error Handlers to handle different type of errors or exceptions. Above example is verymuch generic and hope it serve the purpose to explain you the basic concept.

    Request Attributes - Errors/Exceptions:

    Following is the list of request attributes that an error-handling servlet can access to analyse the nature of error/exception.

    S.N. Attribute & Description

    1javax.servlet.error.status_codeThis attribute give status code which can be stored and analysed after storing in a java.lang.Integer data type.

    2javax.servlet.error.exception_typeThis attribute gives information about exception type which can be stored and analysed after storing in a

    java.lang.Class data type.

    3javax.servlet.error.messageThis attribute gives information exact error message which can be stored and analysed after storing in a

    java.lang.String data type.

  • 8/10/2019 ServLet Tutorials

    5/36

    4javax.servlet.error.request_uriThis attribute gives information about URL calling the servlet and it can be stored and analysed after storing in a

    java.lang.String data type.

    5javax.servlet.error.exceptionThis attribute gives information the exception raised which can be stored and analysed after storing in a

    java.lang.Throwable data type.

    6javax.servlet.error.servlet_nameThis attribute gives servlet name which can be stored and analysed after storing in a java.lang.String data type.

    Error Handler Servlet Example:

    Following is the Servlet Example that would be used as Error Handler in case of any error or exception occurs with yourany of the servlet defined.

    This example would give you basic understanding of Exception Handling in Servlet, but you can write more sophisticated

    filter applications using the same concept:

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

    // Extend HttpServlet classpublic class ErrorHandler extends HttpServlet {

    // Method to handle GET method request.public void doGet(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException

    {// Analyze the servlet exceptionThrowable throwable = (Throwable)request.getAttribute("javax.servlet.error.exception");Integer statusCode = (Integer)request.getAttribute("javax.servlet.error.status_code");String servletName = (String)request.getAttribute("javax.servlet.error.servlet_name");if (servletName == null){

    servletName = "Unknown";}String requestUri = (String)request.getAttribute("javax.servlet.error.request_uri");if (requestUri == null){

    requestUri = "Unknown";}

    // Set response content typeresponse.setContentType("text/html");

    PrintWriter out = response.getWriter();String title = "Error/Exception Information";

    String docType ="\n";out.println(docType +"\n" +"" + title + "\n" +"\n");

    if (throwable == null && statusCode == null){out.println("Error information is missing");out.println("Please return to the

  • 8/10/2019 ServLet Tutorials

    6/36

    "\">Home Page.");}else if (statusCode != null){

    out.println("The status code : " + statusCode);}else{

    out.println("Error information");out.println("Servlet Name : " + servletName +

    "");out.println("Exception Type : " +

    throwable.getClass( ).getName( ) +"");

    out.println("The request URI: " + requestUri +

    "

    ");out.println("The exception message: " +

    throwable.getMessage( ));}out.println("");out.println("");

    }// Method to handle POST method request.public void doPost(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException {doGet(request, response);

    }}

    Compile ErrorHandler.javain usual way and put your class file in /webapps/ROOT/WEB-INF/classes.

    Let us add the following configuration in web.xml to handle exceptions:

    ErrorHandlerErrorHandler

    ErrorHandler/ErrorHandler

    404/ErrorHandler

    java.lang.Throwable/ErrorHandler

    Now try to use a servlet which raise any exception or type a wrong URL, this would trigger Web Container to callErrorHandlerservlet and display an appropriate message as programmed. For example, if you type a wrong URL then itwould display the following result:

    The status code : 404

    Above code may not work with some web browsers. So try with Mozilla and Safari and it should work.

    Cookies

    Cookies are text files stored on the client computer and they are kept for various information tracking purpose. JavaServlets transparently supports HTTP cookies.

    There are three steps involved in identifying returning users:

  • 8/10/2019 ServLet Tutorials

    7/36

    Server script sends a set of cookies to the browser. For example name, age, or identification number etc. Browser stores this information on local machine for future use.

    When next time browser sends any request to web server then it sends those cookies information to the server andserver uses that information to identify the user.

    This chapter will teach you how to set or reset cookies, how to access them and how to delete them.

    The Anatomy of a Cookie:

    Cookies are usually set in an HTTP header (although JavaScript can also set a cookie directly on a browser). A servlet thatsets a cookie might send headers that look something like this:

    HTTP/1.1 200 OKDate: Fri, 04 Feb 2000 21:03:38 GMTServer: Apache/1.3.9 (UNIX) PHP/4.0b3Set-Cookie: name=xyz; expires=Friday, 04-Feb-07 22:03:38 GMT;

    path=/; domain=tutorialspoint.comConnection: closeContent-Type: text/html

    As you can see, the Set-Cookie header contains a name value pair, a GMT date, a path and a domain. The name and value

    will be URL encoded. The expires field is an instruction to the browser to "forget" the cookie after the given time anddate.

    If the browser is configured to store cookies, it will then keep this information until the expiry date. If the user points thebrowser at any page that matches the path and domain of the cookie, it will resend the cookie to the server. The browser's

    headers might look something like this:

    GET / HTTP/1.0Connection: Keep-AliveUser-Agent: Mozilla/4.6 (X11; I; Linux 2.2.6-15apmac ppc)Host: zink.demon.co.uk:1126Accept: image/gif, */*Accept-Encoding: gzip

    Accept-Language: enAccept-Charset: iso-8859-1,*,utf-8Cookie: name=xyz

    A servlet will then have access to the cookie through the request method request.getCookies() which returns an array ofCookieobjects.

    Servlet Cookies Methods:

    Following is the list of useful methods which you can use while manipulating cookies in servlet.

    S.N. Method & Description

    1public void setDomain(String pattern)This method sets the domain to which cookie applies, for example tutorialspoint.com.

    2public String getDomain()This method gets the domain to which cookie applies, for example tutorialspoint.com.

    3public void setMaxAge(int expiry)This method sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the

    cookie will last only for the current session.

    4public int getMaxAge()This method returns the maximum age of the cookie, specified in seconds, By default, -1 indicating the cookie will

    persist until browser shutdown.

  • 8/10/2019 ServLet Tutorials

    8/36

    5public String getName()This method returns the name of the cookie. The name cannot be changed after creation.

    6public void setValue(String newValue)This method sets the value associated with the cookie.

    7public String getValue()This method gets the value associated with the cookie.

    8public void setPath(String uri)This method sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all

    URLs in the same directory as the current page as well as all subdirectories.

    9public String getPath()This method gets the path to which this cookie applies.

    10public void setSecure(boolean flag)This method sets the boolean value indicating whether the cookie should only be sent over encrypted (i.e. SSL)

    connections.

    11public void setComment(String purpose)This method specifies a comment that describes a cookie's purpose. The comment is useful if the browser presentsthe cookie to the user.

    12public String getComment()This method returns the comment describing the purpose of this cookie, or null if the cookie has no comment.

    Setting Cookies with Servlet:

    Setting cookies with servlet involves three steps:

    (1) Creating a Cookie object:You call the Cookie constructor with a cookie name and a cookie value, both of which arestrings.

    Cookie cookie = new Cookie("key","value");

    Keep in mind, neither the name nor the value should contain white space or any of the following characters:

    [ ] ( ) = , " / ? @ : ;

    (2) Setting the maximum age:You use setMaxAge to specify how long (in seconds) the cookie should be valid.

    Following would set up a cookie for 24 hours.

    cookie.setMaxAge(60*60*24);

    (3) Sending the Cookie into the HTTP response headers:You use response.addCookieto add cookies in the HTTPresponse header as follows:

    response.addCookie(cookie);

    Example:

    Let us modify our Form Exampleto set the cookies for first and last name.

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

    // Extend HttpServlet classpublic class HelloForm extends HttpServlet {

  • 8/10/2019 ServLet Tutorials

    9/36

    public void doGet(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException

    {// Create cookies for first and last names.Cookie firstName = new Cookie("first_name",

    request.getParameter("first_name"));Cookie lastName = new Cookie("last_name",

    request.getParameter("last_name"));

    // Set expiry date after 24 Hrs for both the cookies.firstName.setMaxAge(60*60*24);lastName.setMaxAge(60*60*24);

    // Add both the cookies in the response header.response.addCookie( firstName );response.addCookie( lastName );

    // Set response content typeresponse.setContentType("text/html");

    PrintWriter out = response.getWriter();String title = "Setting Cookies Example";String docType ="\n";out.println(docType +

    "\n" +"" + title + "\n" +"\n" +"" + title + "\n" +"\n" +" First Name: "+ request.getParameter("first_name") + "\n" +" Last Name: "+ request.getParameter("last_name") + "\n" +"\n" +"");

    }}

    Compile above servlet HelloFormand create appropriate entry in web.xml file and finally try following HTML page tocall servlet.

    First Name:
    Last Name:

    Keep above HTML content in a file Hello.htm and put it in /webapps/ROOT directory.When you would access http://localhost:8080/Hello.htm, here is the actual output of the above form.

    First Name:

    Last Name:

  • 8/10/2019 ServLet Tutorials

    10/36

    Try to enter First Name and Last Name and then click submit button. This would display first name and last name on yourscreen and same time it would set two cookies firstName and lastName which would be passed back to the server when

    next time you would press Submit button.

    Next section would explain you how you would access these cookies back in your web application.

    Reading Cookies with Servlet:

    To read cookies, you need to create an array of javax.servlet.http.Cookieobjects by calling the getCookies( )method ofHttpServletRequest. Then cycle through the array, and use getName() and getValue() methods to access each cookie andassociated value.

    Example:

    Let us read cookies which we have set in previous example:

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

    // Extend HttpServlet classpublic class ReadCookies extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    Cookie cookie = null;Cookie[] cookies = null;

    // Get an array of Cookies associated with this domaincookies = request.getCookies();

    // Set response content typeresponse.setContentType("text/html");

    PrintWriter out = response.getWriter();String title = "Reading Cookies Example";String docType ="\n";out.println(docType +

    "\n" +"" + title + "\n" +"\n" );

    if( cookies != null ){out.println(" Found Cookies Name and Value");for (int i = 0; i < cookies.length; i++){

    cookie = cookies[i];out.print("Name : " + cookie.getName( ) + ", ");

    out.print("Value: " + cookie.getValue( )+"
    ");}

    }else{out.println("No cookies founds");

    }out.println("");out.println("");

    }}

  • 8/10/2019 ServLet Tutorials

    11/36

    Compile above servlet ReadCookiesand create appropriate entry in web.xml file. If you would have set first_namecookie as "John" and last_name cookie as "Player" then running http://localhost:8080/ReadCookieswould display the

    following result:

    Found Cookies Name and Value

    Name : first_name, Value: John

    Name : last_name, Value: Player

    Delete Cookies with Servlet:

    To delete cookies is very simple. If you want to delete a cookie then you simply need to follow up following three steps:

    Read an already exsiting cookie and store it in Cookie object.

    Set cookie age as zero using setMaxAge()method to delete an existing cookie.

    Add this cookie back into response header.

    Example:

    Following example would delete and existing cookie named "first_name" and when you would run ReadCookies servletnext time it would return null value for first_name.

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

    // Extend HttpServlet classpublic class DeleteCookies extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    Cookie cookie = null;Cookie[] cookies = null;

    // Get an array of Cookies associated with this domaincookies = request.getCookies();

    // Set response content typeresponse.setContentType("text/html");

    PrintWriter out = response.getWriter();String title = "Delete Cookies Example";String docType ="\n";out.println(docType +

    "\n" +"" + title + "\n" +"\n" );

    if( cookies != null ){out.println(" Cookies Name and Value");for (int i = 0; i < cookies.length; i++){

    cookie = cookies[i];if((cookie.getName( )).compareTo("first_name") == 0 ){

    cookie.setMaxAge(0);response.addCookie(cookie);out.print("Deleted cookie : " +

    cookie.getName( ) + "
    ");}

  • 8/10/2019 ServLet Tutorials

    12/36

    out.print("Name : " + cookie.getName( ) + ", ");out.print("Value: " + cookie.getValue( )+"
    ");

    }}else{

    out.println("No cookies founds");

    }out.println("");out.println("");

    }}

    Compile above servlet DeleteCookiesand create appropriate entry in web.xml file. Now runninghttp://localhost:8080/DeleteCookies would display the following result:

    Cookies Name and Value

    Deleted cookie : first_nameName : first_name, Value: JohnName : last_name, Value: Player

    Now try to run http://localhost:8080/ReadCookies and it would display only one cookie as follows:

    Found Cookies Name and Value

    Name : last_name, Value: Player

    You can delete your cookies in Internet Explorer manually. Start at the Tools menu and select Internet Options. To deleteall cookies, press Delete Cookies.

    Session Tracking

    HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the client opens a separate

    connection to the Web server and the server automatically does not keep any record of previous client request.

    Still there are following three ways to maintain session between web client and web server:

    Cookies:

    A webserver can assign a unique session ID as a cookie to each web client and for subsequent requests from the client

    they can be recognized using the recieved cookie.

    This may not be an effective way because many time browser does not support a cookie, so I would not recommend to usethis procedure to maintain the sessions.

    Hidden Form Fields:

    A web server can send a hidden HTML form field along with a unique session ID as follows:

  • 8/10/2019 ServLet Tutorials

    13/36

    This entry means that, when the form is submitted, the specified name and value are automatically included in the GET orPOST data. Each time when web browser sends request back, then session_id value can be used to keep the track of

    different web browsers.

    This could be an effective way of keeping track of the session but clicking on a regular () hypertext link doesnot result in a form submission, so hidden form fields also cannot support general session tracking.

    URL Rewriting:

    You can append some extra data on the end of each URL that identifies the session, and the server can associate thatsession identifier with data it has stored about that session.

    For example, with http://tutorialspoint.com/file.htm;sessionid=12345, the session identifier is attached as sessionid=12345which can be accessed at the web server to identify the client.

    URL rewriting is a better way to maintain sessions and works for the browsers when they don't support cookies but heredrawback is that you would have generate every URL dynamically to assign a session ID though page is simple static

    HTML page.

    The HttpSession Object:Apart from the above mentioned three ways, servlet provides HttpSession Interface which provides a way to identify a

    user across more than one page request or visit to a Web site and to store information about that user.

    The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The sessionpersists for a specified time period, across more than one connection or page request from the user.

    You would get HttpSession object by calling the public method getSession()of HttpServletRequest, as below:

    HttpSession session = request.getSession();

    You need to call request.getSession() before you send any document content to the client. Here is a summary of theimportant methods available through HttpSession object:

    S.N. Method & Description

    1public Object getAttribute(String name)

    This method returns the object bound with the specified name in this session, or null if no object is bound under the name.

    2public Enumeration getAttributeNames()

    This method returns an Enumeration of String objects containing the names of all the objects bound to this session.

    3 public long getCreationTime()This method returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.

    4public String getId()

    This method returns a string containing the unique identifier assigned to this session.

    5

    public long getLastAccessedTime()

    This method returns the last time the client sent a request associated with this session, as the number of milliseconds since

    midnight January 1, 1970 GMT.

  • 8/10/2019 ServLet Tutorials

    14/36

    6

    public int getMaxInactiveInterval()

    This method returns the maximum time interval, in seconds, that the servlet container will keep this session open between

    client accesses.

    7public void invalidate()

    This method invalidates this session and unbinds any objects bound to it.

    8public boolean isNew(

    This method returns true if the client does not yet know about the session or if the client chooses not to join the session.

    9public void removeAttribute(String name)

    This method removes the object bound with the specified name from this session.

    10public void setAttribute(String name, Object value)

    This method binds an object to this session, using the name specified.

    11public void setMaxInactiveInterval(int interval)

    This method specifies the time, in seconds, between client requests before the servlet container will invalidate this session.

    Session Tracking Example:

    This example describes how to use the HttpSession object to find out the creation time and the last-accessed time for a

    session. We would associate a new session with the request if one does not already exist.

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

    // Extend HttpServlet class

    public class SessionTrack extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    // Create a session object if it is already not created.HttpSession session = request.getSession(true);// Get session creation time.Date createTime = new Date(session.getCreationTime());// Get last access time of this web page.Date lastAccessTime =

    new Date(session.getLastAccessedTime());

    String title = "Welcome Back to my website";

    Integer visitCount = new Integer(0);String visitCountKey = new String("visitCount");String userIDKey = new String("userID");String userID = new String("ABCD");

    // Check if this is new comer on your web page.if (session.isNew()){

    title = "Welcome to my website";session.setAttribute(userIDKey, userID);

    } else {visitCount = (Integer)session.getAttribute(visitCountKey);visitCount = visitCount + 1;userID = (String)session.getAttribute(userIDKey);

    }

  • 8/10/2019 ServLet Tutorials

    15/36

    session.setAttribute(visitCountKey, visitCount);

    // Set response content typeresponse.setContentType("text/html");PrintWriter out = response.getWriter();

    String docType ="\n";out.println(docType +

    "\n" +

    "" + title + "\n" +"\n" +"" + title + "\n" +"Session Infomation\n" +"\n" +"\n" +" Session infovalue\n" +"\n" +" id\n" +" " + session.getId() + "\n" +"\n" +" Creation Time\n" +" " + createTime +" \n" +"\n" +

    " Time of Last Access\n" +" " + lastAccessTime +" \n" +"\n" +" User ID\n" +" " + userID +" \n" +"\n" +" Number of visits\n" +" " + visitCount + "\n" +"\n" +"");

    }}

    Compile above servlet SessionTrackand create appropriate entry in web.xml file. Now running

    http://localhost:8080/SessionTrackwould display the following result when you would run for the first time:

    Welcome to my website

    Session Infomation

    Session info value

    id 0AE3EC93FF44E3C525B4351B77ABB2D5

    Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

    Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

    User ID ABCD

  • 8/10/2019 ServLet Tutorials

    16/36

    Number of visits 0

    Now try to run the same servlet for second time, it would display following result.

    Welcome Back to my website

    Session Infomation

    info type value

    id 0AE3EC93FF44E3C525B4351B77ABB2D5

    Creation Time Tue Jun 08 17:26:40 GMT+04:00 2010

    Time of Last Access Tue Jun 08 17:26:40 GMT+04:00 2010

    User ID ABCD

    Number of visits 1

    Deleting Session Data:

    When you are done with a user's session data, you have several options:

    Remove a particular attribute:You can callpublic void removeAttribute(String name)method to delete thevalue associated with a particular key.

    Delete the whole session:You can callpublic void invalidate()method to discard an entire session.

    Setting Session timeout:You can callpublic void setMaxInactiveInterval(int interval)method to set the timeoutfor a session individually.

    Log the user out:The servers that support servlets 2.4, you can call logoutto log the client out of the Web serverand invalidate all sessions belonging to all the users.

    web.xml Configuration:If you are using Tomcat, apart from the above mentioned methods, you can configuresession time out in web.xml file as follows.

    15

    The timeout is expressed as minutes, and overrides the default timeout which is 30 minutes in Tomcat.

    The getMaxInactiveInterval( ) method in a servlet returns the timeout period for that session in seconds. So if your sessionis configured in web.xml for 15 minutes, getMaxInactiveInterval( ) returns 900.

    Servlet JDBC

    This tutorial assumes you have understanding on how JDBC application works. Before starting with database accessthrough a servlet, make sure you have proper JDBC environment setup along with a database.

  • 8/10/2019 ServLet Tutorials

    17/36

    For more detail on how to access database using JDBC and its environment setup you can go through our JDBC Tutorial.

    To start with basic concept, let us create a simple table and create few records in that table as follows:

    Create Table

    To create the Employeestable in TEST database, use the following steps:

    Step 1:

    Open a Command Promptand change to the installation directory as follows:

    C:\>C:\>cd Program Files\MySQL\binC:\Program Files\MySQL\bin>

    Step 2:

    Login to database as follows

    C:\Program Files\MySQL\bin>mysql -u root -pEnter password: ********mysql>

    Step 3:

    Create the table Employeein TESTdatabase as follows:

    mysql> use TEST;mysql> create table Employees

    (

    id int not null,age int not null,first varchar (255),last varchar (255));

    Query OK, 0 rows affected (0.08 sec)mysql>

    Create Data Records

    Finally you create few records in Employee table as follows:

    mysql> INSERT INTO Employees VALUES (100, 18, 'Zara', 'Ali');

    Query OK, 1 row affected (0.05 sec)

    mysql> INSERT INTO Employees VALUES (101, 25, 'Mahnaz', 'Fatma');Query OK, 1 row affected (0.00 sec)

    mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');Query OK, 1 row affected (0.00 sec)

    mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');Query OK, 1 row affected (0.00 sec)

    mysql>

  • 8/10/2019 ServLet Tutorials

    18/36

    Accessing a Database:

    Here is an example which shows how to access TEST database using Servlet.

    // Loading required librariesimport java.io.*;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

    import java.sql.*;

    public class DatabaseAccess extends HttpServlet{

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    // JDBC driver name and database URLstatic final String JDBC_DRIVER="com.mysql.jdbc.Driver";static final String DB_URL="jdbc:mysql://localhost/TEST";

    // Database credentialsstatic final String USER = "root";static final String PASS = "password";

    // Set response content typeresponse.setContentType("text/html");PrintWriter out = response.getWriter();String title = "Database Result";String docType ="\n";out.println(docType +"\n" +"" + title + "\n" +"\n" +"" + title + "\n");

    try{// Register JDBC driver

    Class.forName("com.mysql.jdbc.Driver");

    // Open a connectionconn = DriverManager.getConnection(DB_URL,USER,PASS);

    // Execute SQL querystmt = conn.createStatement();String sql;sql = "SELECT id, first, last, age FROM Employees";ResultSet rs = stmt.executeQuery(sql);

    // Extract data from result setwhile(rs.next()){

    //Retrieve by column nameint id = rs.getInt("id");

    int age = rs.getInt("age");String first = rs.getString("first");String last = rs.getString("last");

    //Display valuesout.println("ID: " + id + "
    ");out.println(", Age: " + age + "
    ");out.println(", First: " + first + "
    ");out.println(", Last: " + last + "
    ");

    }out.println("");

    // Clean-up environmentrs.close();

  • 8/10/2019 ServLet Tutorials

    19/36

    stmt.close();conn.close();

    }catch(SQLException se){//Handle errors for JDBCse.printStackTrace();

    }catch(Exception e){//Handle errors for Class.forNamee.printStackTrace();

    }finally{//finally block used to close resourcestry{

    if(stmt!=null)stmt.close();

    }catch(SQLException se2){}// nothing we can dotry{

    if(conn!=null)conn.close();

    }catch(SQLException se){se.printStackTrace();

    }//end finally try} //end try

    }}

    Now let us compile above servlet and create following entries in web.xml

    ....

    DatabaseAccessDatabaseAccess

    DatabaseAccess/DatabaseAccess

    ....

    Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display following response:

    Database Result

    ID: 100, Age: 18, First: Zara, Last: AliID: 101, Age: 25, First: Mahnaz, Last: FatmaID: 102, Age: 30, First: Zaid, Last: KhanID: 103, Age: 28, First: Sumit, Last: Mittal

    File Upload

    A Servlet can be used with an HTML form tag to allow users to upload files to the server. An uploaded file could be a textfile or image file or any document.

    Creating a File Upload Form:

    The following HTM code below creates an uploader form. Following are the important points to be noted down:

    The form methodattribute should be set to POSTmethod and GET method can not be used.

    The form enctypeattribute should be set to multipart/form-data.

    The form actionattribute should be set to a servlet file which would handle file uploading at backend server.Following example is using UploadServletservlet to upload file.

  • 8/10/2019 ServLet Tutorials

    20/36

    To upload a single file you should use a single tag with attribute type="file". To allow multiple filesuploading, include more than one input tags with different values for the name attribute. The browser associates a

    Browse button with each of them.

    File Uploading Form

    File Upload:Select a file to upload:

    This will display following result which would allow to select a file from local PC and when user would click at "UploadFile", form would be submitted along with the selected file:

    File Upload:Select a file to upload:

    NOTE: This is just dummy form and would not work.

    Writing Backend Servlet:

    Following is the servlet UploadServletwhich would take care of accepting uploaded file and to store it in directory

    /webapps/data. This directory name could also be added using an external configurationsuch as a context-paramelement in web.xml as follows:

    ....

    Location to store uploaded filefile-upload

    c:\apache-tomcat-5.5.29\webapps\data\

    ....

    Following is the source code for UploadServlet which can handle multiple file uploading at a time. Before procedding youhave make sure the followings:

    Following example depends on FileUpload, so make sure you have the latest version of commons-fileupload.x.x.jarfile in your classpath. You can download it from http://commons.apache.org/fileupload/ .

    FileUpload depends on Commons IO, so make sure you have the latest version of commons-io-x.x.jarfile inyour classpath. You can download it from http://commons.apache.org/io/ .

  • 8/10/2019 ServLet Tutorials

    21/36

    While testing following example, you should upload a file which has less size than maxFileSizeotherwise filewould not be uploaded.

    Make sure you have created directories c:\temp and c:\apache-tomcat-5.5.29\webapps\data well in advance.

    // Import required java librariesimport java.io.*;import java.util.*;

    import javax.servlet.ServletConfig;import javax.servlet.ServletException;

    import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;

    import org.apache.commons.fileupload.FileItem;import org.apache.commons.fileupload.FileUploadException;import org.apache.commons.fileupload.disk.DiskFileItemFactory;import org.apache.commons.fileupload.servlet.ServletFileUpload;import org.apache.commons.io.output.*;

    public class UploadServlet extends HttpServlet {

    private boolean isMultipart;private String filePath;private int maxFileSize = 50 * 1024;

    private int maxMemSize = 4 * 1024;private File file ;

    public void init( ){// Get the file location where it would be stored.filePath =

    getServletContext().getInitParameter("file-upload");}public void doPost(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, java.io.IOException {

    // Check that we have a file upload requestisMultipart = ServletFileUpload.isMultipartContent(request);response.setContentType("text/html");java.io.PrintWriter out = response.getWriter( );

    if( !isMultipart ){out.println("");out.println("");out.println("Servlet upload");out.println("");out.println("");out.println("

    No file uploaded

    ");out.println("");out.println("");return;

    }DiskFileItemFactory factory = new DiskFileItemFactory();// maximum size that will be stored in memoryfactory.setSizeThreshold(maxMemSize);// Location to save data that is larger than maxMemSize.

    factory.setRepository(new File("c:\\temp"));

    // Create a new file upload handlerServletFileUpload upload = new ServletFileUpload(factory);// maximum file size to be uploaded.upload.setSizeMax( maxFileSize );

    try{// Parse the request to get file items.List fileItems = upload.parseRequest(request);

    // Process the uploaded file itemsIterator i = fileItems.iterator();

  • 8/10/2019 ServLet Tutorials

    22/36

    out.println("");out.println("");out.println("Servlet upload");out.println("");out.println("");while ( i.hasNext () ){

    FileItem fi = (FileItem)i.next();if ( !fi.isFormField () ){

    // Get the uploaded file parameters

    String fieldName = fi.getFieldName();String fileName = fi.getName();String contentType = fi.getContentType();boolean isInMemory = fi.isInMemory();long sizeInBytes = fi.getSize();// Write the fileif( fileName.lastIndexOf("\\") >= 0 ){

    file = new File( filePath +fileName.substring( fileName.lastIndexOf("\\"))) ;

    }else{file = new File( filePath +fileName.substring(fileName.lastIndexOf("\\")+1)) ;

    }fi.write( file ) ;out.println("Uploaded Filename: " + fileName + "
    ");

    }}out.println("");out.println("");

    }catch(Exception ex) {System.out.println(ex);

    }}public void doGet(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, java.io.IOException {

    throw new ServletException("GET method used with " +getClass( ).getName( )+": POST method required.");

    }

    }

    Compile and Running Servlet:

    Compile above servlet UploadServlet and create required entry in web.xml file as follows.

    UploadServletUploadServlet

    UploadServlet/UploadServlet

    Now try to upload files using the HTML form which you created above. When you would tryhttp://localhost:8080/UploadFile.htm, it would display following result which would help you uploading any file from

    your local machine.

    File Upload:Select a file to upload:

  • 8/10/2019 ServLet Tutorials

    23/36

    If your servelt script works fine, your file should be uploaded in c:\apache-tomcat-5.5.29\webapps\data\ directory.

    One of the most important advantages of using Servlet is that you can use most of the methods available in core Java. Thistutorial would take you through Java provided Dateclass which is available injava.utilpackage, this class encapsulates

    the current date and time.

    The Date class supports two constructors. The first constructor initializes the object with the current date and time.

    Date( )

    The following constructor accepts one argument that equals the number of milliseconds that have elapsed since midnight,January 1, 1970

    Date(long millisec)

    Once you have a Date object available, you can call any of the following support methods to play with dates:

    SN Methods with Description

    1boolean after(Date date)

    Returns true if the invoking Date object contains a date that is later than the one specified by date, otherwise, it returns false.

    2

    boolean before(Date date)

    Returns true if the invoking Date object contains a date that is earlier than the one specified by date, otherwise, it returns

    false.

    3Object clone( )

    Duplicates the invoking Date object.

    4

    int compareTo(Date date)

    Compares the value of the invoking object with that of date. Returns 0 if the values are equal. Returns a negative value if the

    invoking object is earlier than date. Returns a positive value if the invoking object is later than date.

    5int compareTo(Object obj)

    Operates identically to compareTo(Date) if obj is of class Date. Otherwise, it throws a ClassCastException.

    6

    boolean equals(Object date)

    Returns true if the invoking Date object contains the same time and date as the one specified by date, otherwise, it returns

    false.

    7long getTime( )

    Returns the number of milliseconds that have elapsed since January 1, 1970.

    8int hashCode( )

    Returns a hash code for the invoking object.

    9void setTime(long time)

    Sets the time and date as specified by time, which represents an elapsed time in milliseconds from midnight, January 1, 1970

  • 8/10/2019 ServLet Tutorials

    24/36

    10String toString( )

    Converts the invoking Date object into a string and returns the result.

    Getting Current Date & Time

    This is very easy to get current date and time in Java Servlet. You can use a simple Date object with toString()method toprint current date and time as follows:

    // Import required java librariesimport java.io.*;import java.util.Date;import javax.servlet.*;import javax.servlet.http.*;

    // Extend HttpServlet classpublic class CurrentDate extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    // Set response content typeresponse.setContentType("text/html");

    PrintWriter out = response.getWriter();String title = "Display Current Date & Time";Date date = new Date();String docType ="\n";out.println(docType +"\n" +"" + title + "\n" +"\n" +"" + title + "\n" +"" + date.toString() + "\n" +

    "");}}

    Now let us compile above servlet and create appropriate entries in web.xml and then call this servlet using URLhttp://localhost:8080/CurrentDate. This would produce following result:

    Display Current Date & Time

    Mon Jun 21 21:46:49 GMT+04:00 2010

    Try to refersh URL http://localhost:8080/CurrentDate and you would find difference in seconds everytime you wouldrefresh.

    Date Comparison:

    As I mentioned above you can use all the available Java methods in your Servlet. In case you need to compare two dates,following are the methods:

  • 8/10/2019 ServLet Tutorials

    25/36

    You can use getTime( ) to obtain the number of milliseconds that have elapsed since midnight, January 1, 1970,for both objects and then compare these two values.

    You can use the methods before( ), after( ), and equals( ). Because the 12th of the month comes before the 18th,for example, new Date(99, 2, 12).before(new Date (99, 2, 18)) returns true.

    You can use the compareTo( ) method, which is defined by the Comparable interface and implemented by Date.

    Date Formatting using SimpleDateFormat:

    SimpleDateFormat is a concrete class for formatting and parsing dates in a locale-sensitive manner. SimpleDateFormatallows you to start by choosing any user-defined patterns for date-time formatting.

    Let us modify above example as follows:

    // Import required java librariesimport java.io.*;import java.text.*;import java.util.Date;import javax.servlet.*;import javax.servlet.http.*;

    // Extend HttpServlet classpublic class CurrentDate extends HttpServlet {

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    // Set response content typeresponse.setContentType("text/html");

    PrintWriter out = response.getWriter();String title = "Display Current Date & Time";Date dNow = new Date( );SimpleDateFormat ft =new SimpleDateFormat ("E yyyy.MM.dd 'at' hh:mm:ss a zzz");String docType ="\n";out.println(docType +"\n" +"" + title + "\n" +"\n" +"" + title + "\n" +"" + ft.format(dNow) + "\n" +"");

    }}

    Compile above servlet once again and then call this servlet using URL http://localhost:8080/CurrentDate. This wouldproduce following result:

    Display Current Date & Time

    Mon 2010.06.21 at 10:06:44 PM GMT+04:00

    Simple DateFormat format codes:

  • 8/10/2019 ServLet Tutorials

    26/36

    To specify the time format use a time pattern string. In this pattern, all ASCII letters are reserved as pattern letters, whichare defined as the following:

    Character Description Example

    G Era designator AD

    y Year in four digits 2001

    M Month in year July or 07

    d Day in month 10

    h Hour in A.M./P.M. (1~12) 12

    H Hour in day (0~23) 22

    m Minute in hour 30

    s Second in minute 55

    S Millisecond 234

    E Day in week Tuesday

    D Day in year 360

    F Day of week in month 2 (second Wed. in July)

    w Week in year 40

    W Week in month 1

    a A.M./P.M. marker PM

    k Hour in day (1~24) 24

    K Hour in A.M./P.M. (0~11) 10

    z Time zone Eastern Standard Time

    ' Escape for text Delimiter

  • 8/10/2019 ServLet Tutorials

    27/36

    " Single quote `

    For a complete list of constant available methods to manipulate date, you can refer to standard Java documentation.

    Page redirection

    Page redirection is generally used when a document moves to a new location and we need to send the client to this newlocation or may be because of load balancing, or for simple randomization.

    The simplest way of redirecting a request to another page is using method sendRedirect()of response object. Followingis the signature of this method:

    public void HttpServletResponse.sendRedirect(String location)throws IOException

    This method sends back the response to the browser along with the status code and new page location. You can also usesetStatus() and setHeader() methods together to achieve the same:

    ....String site = "http://www.newpage.com" ;response.setStatus(response.SC_MOVED_TEMPORARILY);response.setHeader("Location", site);....

    Example:

    This example shows how a servlet performs page redirection to another location:

    import java.io.*;import java.sql.Date;import java.util.*;

    import javax.servlet.*;import javax.servlet.http.*;

    public class PageRedirect extends HttpServlet{

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    // Set response content typeresponse.setContentType("text/html");

    // New location to be redirectedString site = new String("http://www.photofuntoos.com");

    response.setStatus(response.SC_MOVED_TEMPORARILY);response.setHeader("Location", site);}

    }

    Now let us compile above servlet and create following entries in web.xml

    ....

    PageRedirectPageRedirect

  • 8/10/2019 ServLet Tutorials

    28/36

    PageRedirect/PageRedirect

    ....

    Now call this servlet using URL http://localhost:8080/PageRedirect. This would take you given URLhttp://www.photofuntoos.com.

    Hit Counter for a Web Page:

    Many times you would be interested in knowing total number of hits on a particular page of your website. It is very simple

    to count these hits using a servlet because the life cycle of a servlet is controlled by the container in which it runs.

    Following are the steps to be taken to implement a simple page hit counter which is based on Servlet Life Cycle:

    Initialize a global variable in init() method.

    Increase global variable every time either doGet() or doPost() method is called.

    If required, you can use a database table to store the value of global variable in destroy() method. This value canbe read inside init() method when servlet would be initialized next time. This step is optional.

    If you want to count only unique page hits with-in a session then you can use isNew() method to check if same

    page already have been hit with-in that session. This step is optional. You can display value of the global counter to show total number of hits on your web site. This step is also

    optional.

    Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will bereset.

    Example:

    This example shows how to implement a simple page hit counter:

    import java.io.*;

    import java.sql.Date;import java.util.*;import javax.servlet.*;import javax.servlet.http.*;

    public class PageHitCounter extends HttpServlet{

    private int hitCount;

    public void init(){

    // Reset hit counter.hitCount = 0;

    }

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    // Set response content typeresponse.setContentType("text/html");// This method executes whenever the servlet is hit// increment hitCounthitCount++;PrintWriter out = response.getWriter();String title = "Total Number of Hits";String docType ="\n";

  • 8/10/2019 ServLet Tutorials

    29/36

    out.println(docType +"\n" +"" + title + "\n" +"\n" +"" + title + "\n" +"" + hitCount + "\n" +"");

    }public void destroy(){

    // This is optional step but if you like you// can write hitCount value in your database.

    }}

    Now let us compile above servlet and create following entries in web.xml

    ....

    PageHitCounterPageHitCounter

    PageHitCounter/PageHitCounter

    ....

    Now call this servlet using URL http://localhost:8080/PageHitCounter. This would increase counter by one every timethis page gets refreshed and it would display following result:

    Total Number of Hits

    6

    Hit Counter for a Website:

    Many times you would be interested in knowing total number of hits on your whole website. This is also very simple inServlet and we can achieve this using filters.

    Following are the steps to be taken to implement a simple website hit counter which is based on Filter Life Cycle:

    Initialize a global variable in init() method of a filter.

    Increase global variable every time doFilter method is called.

    If required, you can use a database table to store the value of global variable in destroy() method of filter. This

    value can be read inside init() method when filter would be initialized next time. This step is optional.

    Here I'm assuming that the web container will not be restarted. If it is restarted or servlet destroyed, the hit counter will bereset.

    Example:

    This example shows how to implement a simple website hit counter:

  • 8/10/2019 ServLet Tutorials

    30/36

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

    public class SiteHitCounter implements Filter{

    private int hitCount;

    public void init(FilterConfig config)

    throws ServletException{// Reset hit counter.hitCount = 0;

    }

    public void doFilter(ServletRequest request,ServletResponse response,FilterChain chain)throws java.io.IOException, ServletException {

    // increase counter by onehitCount++;

    // Print the counter.System.out.println("Site visits count :"+ hitCount );

    // Pass request back down the filter chainchain.doFilter(request,response);

    }public void destroy(){

    // This is optional step but if you like you// can write hitCount value in your database.

    }}

    Now let us compile above servlet and create following entries in web.xml

    ....

    SiteHitCounterSiteHitCounter

    SiteHitCounter/*

    ....

    Now call any URL like URL http://localhost:8080/. This would increase counter by one every time any page gets a hit andit would display following message in the log:

    Site visits count : 1Site visits count : 2Site visits count : 3Site visits count : 4Site visits count : 5..................

    Auto Page Refresh

    Consider a webpage which is displaying live game score or stock market status or currency exchange ration. For all such

    type of pages, you would need to refresh your web page regularly using referesh or reload button with your browser.

  • 8/10/2019 ServLet Tutorials

    31/36

    Java Servlet makes this job easy by providing you a mechanism where you can make a webpage in such a way that itwould refresh automatically after a given interval.

    The simplest way of refreshing a web page is using method setIntHeader()of response object. Following is the signature

    of this method:

    public void setIntHeader(String header, int headerValue)

    This method sends back header "Refresh" to the browser along with an integer value which indicates time interval inseconds.

    Auto Page Refresh Example:

    This example shows how a servlet performs auto page refresh using setIntHeader()method to set Refreshheader.

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;import java.util.*;

    // Extend HttpServlet classpublic class Refresh extends HttpServlet {

    // Method to handle GET method request.public void doGet(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException

    {// Set refresh, autoload time as 5 secondsresponse.setIntHeader("Refresh", 5);

    // Set response content typeresponse.setContentType("text/html");

    // Get current time

    Calendar calendar = new GregorianCalendar();String am_pm;int hour = calendar.get(Calendar.HOUR);int minute = calendar.get(Calendar.MINUTE);int second = calendar.get(Calendar.SECOND);if(calendar.get(Calendar.AM_PM) == 0)am_pm = "AM";

    elseam_pm = "PM";

    String CT = hour+":"+ minute +":"+ second +" "+ am_pm;

    PrintWriter out = response.getWriter();String title = "Auto Page Refresh using Servlet";String docType =

    "\n";out.println(docType +"\n" +"" + title + "\n"+"\n" +"" + title + "\n" +"

    Current Time is: " + CT + "

    \n");

    }// Method to handle POST method request.public void doPost(HttpServletRequest request,

    HttpServletResponse response)throws ServletException, IOException {doGet(request, response);

  • 8/10/2019 ServLet Tutorials

    32/36

    }}

    Now let us compile above servlet and create following entries in web.xml

    ....

    RefreshRefresh

    Refresh/Refresh

    ....

    Now call this servlet using URL http://localhost:8080/Refresh which would display current system time after every 5seconds as follows. Just run the servlet and wait to see the result:

    Auto Page Refresh using Servlet

    Current Time is: 9:44:50 PM

    The web application structure involving the WEB-INF subdirectory is standard to all Java web applications and specified

    by the servlet API specification. Given a top-level directory name of myapp, Here is what this directory structure lookslike:

    /myapp/images/WEB-INF

    /classes/lib

    The WEB-INF subdirectory contains the application's deployment descriptor, named web.xml. All the HTML files live inthe top-level directory which is myapp. For admin user, you would find ROOT directory as parent directory as myapp.

    Creating Servlets in Packages:

    The WEB-INF/classes directory contains all the servlet classes and other class files, in a structure that matches theirpackage name. For example, If you have a fully qualified class name of com.myorg.MyServlet, then this servlet classmust be located in the following directory:

    /myapp/WEB-INF/classes/com/myorg/MyServlet.class

    Following is the example to create MyServlet class with a package name com.myorg

    // Name your packagepackage com.myorg;

    // Import required java librariesimport java.io.*;import javax.servlet.*;import javax.servlet.http.*;

    public class MyServlet extends HttpServlet {

  • 8/10/2019 ServLet Tutorials

    33/36

    private String message;

    public void init() throws ServletException{

    // Do required initializationmessage = "Hello World";

    }

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

    // Set response content typeresponse.setContentType("text/html");

    // Actual logic goes here.PrintWriter out = response.getWriter();out.println("" + message + "");

    }

    public void destroy(){

    // do nothing.}

    }

    Compiling Servlets in Packages:

    There is nothing much different to compile a class available in package. The simplest way is to keep your java file in fully

    qualified path, as mentioned above class would be kept in com.myorg. You would also need to add this directory inCLASSPATH.

    Assuming your environment is setup properly, go in /webapps/ROOT/WEB-INF/classesdirectory and compile MyServlet.java as follows:

    $ javac MyServlet.java

    If the servlet depends on any other libraries, you have to include those JAR files on your CLASSPATH as well. I haveincluded only servlet-api.jar JAR file because I'm not using any other library in Hello World program.

    This command line uses the built-in javac compiler that comes with the Sun Microsystems Java Software DevelopmentKit (JDK). For this command to work properly, you have to include the location of the Java SDK that you are using in the

    PATH environment variable.

    If everything goes fine, above compilation would produce MyServlet.classfile in the same directory. Next section wouldexplain how a compiled servlet would be deployed in production.

    Packaged Servlet Deployment:By default, a servlet application is located at the path /webapps/ROOT and the class filewould reside in /webapps/ROOT/WEB-INF/classes.

    If you have a fully qualified class name of com.myorg.MyServlet, then this servlet class must be located in WEB-

    INF/classes/com/myorg/MyServlet.class and you would need to create following entries in web.xmlfile located in/webapps/ROOT/WEB-INF/

    MyServletcom.myorg.MyServlet

  • 8/10/2019 ServLet Tutorials

    34/36

    MyServlet/MyServlet

    Above entries to be created inside ... tags available in web.xml file. There could be various entriesin this table already available, but never mind.

    You are almost done, now let us start tomcat server using \bin\startup.bat (on windows) or/bin/startup.sh (on Linux/Solaris etc.) and finally type http://localhost:8080/MyServlet

    in browser's address box. If everything goes fine, you would get following result:

    It is always difficult to testing/debugging a servlets. Servlets tend to involve a large amount of client/server interaction,making errors likely but hard to reproduce.

    Here are a few hints and suggestions that may aid you in your debugging.

    System.out.println()

    System.out.println() is easy to use as a marker to test whether a certain piece of code is being executed or not. We canprint out variable values as well. Additionally:

    Since the System object is part of the core Java objects, it can be used everywhere without the need to install anyextra classes. This includes Servlets, JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications.

    Compared to stopping at breakpoints, writing to System.out doesn't interfere much with the normal executionflow of the application, which makes it very valuable when timing is crucial.

    Following is the syntax to use System.out.println():

    System.out.println("Debugging message");

    All the messages generated by above syntax would be logged in web server log file.

    Message Logging:

    It is always great idea to use proper logging method to log all the debug, warning and error messages using a standardlogging method. I use log4Jto log all the messages.

    The Servlet API also provides a simple way of outputting information by using the log() method as follows:

    // Import required java librariesimport java.io.*;

    import javax.servlet.*;import javax.servlet.http.*;

    public class ContextLog extends HttpServlet {public void doGet(HttpServletRequest request,

    HttpServletResponse response) throws ServletException,java.io.IOException {

    String par = request.getParameter("par1");//Call the two ServletContext.log methodsServletContext context = getServletContext( );

    if (par == null || par.equals(""))//log version with Throwable parameter

  • 8/10/2019 ServLet Tutorials

    35/36

    context.log("No message received:",new IllegalStateException("Missing parameter"));

    elsecontext.log("Here is the visitor's message: " + par);

    response.setContentType("text/html");java.io.PrintWriter out = response.getWriter( );String title = "Context Log";String docType ="\n";

    out.println(docType +"\n" +"" + title + "\n" +"\n" +"" + title + "\n" +"Messages sent\n" +"");

    } //doGet}

    The ServletContext logs its text messages to the servlet container's log file. With Tomcat these logs are found in /logs.

    The log files do give an indication of new emerging bugs or the frequency of problems. For that reason it's good to use the

    log() function in the catch clause of exceptions which should normally not occur.

    Using JDB Debugger:

    You can debug servlets with the same jdb commands you use to debug an applet or an application.

    To debug a servlet, we can debug sun.servlet.http.HttpServer, then watch as HttpServer executes servlets in response to

    HTTP requests we make from a browser. This is very similar to how applets are debugged. The difference is that withapplets, the actual program being debugged is sun.applet.AppletViewer.

    Most debuggers hide this detail by automatically knowing how to debug applets. Until they do the same for servlets, youhave to help your debugger by doing the following:

    Set your debugger's classpath so that it can find sun.servlet.http.Http-Server and associated classes. Set your debugger's classpath so that it can also find your servlets and support classes, typically

    server_root/servlets and server_root/classes.

    You normally wouldn't want server_root/servlets in your classpath because it disables servlet reloading. This inclusion,however, is useful for debugging. It allows your debugger to set breakpoints in a servlet before the custom servlet loaderin HttpServer loads the servlet.

    Once you have set the proper classpath, start debugging sun.servlet.http.HttpServer. You can set breakpoints in whatever

    servlet you're interested in debugging, then use a web browser to make a request to the HttpServer for the given servlet(http://localhost:8080/servlet/ServletToDebug). You should see execution stop at your breakpoints.

    Using Comments:

    Comments in your code can help the debugging process in various ways. Comments can be used in lots of other ways in

    the debugging process.

    The Servlet uses Java comments and single line (// ...) and multiple line (/* ... */) comments can be used to temporarilyremove parts of your Java code. If the bug disappears, take a closer look at the code you just commented and find out the

    problem.

  • 8/10/2019 ServLet Tutorials

    36/36

    Client and Server Headers:

    Sometimes when a servlet doesn't behave as expected, it's useful to look at the raw HTTP request and response. If you'refamiliar with the structure of HTTP, you can read the request and response and see exactly what exactly is going withthose headers.

    Important Debugging Tips:

    Here is a list of some more debugging tips on servlet debugging:

    Be aware that server_root/classes doesn't reload and that server_root/servlets probably does.

    Ask a browser to show the raw content of the page it is displaying. This can help identify formatting problems. It'susually an option under the View menu.

    Make sure the browser isn't caching a previous request's output by forcing a full reload of the page. WithNetscape Navigator, use Shift-Reload; with Internet Explorer use Shift-Refresh.

    Verify that your servlet's init() method takes a ServletConfig parameter and calls super.init(config) right away.


Recommended