Search for notes by fellow students, in your own course and all over the country.

Browse our notes for titles which look like what you need, you can preview any of the notes via a sample of the contents. After you're happy these are the notes you're after simply pop them into your shopping cart.

My Basket

You have nothing in your shopping cart yet.

Title: discrete mathematics full notes (engineering) btech
Description: this PDF will provide you full notes of discrete mathematics subject ! it's easy way to understand critical solution in easy way ! try it

Document Preview

Extracts from the notes are below, to see the PDF you'll receive please use the links above


Java Servlets

About the Tutorial
Servlets provide a component-based, platform-independent method for building Webbased applications, without the performance limitations of CGI programs
...

This tutorial will teach you how to use Java Servlets to develop your web based
applications in simple and easy steps
...
After completing this tutorial you will find yourself at a
moderate level of expertise in using Java Servlets from where you can take yourself to
next levels
...
It will be
great if you have a basic understanding of web application and how internet works
...
Ltd
...
Ltd
...

We strive to update the contents of our website and tutorials as timely and as precisely
as possible, however, the contents may contain inaccuracies or errors
...
Ltd
...
If you discover any errors on our
website or in this tutorial, please notify us at contact@tutorialspoint
...
i
Audience
...
i
Table of Content
...


SERVLETS – OVERVIEW
...
2
Servlets Packages
...
2

2
...
3
Setting up Java Development Kit
...
3
Setting Up the CLASSPATH
...


SERVLETS – LIFE CYCLE
...
7
The service() Method
...
8
The doPost() Method
...
8
Architecture Diagram
...


SERVLETS – EXAMPLES
...
10
Compiling a Servlet
...
11

ii

Java Servlets

5
...
13
GET Method
...
13
Reading Form Data using Servlet
...
14
GET Method Example Using Form
...
16
Passing Checkbox Data to Servlet Program
...
20

6
...
24
Methods to read HTTP Header
...
27

7
...
30
Methods to Set HTTP Response Header
...
33

8
...
36
Methods to Set HTTP Status Code
...
39

9
...
41
Servlet Filter Methods
...
42
Servlet Filter Mapping in Web
...
43
Using Multiple Filters
...
44

iii

Java Servlets

10
...
46
web
...
46
Request Attributes – Errors/Exceptions
...
48

11
...
52
The Anatomy of a Cookie
...
53
Setting Cookies with Servlet
...
56
Delete Cookies with Servlet
...


SERVLETS – SESSION TRACKING
...
62
Hidden Form Fields
...
62
The HttpSession Object
...
64
Deleting Session Data
...


SERVLETS – DATABASE ACCESS
...
69
Create Data Records
...
70

14
...
74
Creating a File Upload Form
...
75
Compile and Running Servlet
...


SERVLET – HANDLING DATE
...
81
Date Comparison
...
82
Simple DateFormat Format Codes
...


SERVLETS – PAGE REDIRECTION
...


SERVLETS – HITS COUNTER
...
87

18
...
92
Auto Page Refresh Example
...


SERVLETS – SENDING EMAIL
...
95
Send an HTML Email
...
100
User Authentication Part
...


SERVLETS – PACKAGING
...
104
Compiling Servlets in Packages
...
106

21
...
107
System
...
println()
...
107
Using JDB Debugger
...
109
Client and Server Headers
...
109

22
...
111
Detecting Locale
...
113
Locale Specific Dates
...
115
Locale Specific Percentage
...


SERVLET – ANNOTATIONS
...
120
@WebInitParam
...
123

vi

1
...

Using Servlets, you can collect input from users through web page forms, present
records from a database or another source, and create web pages dynamically
...
But Servlets offer several advantages in comparison
with the CGI
...




Servlets execute within the address space of a Web server
...




Servlets are platform-independent because they are written in Java
...
So servlets are trusted
...
It can
communicate with applets, databases, or other software via the sockets and RMI
mechanisms that you have seen already
...


1

Java Servlets

Servlets Tasks
Servlets perform the following major tasks:


Read the explicit data sent by the clients (browsers)
...




Read the implicit HTTP request data sent by the clients (browsers)
...




Process the data and generate the results
...




Send the explicit data (i
...
, the document) to the clients (browsers)
...




Send the implicit HTTP response to the clients (browsers)
...
g
...


Servlets Packages
Java Servlets are Java classes run by a web server that has an interpreter that supports
the Java Servlet specification
...
servlet and javax
...
http packages,
which are a standard part of the Java's enterprise edition, an expanded version of the
Java class library that supports large-scale development projects
...
At the time of writing
this tutorial, the versions are Java Servlet 2
...
1
...
After you
install the servlet packages and add them to your computer's Classpath, you can compile
servlets with the JDK's Java compiler or any other current compiler
...
So
fasten your belt for a nice drive with Servlets
...


2

Java Servlets

2
...

Like any other Java program, you need to compile a servlet by using the Java compiler
javac and after compilation the servlet application, it would be deployed in a configured
environment to test and run
...

You can download SDK from Oracle's Java site: Java SE Downloads
...
Finally set PATH and JAVA_HOME environment variables to refer to
the directory that contains java and javac, typically java_install_dir/bin and
java_install_dir respectively
...
8
...
bat file
...
8
...
8
...
Then, you would update the
PATH value and press the OK button
...
), if the SDK is installed in /usr/local/jdk1
...
0_65 and you
use the C shell, you would put the following into your
...

setenv PATH /usr/local/jdk1
...
0_65/bin:$PATH
setenv JAVA_HOME /usr/local/jdk1
...
0_65
Alternatively, if you use an Integrated Development Environment (IDE) like Borland
JBuilder, Eclipse, IntelliJ IDEA, or Sun ONE Studio, compile and run a simple program to
confirm that the IDE knows where you installed Java
...
Some web
servers are freely downloadable and Tomcat is one of them
...
Here are the steps to setup Tomcat on
your machine:


Download latest version of Tomcat from http://tomcat
...
org/
...
For example in C:\apache-tomcat-8
...
28 on windows, or
/usr/local/apache-tomcat-8
...
289 on Linux/Unix and create CATALINA_HOME
environment variable pointing to these locations
...
bat

or

C:\apache-tomcat-8
...
28\bin\startup
...
) machine:
$CATALINA_HOME/bin/startup
...
0
...
sh
After startup, the default web applications included with Tomcat will be available by
visiting http://localhost:8080/
...
apache
...
0
...
) machine:
/usr/local/apache-tomcat-8
...
28/bin/shutdown
...

If you are running Windows, you need to put the following lines in your C:\autoexec
...

set CATALINA=C:\apache-tomcat-8
...
28
set CLASSPATH=%CATALINA%\common\lib\servlet-api
...
Then, you would update the CLASSPATH value and
press the OK button
...
), if you are using the C shell, you would put the following
lines into your
...

setenv CATALINA=/usr/local/apache-tomcat-8
...
28
5

Java Servlets

setenv CLASSPATH $CATALINA/common/lib/servlet-api
...


6

3
...
The following are the paths followed by a servlet


The servlet is initialized by calling the init () method
...




The servlet is terminated by calling the destroy() method
...


Now let us discuss the life cycle methods in detail
...
It is called only when the servlet is created, and not
called for any user requests afterwards
...

The servlet is normally created when a user first invokes a URL corresponding to the
servlet, but you can also specify that the servlet be loaded when the server is first
started
...
The init() method simply creates or loads some data that will be used
throughout the life of the servlet
...

}

The service() Method
The service() method is the main method to perform the actual task
...
e
...

Each time the server receives a request for a servlet, the server spawns a new thread
and calls service
...
) and calls doGet, doPost, doPut, doDelete, etc
...


7

Java Servlets
Here is the signature of this method:
public void service(ServletRequest request,
ServletResponse response)
throws ServletException, IOException{
}
The service () method is called by the container and service method invokes doGe,
doPost, doPut, doDelete, etc
...
So you have nothing to do with
service() method but you override either doGet() or doPost() depending on what type of
request you receive from the client
...
Here is the signature of these two methods
...

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException {
// Servlet code
}

The doPost() Method
A POST request results from an HTML form that specifically lists POST as the METHOD
and it should be handled by doPost() method
...
This
method gives your servlet a chance to close database connections, halt background
threads, write cookie lists or hit counts to disk, and perform other such cleanup
activities
...

The destroy method definition looks like this:
8

Java Servlets

public void destroy() {
// Finalization code
...



First the HTTP requests coming to the server are delegated to the servlet
container
...




Then the servlet container handles multiple requests by spawning multiple
threads, each thread executing the service() method of a single instance of the
servlet
...
Servlets – Examples

Java Servlets

Servlets are Java classes which service HTTP requests and implement the
javax
...
Servlet interface
...
servlet
...
HttpServlet, an abstract class that implements the Servlet
interface and is specially designed to handle HTTP requests
...
io
...
servlet
...
servlet
...
*;

// Extend HttpServlet class
public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException
{
// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
// Set response content type
response
...

PrintWriter out = response
...
println("

" + message + "

");
}

public void destroy()
{
// do nothing
...
java with the code shown above
...
This path location
must be added to CLASSPATH before proceeding further
...
java as follows:
$ javac HelloWorld
...
I have included only servlet-api
...

This command line uses the built-in javac compiler that comes with the Sun
Microsystems Java Software Development Kit (JDK)
...

If everything goes fine, above compilation would produce HelloWorld
...
Next section would explain how a compiled servlet would be deployed in
production
...

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

For
now,
let
us
copy
HelloWorld
...
xml file
located in /webapps/ROOT/WEB-INF/

HelloWorld
11

Java Servlets

HelloWorld



HelloWorld
/HelloWorld

Above entries to be created inside
...
xml
file
...

You are almost done, now let us start tomcat server using \bin\startup
...
sh
(on
Linux/Solaris
etc
...
If everything goes
fine, you would get the following result:

12

5
...
The browser
uses two methods to pass this information to web server
...


GET Method
The GET method sends the encoded user information appended to the page request
...
test
...
Never use the
GET method if you have password or other sensitive information to pass to the server
...

This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable and Servlet handles this type of requests using
doGet() method
...
This packages the information in exactly the same way as GET method,
but instead of sending it as a text string after a ? (question mark) in the URL it sends it
as a separate message
...
Servlet handles this
type of requests using doPost() method
...
getParameter() method to get the value of a
form parameter
...




getParameterNames(): Call this method if you want a complete list of all
parameters in the current request
...

http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI
Given below is the HelloForm
...
We are going to use getParameter() method which makes it very easy to
access passed information:
// Import required java libraries
import java
...
*;
import javax
...
*;
import javax
...
http
...
setContentType("text/html");

PrintWriter out = response
...
0 " +
"transitional//en\">\n";
out
...
getParameter("first_name") + "\n" +
"

  • Last Name: "
    14

    Java Servlets

    + request
    ...
    java as follows:
    $ javac HelloForm
    ...
    class file
    ...
    xml file
    located in /webapps/ROOT/WEB-INF/

    HelloForm
    HelloForm



    HelloForm
    /HelloForm

    Now type http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI in your
    browser's Location:box and make sure you already started tomcat server, before firing
    above command in the browser
    ...

    We are going to use same Servlet HelloForm to handle this imput
    ...
    htm and put it in /webapps/ROOT
    directory
    ...
    htm, here is the actual output of the above form
    ...
    Based on the input provided, it will
    generate similar result as mentioned in the above example
    ...
    Below is HelloForm
    ...

    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...

    16

    Java Servlets

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set response content type
    response
    ...
    getWriter();
    String title = "Using GET Method to Read Form Data";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + title + "

    \n" +
    "
      \n" +
      "

    • First Name: "

      + request
      ...
      getParameter("last_name") + "\n" +
      "
    \n" +
    "");
    }
    // Method to handle POST method request
    ...
    htm with the POST
    method as follows:
    17

    Java Servlets




    First Name:


    Last Name:




    Here is the actual output of the above form, Try to enter First and Last Name and then
    click submit button to see the result on your local machine where tomcat is running
    ...


    Passing Checkbox Data to Servlet Program
    Checkboxes are used when more than one option is required to be selected
    ...
    htm, for a form with two checkboxes



    Maths

    /> Physics


    Chemistry




    The result of this code is the following form

    18

    Java Servlets

    Maths

    Physics

    Chemistry Select Subject

    Selected Subject

    Given below is the CheckBox
    ...

    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set response content type
    response
    ...
    getWriter();
    String title = "Reading Checkbox Data";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + title + "

    \n" +
    "
      \n" +
      "

    • Maths Flag : : "

      + request
      ...
      getParameter("physics") + "\n" +
      19

      Java Servlets

      "

    • Chemistry Flag: : "

      + request
      ...

      public void doPost(HttpServletRequest request,
      HttpServletResponse response)
      throws ServletException, IOException {
      doGet(request, response);
      }
      }
      For the above example, it would display following result:

      Reading Checkbox Data

      Maths Flag : : on

      Physics Flag: : null

      Chemistry Flag: : on

      Reading All Form Parameters
      Following is the generic example which uses getParameterNames() method of
      HttpServletRequest to read all the available form parameters
      ...

      Once we have an Enumeration, we can loop down the Enumeration in standard way by,
      using hasMoreElements() method to determine when to stop and using nextElement()
      method to get each parameter name
      ...
      io
      ...
      servlet
      ...
      servlet
      ...
      *;
      import java
      ...
      *;

      // Extend HttpServlet class
      public class ReadParams extends HttpServlet {

      // Method to handle GET method request
      ...
      setContentType("text/html");

      PrintWriter out = response
      ...
      0 " +
      "transitional//en\">\n";
      out
      ...
      getParameterNames();

      while(paramNames
      ...
      nextElement();
      out
      ...
      getParameterValues(paramName);
      // Read single valued data
      if (paramValues
      ...
      length() == 0)
      out
      ...
      println(paramValue);
      } else {
      // Read multiple valued data
      out
      ...
      length; i++) {
      out
      ...
      println("
    ");
    }
    }
    out
    ...

    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    }
    }
    Now, try the above servlet with the following form:



    Maths

    /> Physics

    Chem


    22

    Java Servlets



    Now calling servlet using the above form would generate the following result:

    Reading All Form Parameters
    Param

    Value(s)

    maths

    on

    chemistry

    on

    You Cccdtry the above servlet to read any other form's data having other objects like text
    can
    box, radio button or drop down box etc
    ...
    Servlets – Client HTTP Request

    When a browser requests for a web page, it sends lot of information to the web server
    which cannot be read directly because this information travel as a part of header of HTTP
    request
    ...

    Following is the important header information which comes from browser side and you
    would use very frequently in web programming:
    Header

    Description

    Accept

    This header specifies the MIME types that the browser or
    other clients can handle
    ...


    Accept-Charset

    This header specifies the character sets the browser can use
    to display the information
    ...


    Accept-Encoding

    This header specifies the types of encodings that the
    browser knows how to handle
    ...


    Accept-Language

    This header specifies the client's preferred languages in
    case the servlet can produce results in more than one
    language
    ...


    Authorization

    This header is used by clients to identify themselves when
    accessing password-protected Web pages
    ...
    Persistent connections permit
    the client or other browser to retrieve multiple files with a
    single request
    ...


    Cookie

    This header returns cookies to servers that previously sent
    them to the browser
    ...


    If-Modified-Since

    This header indicates that the client wants the page only if it
    has been changed after the specified date
    ...

    24

    Java Servlets

    If-Unmodified-Since

    This header is the reverse of If-Modified-Since; it specifies
    that the operation should succeed only if the document is
    older than the specified date
    ...

    For example, if you are at Web page 1 and click on a link to
    Web page 2, the URL of Web page 1 is included in the
    Referrer header when the browser requests Web page 2
    ...


    Methods to read HTTP Header
    There are following methods which can be used to read HTTP header in your servlet
    program
    ...

    S
    ...


    Method & Description

    1

    Cookie[] getCookies()
    Returns an array containing all of the Cookie objects the client sent with this
    request
    ...


    3

    Enumeration getHeaderNames()
    Returns an enumeration of all the header names this request contains
    ...


    5

    HttpSession getSession()
    Returns the current session associated with this request, or if the request does
    not have a session, creates one
    ...


    7

    Locale getLocale()
    Returns the preferred Locale that the client will accept content in, based on the
    Accept-Language header
    ...


    9

    ServletInputStream getInputStream()
    Retrieves the body of the request as binary data using a ServletInputStream
    ...


    11

    String getCharacterEncoding()
    Returns the name of the character encoding used in the body of this request
    ...


    13

    String getContextPath()
    Returns the portion of the request URI that indicates the context of the request
    ...


    15

    String getMethod()
    Returns the name of the HTTP method with which this request was made, for
    example, GET, POST, or PUT
    ...


    17

    String getPathInfo()
    Returns any extra path information associated with the URL the client sent when
    it made this request
    ...


    19

    String getQueryString()
    Returns the query string that is contained in the request URL after the path
    ...


    21

    String getRemoteHost()
    Returns the fully qualified name of the client that sent the request
    ...


    23

    String getRequestURI()
    Returns the part of this request's URL from the protocol name up to the query
    string in the first line of the HTTP request
    ...


    25

    String getServletPath()
    Returns the part of this request's URL that calls the JSP
    ...


    27

    boolean isSecure()
    Returns a Boolean indicating whether this request was made using a secure
    channel, such as HTTPS
    ...


    29

    int getIntHeader(String name)
    Returns the value of the specified request header as an int
    ...


    HTTP Header Request Example
    Following is the example which uses getHeaderNames() method of HttpServletRequest
    to read the HTTP header information
    ...

    Once we have an Enumeration, we can loop down the Enumeration in the standard
    manner, using hasMoreElements() method to determine when to stop and using
    nextElement() method to get each parameter name
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    *;

    // Extend HttpServlet class
    public class DisplayHeader extends HttpServlet {

    // Method to handle GET method request
    ...
    setContentType("text/html");

    PrintWriter out = response
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...
    getHeaderNames();

    while(headerNames
    ...
    nextElement();
    out
    ...
    getHeader(paramName);
    out
    ...
    println("\n");
    }
    // Method to handle POST method request
    ...
    0 (compatible; MSIE 7
    ...
    1;
    Trident/4
    ...
    2; MS-RTC LM 8)

    accept-encoding

    gzip, deflate

    host

    localhost:8080

    connection

    Keep-Alive

    cache-control

    no-cache

    29

    Java Servlets

    7
    ...
    A typical response looks like this:
    HTTP/1
    ...


    ...

    (Blank Line)
    ...



    ...
    1 in the example), a status code
    (200 in the example), and a very short message corresponding to the status code (OK in
    the example)
    ...
    1 response headers which go back to
    the browser from web server side and you would use them very frequently in web
    programming:
    Header

    Description

    Allow

    This header specifies the request methods (GET, POST, etc
    ...


    Cache-Control

    This header specifies the circumstances in which the
    response document can safely be cached
    ...
    Public means document is
    cacheable, Private means document is for a single user and
    can only be stored in private (non-shared) caches and nocache means document should never be cached
    ...
    A value of close instructs the
    browser not to use persistent HTTP connections and keepalive means using persistent connections
    ...


    Content-Encoding

    This header specifies the way in which the page was encoded
    during transmission
    ...
    For example en, en-us, ru, etc
    ...

    This information is needed only if the browser is using a
    persistent (keep-alive) HTTP connection
    ...


    Expires

    This header specifies the time at which the content should be
    considered out-of-date and thus no longer be cached
    ...

    The client can then cache the document and supply a date by
    an If-Modified-Since request header in later requests
    ...
    This notifies the browser of the
    document address
    ...


    Refresh

    This header specifies how soon the browser should ask for an
    updated page
    ...


    Retry-After

    This header can be used in conjunction with a 503 (Service
    Unavailable) response to tell the client how soon it can repeat
    its request
    ...


    31

    Java Servlets

    Methods to Set HTTP Response Header
    There are following methods which can be used to set HTTP response header in your
    servlet program
    ...

    S
    ...

    1
    2

    3

    Method & Description
    String encodeRedirectURL(String url)
    Encodes the specified URL for use in the sendRedirect method or, if encoding is
    not needed, returns the URL unchanged
    ...

    boolean containsHeader(String name)
    Returns a Boolean indicating whether the named response header has already
    been set
    ...


    5

    void addCookie(Cookie cookie)
    Adds the specified cookie to the response
    ...


    7

    void addHeader(String name, String value)
    Adds a response header with the given name and value
    ...


    9

    void flushBuffer()
    Forces any content in the buffer to be written to the client
    ...


    11

    void resetBuffer()
    Clears the content of the underlying buffer in the response without clearing
    headers or status code
    ...


    13
    14
    15
    16

    void sendError(int sc, String msg)
    Sends an error response to the client using the specified status
    ...

    void setBufferSize(int size)
    Sets the preferred buffer size for the body of the response
    ...

    void setContentLength(int len)
    Sets the length of the content body in the response In HTTP servlets, this
    method sets the HTTP Content-Length header
    ...

    void setDateHeader(String name, long date)
    Sets a response header with the given name and date-value
    ...

    void setIntHeader(String name, int value)
    Sets a response header with the given name and integer value
    ...

    void setStatus(int sc)
    Sets the status code for this response
    ...

    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    util
    ...

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set refresh, autoload time as 5 seconds
    response
    ...
    setContentType("text/html");
    33

    Java Servlets

    // Get current time
    Calendar calendar = new GregorianCalendar();
    String am_pm;
    int hour = calendar
    ...
    HOUR);
    int minute = calendar
    ...
    MINUTE);
    int second = calendar
    ...
    SECOND);
    if(calendar
    ...
    AM_PM) == 0)
    am_pm = "AM";
    else
    am_pm = "PM";

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

    PrintWriter out = response
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...

    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    }
    }

    34

    Java Servlets
    Now calling the above servlet would display current system time after every 5 seconds
    as follows
    ...
    Servlets – Http Status Codes

    The format of the HTTP request and HTTP response messages are similar and will have
    following structure:


    An initial status line + CRLF ( Carriage Return + Line Feed i
    ...
    New Line )



    Zero or more header lines + CRLF



    A blank line, i
    ...
    , a CRLF



    An optional message body like file, query data or query output
    ...
    1 200 OK
    Content-Type: text/html
    Header2:
    ...

    HeaderN:
    ...
    >


    ...



    The status line consists of the HTTP version (HTTP/1
    ...

    Following is a list of HTTP status codes and associated messages that might be returned
    from the Web Server:
    Code

    Message

    Description

    100

    Continue

    Only a part of the request has been received by
    the server, but as long as it has not been
    rejected, the client should continue with the
    request

    101

    Switching Protocols

    The server switches protocol
    ...


    203

    Non-authoritative
    Information

    204

    No Content

    205

    Reset Content

    206

    Partial Content

    300

    Multiple Choices

    A link list
    ...
    Maximum five addresses

    301

    Moved Permanently

    The requested page has moved to a new url

    302

    Found

    The requested page has moved temporarily to
    a new url

    303

    See Other

    The requested page can be found under a
    different url

    304

    Not Modified

    305

    Use Proxy

    306

    Unused

    This code was used in a previous version
    ...


    307

    Temporary Redirect

    The requested page has moved temporarily to
    a new url
    ...


    405

    Method Not Allowed

    The method specified in the request is not
    allowed
    ...


    407

    Proxy Authentication
    Required

    You must authenticate with a proxy server
    before this request can be served
    ...


    409

    Conflict

    The request could not be completed because of
    a conflict
    ...


    411

    Length Required

    The "Content-Length" is not defined
    ...


    412

    Precondition Failed

    The precondition given in the request evaluated
    to false by the server
    ...


    414

    Request-url Too Long

    The server will not accept the request, because
    the url is too long
    ...


    415

    Unsupported Media Type

    The server will not accept the request, because
    the media type is not supported
    ...
    The server
    met an unexpected condition

    501

    Not Implemented

    The request was not completed
    ...


    502

    Bad Gateway

    The request was not completed
    ...
    The server is
    temporarily overloading or down
    ...


    505

    HTTP Version Not Supported

    The server does not support the "http protocol"
    version
    ...

    These methods are available with HttpServletResponse object
    ...
    N
    ...
    The setStatus method takes an int
    (the status code) as an argument
    ...

    public void sendRedirect(String url)

    1

    2

    This method generates a 302 response along with a Location header giving the
    URL of the new document
    ...


    HTTP Status Code Example
    Following is the example which would send a 407 error code to the client browser and
    browser would show you "Need authentication!!!" message
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    *;

    // Extend HttpServlet class
    public class showError extends HttpServlet {

    // Method to handle GET method request
    ...

    response
    ...

    39

    Java Servlets

    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    }
    }
    Now calling the above servlet would display the following result:

    HTTP Status 407 - Need authentication!!!
    type Status report

    messageNeed authentication!!!

    descriptionThe client must first authenticate itself with the proxy (Need
    authentication!!!)
    ...
    5
    ...
    Servlets – Writing Filters

    Java Servlets

    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
    ...


    There 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
    ...

    When the web container starts up your web application, it creates an instance of each
    filter that you have declared in the deployment descriptor
    ...


    Servlet Filter Methods
    A filter is simply a Java class that implements the javax
    ...
    Filter interface
    ...
    servlet
    ...
    N
    ...

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


    41

    Java Servlets

    Servlet Filter – Example
    Following is the Servlet Filter Example that would print the clients IP address and current
    date time
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    *;

    // Implements Filter class
    public class LogFilter implements Filter
    public void

    {

    init(FilterConfig config)
    throws ServletException{

    // Get init parameter
    String testParam = config
    ...
    out
    ...
    io
    ...

    String ipAddress = request
    ...

    System
    ...
    println("IP "+ ipAddress + ", Time "
    + new Date()
    ...
    doFilter(request,response);
    }
    public void destroy( ){
    42

    Java Servlets

    /* Called before the Filter instance is removed
    from service by the web container*/
    }
    }
    Compile LogFilter
    ...


    Servlet Filter Mapping in Web
    ...
    Create the following entry for filter
    tag in the deployment descriptor file web
    ...
    You can specicy a particular servlet path if you want to apply filter on few
    servlets only
    ...
    You can use Log4J logger to log above log in a separate file
    ...

    Consider, you define two filters AuthenFilter and LogFilter
    ...
    xml determines the order in which the web
    container applies the filter to the servlet
    ...
    xml file
    ...
    Servlets – Exception Handling

    When a servlet throws an exception, the web container searches the configurations in
    web
    ...

    You would have to use the error-page element in web
    ...


    web
    ...
    Following would be the entry created in web
    ...



    ErrorHandler
    ErrorHandler



    ErrorHandler
    /ErrorHandler




    404
    /ErrorHandler


    403
    /ErrorHandler





    46

    Java Servlets

    javax
    ...
    ServletException

    /ErrorHandler



    java
    ...
    IOException

    /ErrorHandler

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

    java
    ...
    Throwable

    /ErrorHandler

    Following are the points to be noted about above web
    ...
    xml
    ...




    If the web application throws either ServletException or IOException, then the
    web container invokes the /ErrorHandler servlet
    ...
    Above example is very much generic and hope it serve the purpose to
    explain you the basic concept
    ...

    S
    ...

    1
    2

    Attribute & Description
    javax
    ...
    error
    ...
    lang
    ...

    javax
    ...
    error
    ...
    lang
    ...

    47

    Java Servlets
    javax
    ...
    error
    ...
    lang
    ...

    javax
    ...
    error
    ...
    lang
    ...

    javax
    ...
    error
    ...

    javax
    ...
    error
    ...
    lang
    ...


    Error Handler Servlet – Example
    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 libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    util
    ...

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Analyze the servlet exception
    Throwable throwable = (Throwable)
    request
    ...
    servlet
    ...
    exception");
    Integer statusCode = (Integer)
    request
    ...
    servlet
    ...
    status_code");
    String servletName = (String)
    request
    ...
    servlet
    ...
    servlet_name");
    if (servletName == null){
    servletName = "Unknown";
    48

    Java Servlets

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

    // Set response content type
    response
    ...
    getWriter();
    String title = "Error/Exception Information";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n");

    if (throwable == null && statusCode == null){
    out
    ...
    println("Please return to the response
    ...
    ");
    }else if (statusCode != null){
    out
    ...
    println("

    Error information

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

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

    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    }
    }
    Compile ErrorHandler
    ...

    Let us add the following configuration in web
    ...
    lang
    ...
    For example, if you type a wrong URL then it would display the
    following result:
    The status code : 404
    The above code may not work with some web browsers
    ...


    51

    Java Servlets

    11
    ...
    Java Servlets transparently supports HTTP cookies
    ...
    For example name, age, or
    identification number etc
    ...




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


    The Anatomy of a Cookie
    Cookies are usually set in an HTTP header (although JavaScript can also set a cookie
    directly on a browser)
    ...
    1 200 OK
    Date: Fri, 04 Feb 2000 21:03:38 GMT
    Server: Apache/1
    ...
    9 (UNIX) PHP/4
    ...
    com
    Connection: close
    Content-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 expires field is an
    instruction to the browser to "forget" the cookie after the given time and date
    ...
    If the user points the browser at any page that matches the path and
    domain of the cookie, it will resend the cookie to the server
    ...
    0
    Connection: Keep-Alive
    User-Agent: Mozilla/4
    ...
    2
    ...
    demon
    ...
    uk:1126
    Accept: image/gif, */*
    Accept-Encoding: gzip
    Accept-Language: en
    Accept-Charset: iso-8859-1,*,utf-8
    Cookie: name=xyz
    A servlet will then have access to the cookie through
    request
    ...


    the

    request

    method

    Servlet Cookies Methods
    Following is the list of useful methods which you can use while manipulating cookies in
    servlet
    ...
    N
    ...
    com
    ...
    com
    ...
    If you don't set this, the cookie will last only for the current session
    ...

    public String getName()
    This method returns the name of the cookie
    ...

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

    public void setPath(String uri)
    This method sets the path to which this cookie applies
    ...

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

    public void setComment(String purpose)
    This method specifies a comment that describes a cookie's purpose
    ...

    public String getComment()
    53

    Java Servlets
    This method returns the comment describing the purpose of this cookie, or null
    if the cookie has no comment
    ...

    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
    ...

    cookie
    ...
    addCookie to add cookies in the HTTP response header as follows:

    You

    use

    response
    ...

    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...

    Cookie firstName = new Cookie("first_name",
    54

    Java Servlets

    request
    ...
    getParameter("last_name"));

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

    response
    ...
    addCookie( lastName );

    // Set response content type
    response
    ...
    getWriter();
    String title = "Setting Cookies Example";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + title + "

    \n" +
    "
      \n" +
      "

    • First Name: "

      + request
      ...
      getParameter("last_name") + "\n" +
      "
    \n" +
    "");
    }
    }
    Compile the above servlet HelloForm and create appropriate entry in web
    ...

    55

    Java Servlets




    First Name:


    Last Name:




    Keep above HTML content in a file Hello
    ...

    When
    you
    would
    access
    http://localhost:8080/Hello
    ...

    First Name:
    Last Name:

    Submit

    Try to enter First Name and Last Name and then click submit button
    ...

    Next section would explain you how you would access these cookies back in your web
    application
    ...
    servlet
    ...
    Cookie objects by
    calling the getCookies( ) method of HttpServletRequest
    ...


    Example
    Let us read cookies which we have set in previous example:
    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    getCookies();

    // Set response content type
    response
    ...
    getWriter();
    String title = "Reading Cookies Example";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" );
    if( cookies != null ){
    out
    ...
    length; i++){
    cookie = cookies[i];
    out
    ...
    getName( ) + ",

    ");

    out
    ...
    getValue( )+"
    ");
    }
    }else{
    out
    ...
    println("");
    out
    ...
    xml file
    ...
    If you want to delete a cookie then you simply need to
    follow up following three steps:


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




    Add this cookie back into response header
    ...

    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    getCookies();

    // Set response content type
    response
    ...
    getWriter();
    String title = "Delete Cookies Example";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" );
    if( cookies != null ){
    out
    ...
    length; i++){
    cookie = cookies[i];
    if((cookie
    ...
    compareTo("first_name") == 0 ){
    cookie
    ...
    addCookie(cookie);
    out
    ...
    getName( ) + "
    ");
    }
    out
    ...
    getName( ) + ",

    ");

    out
    ...
    getValue( )+"
    ");
    }
    }else{
    out
    ...
    println("");
    out
    ...
    xml file
    ...
    Start at the Tools menu and
    select Internet Options
    ...


    60

    Java Servlets

    61

    Java Servlets

    12
    ...

    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
    ...


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

    This entry means that, when the form is submitted, the specified name and value are
    automatically included in the GET or POST data
    ...

    This could be an effective way of keeping track of the session but clicking on a regular
    (
    ...


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

    URL rewriting is a better way to maintain sessions and it works even when browsers
    don't support cookies
    ...


    62

    Java Servlets

    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 session persists for a specified time period, across more than one
    connection or page request from the user
    ...
    getSession();
    You need to call request
    ...
    Here is a summary of the important methods available through HttpSession
    object:
    S
    ...


    Method & Description
    public Object getAttribute(String name)

    1

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

    public long getCreationTime()

    3

    This method returns the time when this session was created, measured in
    milliseconds since midnight January 1, 1970 GMT
    ...

    public long getLastAccessedTime()
    This method returns the last accessed time of the session, in the format of
    milliseconds since midnight January 1, 1970 GMT
    ...

    public void invalidate()

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

    63

    Java Servlets
    public void removeAttribute(String name)
    9

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

    public void setMaxInactiveInterval(int interval)
    11

    This method specifies the time, in seconds, between client requests before the
    servlet container will invalidate this session
    ...
    We would associate a new session with the
    request if one does not already exist
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    *;

    // 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
    ...
    getSession(true);
    // Get session creation time
    ...
    getCreationTime());
    // Get last access time of this web page
    ...
    getLastAccessedTime());

    String title = "Welcome Back to my website";
    Integer visitCount = new Integer(0);
    String visitCountKey = new String("visitCount");
    64

    Java Servlets

    String userIDKey = new String("userID");
    String userID = new String("ABCD");

    // Check if this is new comer on your web page
    ...
    isNew()){
    title = "Welcome to my website";
    session
    ...
    getAttribute(visitCountKey);
    visitCount = visitCount + 1;
    userID = (String)session
    ...
    setAttribute(visitCountKey,

    visitCount);

    // Set response content type
    response
    ...
    getWriter();

    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + title + "

    \n" +
    "

    Session Infomation

    \n" +
    "\n" +
    "\n" +
    "

    \n" +

    "\n" +
    "

    \n" +

    "

    Session infovalue
    id" + session
    ...
    xml file
    ...


    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

    Number of visits

    0

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


    Remove a particular attribute: You can call public void removeAttribute(String
    name) method to delete the value associated with a particular key
    ...




    Setting Session timeout: You can call public void setMaxInactiveInterval(int
    interval) method to set the timeout for a session individually
    ...
    4, you can call logout to
    log the client out of the Web server and invalidate all sessions belonging to all the
    users
    ...
    xml Configuration: If you are using Tomcat, apart from the above
    mentioned methods, you can configure session time out in web
    ...



    15


    67

    Java Servlets
    The timeout is expressed as minutes, and overrides the default timeout which is 30
    minutes in Tomcat
    ...
    So if your session is configured in web
    ...


    68

    Java Servlets

    13
    ...
    Before
    starting with database access through a servlet, make sure you have proper JDBC
    environment setup along with a database
    ...

    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 Employees table in TEST database, use the following steps:

    Step 1
    Open a Command Prompt and change to the installation directory as follows:
    C:\>
    C:\>cd Program Files\MySQL\bin
    C:\Program Files\MySQL\bin>

    Step 2
    Login to database as follows
    C:\Program Files\MySQL\bin>mysql -u root -p
    Enter password: ********
    mysql>

    Step 3
    Create table Employee in TEST database as follows:
    mysql> use TEST;
    mysql> create table Employees
    (
    id int not null,
    age int not null,
    first varchar (255),
    last varchar (255)
    69

    Java Servlets

    );
    Query OK, 0 rows 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 (103, 28, 'Sumit', 'Mittal');
    Query OK, 1 row affected (0
    ...

    // Loading required libraries
    import java
    ...
    *;
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    sql
    ...
    mysql
    ...
    Driver";
    static final String DB_URL="jdbc:mysql://localhost/TEST";

    //

    Database credentials

    static final String USER = "root";
    static final String PASS = "password";

    // Set response content type
    response
    ...
    getWriter();
    String title = "Database Result";
    String stmt = null;
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + title + "

    \n");
    try{
    // Register JDBC driver
    Class
    ...
    mysql
    ...
    Driver");

    // Open a connection
    conn = DriverManager
    ...
    createStatement();
    String sql;
    sql = "SELECT id, first, last, age FROM Employees";
    ResultSet rs = stmt
    ...
    next()){
    //Retrieve by column name
    int id

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

    //Display values
    out
    ...
    println(", Age: " + age + "
    ");
    out
    ...
    println(", Last: " + last + "
    ");
    }
    out
    ...
    close();
    stmt
    ...
    close();
    }catch(SQLException se){
    //Handle errors for JDBC
    se
    ...
    forName
    e
    ...
    close();
    }catch(SQLException se2){
    }// nothing we can do
    try{
    if(conn!=null)
    conn
    ...
    printStackTrace();
    }//end finally try
    } //end try
    }
    }
    Now let us compile above servlet and create following entries in web
    ...


    DatabaseAccess
    DatabaseAccess



    DatabaseAccess
    /DatabaseAccess


    ...
    Servlets – File Uploading

    Java Servlets

    A Servlet can be used with an HTML form tag to allow users to upload files to the server
    ...


    Creating a File Upload Form
    The following HTM code below creates an uploader form
    ...




    The form enctype attribute should be set to multipart/form-data
    ...
    Following example is using UploadServlet servlet
    to upload file
    ...
    /> tag with attribute
    type="file"
    ...
    The browser associates a Browse
    button with each of them
    ...


    Writing Backend Servlet
    Following is the servlet UploadServlet which would take care of accepting uploaded file
    and to store it in directory /webapps/data
    ...
    xml as follows:



    ...
    0
    ...


    Following is the source code for UploadServlet which can handle multiple file uploading
    at a time
    ...
    x
    ...
    jar file in your classpath
    ...
    apache
    ...




    FileUpload depends on Commons IO, so make sure you have the latest version of
    commons-io-x
    ...
    jar file in your classpath
    ...
    apache
    ...

    75

    Java Servlets


    While testing following example, you should upload a file which has less size than
    maxFileSize otherwise file would not be uploaded
    ...
    0
    ...


    c:\temp

    and

    c:\apache-tomcat-

    // Import required java libraries
    import java
    ...
    *;
    import java
    ...
    *;

    import javax
    ...
    ServletConfig;
    import javax
    ...
    ServletException;
    import javax
    ...
    http
    ...
    servlet
    ...
    HttpServletRequest;
    import javax
    ...
    http
    ...
    apache
    ...
    fileupload
    ...
    apache
    ...
    fileupload
    ...
    apache
    ...
    fileupload
    ...
    DiskFileItemFactory;
    import org
    ...
    commons
    ...
    servlet
    ...
    apache
    ...
    io
    ...
    *;

    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
    ...
    getInitParameter("file-upload");
    }
    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, java
    ...
    IOException {
    76

    Java Servlets

    // Check that we have a file upload request
    isMultipart = ServletFileUpload
    ...
    setContentType("text/html");
    java
    ...
    PrintWriter out = response
    ...
    println("");
    out
    ...
    println("Servlet upload");
    out
    ...
    println("");
    out
    ...
    println("");
    out
    ...
    setSizeThreshold(maxMemSize);
    // Location to save data that is larger than maxMemSize
    ...
    setRepository(new File("c:\\temp"));

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

    try{
    // Parse the request to get file items
    ...
    parseRequest(request);

    // Process the uploaded file items
    Iterator i = fileItems
    ...
    println("");
    out
    ...
    println("Servlet upload");
    77

    Java Servlets

    out
    ...
    println("");
    while ( i
    ...
    next();
    if ( !fi
    ...
    getFieldName();
    String fileName = fi
    ...
    getContentType();
    boolean isInMemory = fi
    ...
    getSize();
    // Write the file
    if( fileName
    ...
    substring( fileName
    ...
    substring(fileName
    ...
    write( file ) ;
    out
    ...
    println("");
    out
    ...
    out
    ...
    io
    ...
    getName( )+": POST method required
    ...
    xml file as follows
    ...
    When you would
    try http://localhost:8080/UploadFile
    ...

    File Upload:
    Select a file to upload:
    Choose File

    No File Chosen

    Upload File
    If your servlet script works fine, your file should be uploaded in c:\apache-tomcat8
    ...
    28\webapps\data\ directory
    ...
    Servlet – Handling Date

    Java Servlets

    One of the most important advantages of using Servlet is that you can use most of the
    methods available in core Java
    ...
    util package, this class encapsulates the current date
    and time
    ...
    The first constructor initializes the object with
    the current date and time
    ...

    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
    ...

    int compareTo(Date date)
    Compares the value of the invoking object with that of date
    ...
    Returns a negative value if the invoking object is earlier than
    date
    ...

    int compareTo(Object obj)
    Operates identically to compareTo(Date) if obj is of class Date
    ...

    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
    ...

    int hashCode( )
    Returns a hash code for the invoking object
    ...

    String toString( )
    Converts the invoking Date object into a string and returns the result
    ...
    You can use a simple Date
    object with toString() method to print current date and time as follows:
    // Import required java libraries
    import java
    ...
    *;
    import java
    ...
    Date;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    setContentType("text/html");

    PrintWriter out = response
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...
    toString() + "\n" +
    "");
    }
    }

    81

    Java Servlets
    Now let us compile above servlet and create appropriate entries in web
    ...
    This would produce following
    result:

    Display Current Date & Time
    Mon Jun 21 21:46:49 GMT+04:00 2010
    Try to refresh URL http://localhost:8080/CurrentDate and you would find difference in
    seconds every time you would refresh
    ...
    In case
    you need to compare two dates, following are the methods:


    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
    ...
    Because the 12th of
    the month comes before the 18th, for example, new Date(99, 2, 12)
    ...




    You can use the compareTo( ) method, which is defined by the Comparable
    interface and implemented by Date
    ...
    SimpleDateFormat allows you to start by choosing any user-defined
    patterns for date-time formatting
    ...
    io
    ...
    text
    ...
    util
    ...
    servlet
    ...
    servlet
    ...
    *;

    // Extend HttpServlet class
    public class CurrentDate extends HttpServlet {
    82

    Java Servlets

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set response content type
    response
    ...
    getWriter();
    String title = "Display Current Date & Time";
    Date dNow = new Date( );
    SimpleDateFormat ft =
    new SimpleDateFormat ("E yyyy
    ...
    dd 'at' hh:mm:ss a zzz");
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + title + "

    \n" +
    "

    " + ft
    ...
    This would produce following result:

    using

    URL

    Display Current Date & Time
    Mon 2010
    ...
    21 at 10:06:44 PM GMT+04:00

    Simple DateFormat Format Codes
    To specify the time format use a time pattern string
    ...
    M
    ...
    M
    ...
    in July)

    w

    Week in year

    40

    W

    Week in month

    1

    a

    A
    ...
    /P
    ...
    marker

    PM

    k

    Hour in day (1~24)

    24

    K

    Hour in A
    ...
    /P
    ...
    (0~11)

    10

    z

    Time zone

    Eastern Standard Time

    '

    Escape for text

    Delimiter

    "

    Single quote

    `

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

    Page redirection is a technique where the client is sent to a new location other than
    requested
    ...

    The simplest way of redirecting a request to another page is using method
    sendRedirect() of response object
    ...
    sendRedirect(String location)
    throws IOException
    This method sends back the response to the browser along with the status code and new
    page location
    ...

    String site = "http://www
    ...
    com" ;
    response
    ...
    SC_MOVED_TEMPORARILY);
    response
    ...


    Example
    This example shows how a servlet performs page redirection to another location:
    import java
    ...
    *;
    import java
    ...
    Date;
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    setContentType("text/html");
    85

    Java Servlets

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

    response
    ...
    SC_MOVED_TEMPORARILY);
    response
    ...
    xml

    ...

    Now call this servlet using URL http://localhost:8080/PageRedirect
    ...
    photofuntoos
    ...


    86

    17
    ...
    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
    ...




    Increase global variable every time either doGet() or doPost() method is called
    ...
    This value can be read inside init() method when servlet would
    be initialized next time
    ...




    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
    ...




    You can display value of the global counter to show total number of hits on your
    web site
    ...


    Here I'm assuming that the web container will not be restarted
    ...


    Example
    This example shows how to implement a simple page hit counter:
    import java
    ...
    *;
    import java
    ...
    Date;
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...

    hitCount = 0;
    }

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set response content type
    response
    ...
    getWriter();
    String title = "Total Number of Hits";
    String docType =
    " ...
    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
    ...
    xml
    88

    Java Servlets


    PageHitCounter
    PageHitCounter



    PageHitCounter
    /PageHitCounter


    ...
    This would
    increase counter by one every time this 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
    ...

    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
    ...




    If required, you can use a database table to store the value of global variable in
    destroy() method of filter
    ...
    This step is optional
    ...
    If it is restarted or
    servlet destroyed, the hit counter will be reset
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    *;

    public class SiteHitCounter implements Filter{

    private int hitCount;

    public void

    init(FilterConfig config)
    throws ServletException{

    // Reset hit counter
    ...
    io
    ...

    System
    ...
    println("Site visits count :"+ hitCount );

    // Pass request back down the filter chain
    chain
    ...

    }
    }

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


    SiteHitCounter
    SiteHitCounter



    SiteHitCounter
    /*



    ...
    This would increase counter by one
    every time any page gets a hit and it would display following message in the log:
    Site visits count : 1
    Site visits count : 2
    Site visits count : 3
    Site visits count : 4
    Site visits count : 5

    ...
    Servlets – Auto Page Refresh

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

    Java Servlet makes this job easy by providing you a mechanism where you can make a
    webpage in such a way that it would refresh automatically after a given interval
    ...
    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 in seconds
    ...

    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    util
    ...

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set refresh, autoload time as 5 seconds
    response
    ...
    setContentType("text/html");

    // Get current time
    Calendar calendar = new GregorianCalendar();
    String am_pm;
    int hour = calendar
    ...
    HOUR);
    int minute = calendar
    ...
    MINUTE);
    int second = calendar
    ...
    SECOND);
    if(calendar
    ...
    AM_PM) == 0)
    am_pm = "AM";
    else
    am_pm = "PM";

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

    PrintWriter out = response
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...

    public void doPost(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException {
    doGet(request, response);
    }
    }

    93

    Java Servlets

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


    Refresh
    Refresh



    Refresh
    /Refresh


    ...
    Just run the servlet and wait to
    see the result:

    Auto Page Refresh using Servlet
    Current Time is: 9:44:50 PM

    94

    19
    ...



    You can download latest version of JavaMail (Version 1
    ...




    You can download latest version of JAF (Version 1
    ...
    1) from Java's standard
    website
    ...
    You need to add mail
    ...
    jar files in your CLASSPATH
    ...
    Here it is assumed that
    your localhost is connected to the internet and capable enough to send an email
    ...

    // File Name SendEmail
    ...
    io
    ...
    util
    ...
    servlet
    ...
    servlet
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    internet
    ...
    activation
    ...

    String to = "abcd@gmail
    ...
    com";

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System
    ...
    setProperty("mail
    ...
    host", host);

    // Get the default Session object
    ...
    getDefaultInstance(properties);

    // Set response content type
    response
    ...
    getWriter();

    try{
    // Create a default MimeMessage object
    ...

    message
    ...

    message
    ...
    RecipientType
    ...
    setSubject("This is the Subject Line!");
    // Now set the actual message
    message
    ...
    send(message);
    String title = "Send Email";
    String res = "Sent message successfully
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...
    printStackTrace();
    }
    }
    }
    Now let us compile the above servlet and create the following entries in web
    ...


    SendEmail
    SendEmail



    SendEmail
    /SendEmail


    ...
    com and would display following response:

    Send Email
    Sent message successfully
    ...
    RecipientType type,
    97

    Java Servlets

    Address[] addresses)
    throws MessagingException
    Here is the description of the parameters:


    type: This would be set to TO, CC or BCC
    ...
    Example Message
    ...
    TO



    addresses: This is the array of email ID
    ...
    Here it is assumed that
    your localhost is connected to the internet and capable enough to send an email
    ...

    This example is very similar to previous one, except here we are using setContent()
    method to set content whose second argument is "text/html" to specify that the HTML
    content is included in the message
    ...

    // File Name SendEmail
    ...
    io
    ...
    util
    ...
    servlet
    ...
    servlet
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    internet
    ...
    activation
    ...

    String to = "abcd@gmail
    ...
    com";

    // Assuming you are sending email from localhost
    String host = "localhost";

    // Get system properties
    Properties properties = System
    ...
    setProperty("mail
    ...
    host", host);

    // Get the default Session object
    ...
    getDefaultInstance(properties);

    // Set response content type
    response
    ...
    getWriter();

    try{
    // Create a default MimeMessage object
    ...

    message
    ...

    message
    ...
    RecipientType
    ...
    setSubject("This is the Subject Line!");

    // Send the actual HTML message, as big as you like
    message
    ...
    send(message);
    String title = "Send Email";
    String res = "Sent message successfully
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...
    printStackTrace();
    }
    }
    }
    Compile and run the above servlet to send HTML message on a given email ID
    ...
    Here it is
    assumed that your localhost is connected to the internet and capable enough to send
    an email
    ...
    java
    import java
    ...
    *;
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    mail
    ...
    mail
    ...
    *;
    import javax
    ...
    *;

    public class SendEmail extends HttpServlet{

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    100

    Java Servlets

    {
    // Recipient's email ID needs to be mentioned
    ...
    com";

    // Sender's email ID needs to be mentioned
    String from = "web@gmail
    ...
    getProperties();

    // Setup mail server
    properties
    ...
    smtp
    ...

    Session session = Session
    ...
    setContentType("text/html");
    PrintWriter out = response
    ...

    MimeMessage message = new MimeMessage(session);

    // Set From: header field of the header
    ...
    setFrom(new InternetAddress(from));

    // Set To: header field of the header
    ...
    addRecipient(Message
    ...
    TO,
    new InternetAddress(to));

    // Set Subject: header field
    message
    ...
    setText("This is message body");

    // Create a multipar message
    Multipart multipart = new MimeMultipart();

    // Set text message part
    multipart
    ...
    txt";
    DataSource source = new FileDataSource(filename);
    messageBodyPart
    ...
    setFileName(filename);
    multipart
    ...
    setContent(multipart );

    // Send message
    Transport
    ...
    ";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + title + "

    \n" +
    102

    Java Servlets

    "

    " + res + "

    \n" +
    "");
    }catch (MessagingException mex) {
    mex
    ...


    User Authentication Part
    If it is required to provide user ID and Password to the email server for authentication
    purpose then you can set these properties as follows:
    props
    ...
    user", "myuser");
    props
    ...
    password", "mypwd");
    Rest of the email sending mechanism would remain as explained above
    ...
    Servlets – Packaging

    Java Servlets

    The web application structure involving the WEB-INF subdirectory is standard to all Java
    web applications and specified by the servlet API specification
    ...
    Here is how this directory structure looks like:
    /myapp
    /images
    /WEB-INF
    /classes
    /lib
    The WEB-INF subdirectory contains the application's deployment descriptor, named
    web
    ...
    All the HTML files should be kept in the top-level directory which is myapp
    ...


    Creating Servlets in Packages
    The WEB-INF/classes directory contains all the servlet classes and other class files, in a
    structure that matches their package name
    ...
    myorg
    ...
    class
    Following is the example to create MyServlet class with a package name com
    ...
    myorg;

    // Import required java libraries
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    setContentType("text/html");

    // Actual logic goes here
    ...
    getWriter();
    out
    ...

    }
    }

    Compiling Servlets in Packages
    There is nothing much different to compile a class available in package
    ...
    myorg
    ...

    Assuming your environment is setup properly, go in /webapps/ROOT/WEB-INF/classes directory and compile MyServlet
    ...
    java
    If the servlet depends on any other libraries, you have to include those JAR files on your
    CLASSPATH as well
    ...
    jar JAR file because I'm not using
    any other library in Hello World program
    ...
    For this command to work properly,
    105

    Java Servlets
    you have to include the location of the Java SDK that you are using in the PATH
    environment variable
    ...
    class file in the
    same directory
    ...


    Packaged Servlet Deployment
    By default, a servlet application is located at the path /webapps/ROOT and the class file would reside in /webapps/ROOT/WEB-INF/classes
    ...
    myorg
    ...
    class and you would
    need to create following entries in web
    ...
    myorg
    ...
    tags available in web
    ...
    There could be various entries in this table already available, but never mind
    ...
    bat
    (on
    windows)
    or
    /bin/startup
    ...
    )
    and
    finally
    type
    http://localhost:8080/MyServlet in browser's address box
    ...
    Servlets – Debugging

    Java Servlets

    It is always difficult to testing/debugging a servlets
    ...

    Here are a few hints and suggestions that may aid you in your debugging
    ...
    out
    ...
    out
    ...
    We can print out variable values as well
    ...
    This includes Servlets,
    JSP, RMI, EJB's, ordinary Beans and classes, and standalone applications
    ...
    Whereas writing to System
    ...


    Following is the syntax to use System
    ...
    println():
    System
    ...
    println("Debugging message");
    All the messages generated by above syntax would be logged in web server log file
    ...
    I use log4J to log all the messages
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;

    public class ContextLog extends HttpServlet {
    public void doGet(HttpServletRequest request,
    HttpServletResponse response) throws ServletException,
    java
    ...
    IOException {

    107

    Java Servlets

    String par = request
    ...
    log methods
    ServletContext context = getServletContext( );

    if (par == null || par
    ...
    log("No message received:",
    new IllegalStateException("Missing parameter"));
    else
    context
    ...
    setContentType("text/html");
    java
    ...
    PrintWriter out = response
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...
    With Tomcat
    these logs are found in /logs
    ...

    For that reason it's good to use the log() function in the catch clause of exceptions which
    should normally not occur
    ...

    To debug a servlet, we debug sun
    ...
    http
    ...
    This is
    108

    Java Servlets
    very similar to how applets are debugged
    ...
    applet
    ...

    Most debuggers hide this detail by automatically knowing how to debug applets
    ...
    servlet
    ...
    Http-Server and
    associated classes
    ...


    You normally wouldn't want server_root/servlets in your classpath because it disables
    servlet reloading
    ...
    It allows your
    debugger to set breakpoints in a servlet before the custom servlet loader in HttpServer
    loads the servlet
    ...
    servlet
    ...
    HttpServer
    ...
    You should see execution being stopped
    at your breakpoints
    ...
    Comments can
    be used in lots of other ways in the debugging process
    ...
    ) and multiple line (/*
    ...
    If the bug
    disappears, take a closer look at the code you just commented and find out the problem
    ...
    If you're familiar with the structure of HTTP, you can read
    the request and response and see exactly what exactly is going with those headers
    ...




    Ask a browser to show the raw content of the page it is displaying
    ...
    It's usually an option under the View menu
    ...
    With Netscape Navigator, use Shift-Reload; with Internet
    Explorer use Shift-Refresh
    ...
    init(config) right away
    ...
    Servlets – Internationalization

    Before we proceed, let me explain three important terms:


    Internationalization (i18n): This means enabling a web site to provide
    different versions of content translated into the visitor's language or nationality
    ...




    locale: This is a particular cultural or geographical region
    ...
    For example "en_US" represents English locale for US
    ...
    This tutorial would not give you complete detail on this but it would give you a
    good example on how you can offer your web page in different languages to internet
    community by differentiating their location i
    ...
    locale
    ...
    Following is the method of request object which returns Locale object
    ...
    util
    ...
    getLocale()

    Detecting Locale
    Following are the important locale methods which you can use to detect requester's
    location, language and of course locale
    ...

    S
    ...

    1

    2
    3
    4
    5
    6

    Method & Description
    String getCountry()
    This method returns the country/region code in upper case for this locale in ISO
    3166 2-letter format
    ...

    String getLanguage()
    This method returns the language code in lower case for this locale in ISO 639
    format
    ...

    String getISO3Country()
    This method returns a three-letter abbreviation for this locale's country
    ...


    111

    Java Servlets

    Example
    This example shows how you display a language and associated country for a request:
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    util
    ...
    getLocale();
    String language = locale
    ...
    getCountry();

    // Set response content type
    response
    ...
    getWriter();

    String title = "Detecting Locale";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + language + "

    \n" +
    "

    " + country + "

    \n" +
    "");
    }
    }
    112

    Java Servlets

    Languages Setting
    A servlet can output a page written in a Western European language such as English,
    Spanish, German, French, Italian, Dutch etc
    ...

    Second point is to display all the special characters using HTML entities
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    Locale;

    public class DisplaySpanish extends HttpServlet{

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set response content type
    response
    ...
    getWriter();
    // Set spanish language code
    ...
    setHeader("Content-Language", "es");

    String title = "En Español";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + "En Español:" + "

    \n" +
    "

    " + "¡Hola Mundo!" + "

    \n" +
    "");
    }
    113

    Java Servlets

    }

    Locale Specific Dates
    You can use the java
    ...
    DateFormat class and its static getDateTimeInstance() method
    to format date and time specific to locale
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    Locale;
    import java
    ...
    DateFormat;
    import java
    ...
    Date;

    public class DateLocale extends HttpServlet{

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set response content type
    response
    ...
    getWriter();
    //Get the client's Locale
    Locale locale = request
    ...
    getDateTimeInstance(
    DateFormat
    ...
    SHORT,
    locale)
    ...
    0 " +
    "transitional//en\">\n";
    out
    ...
    txt
    ...

    Following is the example which shows how to format currency specific to a given locale:
    import java
    ...
    *;
    import javax
    ...
    *;
    import javax
    ...
    http
    ...
    util
    ...
    text
    ...
    util
    ...
    setContentType("text/html");
    PrintWriter out = response
    ...
    getLocale( );
    NumberFormat nft = NumberFormat
    ...
    format(1000000);

    String title = "Locale Specific Currency";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + formattedCurr + "

    \n" +
    "");
    }
    }

    Locale Specific Percentage
    You can use the java
    ...
    NumberFormat class and its static getPercentInstance() method
    to get locale specific percentage
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    *;
    import java
    ...
    Locale;
    import java
    ...
    NumberFormat;
    import java
    ...
    Date;

    public class PercentageLocale extends HttpServlet{

    public void doGet(HttpServletRequest request,
    HttpServletResponse response)
    throws ServletException, IOException
    {
    // Set response content type
    response
    ...
    getWriter();
    //Get the client's Locale
    Locale locale = request
    ...
    getPercentInstance(locale);
    String formattedPerc = nft
    ...
    51);

    116

    Java Servlets

    String title = "Locale Specific Percentage";
    String docType =
    " ...
    println(docType +
    "\n" +
    "" + title + "\n" +
    "\n" +
    "

    " + formattedPerc + "

    \n" +
    "");
    }
    }

    117

    Java Servlets

    118

    23
    ...
    xml file) for
    deploying your application into a web server
    ...
    0 has introduced a new
    package called javax
    ...
    annotation
    ...
    If you use annotation, then the deployment descriptor
    (web
    ...
    But you should use tomcat7 or any later version of tomcat
    ...
    xml) such as servlet declaration and servlet mapping
    ...

    The annotation types introduced in Servlet 3
    ...


    @WebInitParam

    To specify an initialization parameter
    ...


    @WebListener

    To declare a WebListener
    ...

    This annotation is used within
    the ServletSecurity annotation to represent the security
    constraints to be applied to all HTTP protocol methods for
    which a corresponding HttpMethodConstraint element does
    NOT occur within the ServletSecurity annotation
    ...

    Annotation that may be specified on a Servlet class,

    @MultipartConfig

    @ServletSecurity

    indicating that instances of the Servlet expect requests
    that conform to the multipart/form-data MIME type
    ...


    Here we have discussed some of the Annotations in detail
    ...
    The
    following table contains the list of attributes used for WebServlet annotation
    ...

    The value attribute is recommended for use when the URL pattern is the only attribute
    being set, otherwise the urlPattern attribute should be used
    ...
    It is a simple
    servlet that displays the text Hello Servlet
    ...
    io
    ...
    io
    ...
    servlet
    ...
    servlet
    ...
    WebInitParam;
    import javax
    ...
    annotation
    ...
    servlet
    ...
    HttpServlet;
    import javax
    ...
    http
    ...
    servlet
    ...
    HttpServletResponse;

    120

    Java Servlets

    @WebServlet(value = "/Simple")
    public class Simple extends HttpServlet {
    private static final long serialVersionUID = 1L;

    protected void doGet(HttpServletRequest request, HttpServletResponse
    response)
    throws ServletException, IOException {
    response
    ...
    getWriter();
    out
    ...
    print("

    Hello Servlet

    ");
    out
    ...
    java in the usual way and put your class file in /webapps/ROOT/WEB-INF/classes
    ...
    You will see the
    following output on the web page
    ...
    It is used within a WebFilter or WebSevlet annotations
    ...

    Attribute Name
    String name
    String value
    String description

    Description
    Name of the initialization parameter
    Value of the initialization parameter
    Description of the initialization parameter

    Example
    The following example describes how to use @WeInitParam annotation along with
    @WebServlet annotation
    ...


    121

    Java Servlets

    import java
    ...
    IOException;
    import java
    ...
    PrintWriter;
    import javax
    ...
    ServletException;
    import javax
    ...
    annotation
    ...
    servlet
    ...
    WebServlet;
    import javax
    ...
    http
    ...
    servlet
    ...
    HttpServletRequest;
    import javax
    ...
    http
    ...
    setContentType("text/html");
    PrintWriter out=response
    ...
    print("");
    out
    ...
    println(getInitParameter("foo"));
    out
    ...
    print("");
    }
    }
    Compile Simple
    ...

    Now try to call any servlet by just running http://localhost:8080/Simple
    ...

    Hello Servlet

    Hello World!

    122

    Java Servlets

    @Webfilter
    This is the annotation used to declare a servlet filter
    ...

    The @WebFilter annotation defines a filter in a web application
    ...
    The
    annotated filter must specify at least one URL pattern
    ...

    Attribute Name
    String filterName
    String[] value
    Or
    String[] urlPatterns
    DispatcherType[]
    dispatcherTypes

    Description
    Name of the filter
    Provides array of values or urlPatterns to which the
    filter applies
    Specifies the types of dispatcher
    (Request/Response) to which the filter applies

    String[] servletNames

    Provides an array of servlet names

    String displayName

    Name of the filter

    String description

    Description of the filter

    WebInitParam[] initParams

    Array of initialization parameters for this filter

    Boolean asyncSupported

    Asynchronous operation supported by this filter

    String smallIcon

    Small icon for this filter, if present

    String largeIcon

    Large icon for this filter, if present

    Example
    The following example describes how to use @WebFilter annotation
    ...
    That means, the filter works like an interface layer between
    the request and the response
    ...
    It means, this filter is
    applicable for all the servlets
    ...
    io
    ...
    servlet
    ...
    WebFilter;
    import javax
    ...
    annotation
    ...
    servlet
    ...
    util
    ...
    getInitParameter("test-param");

    //Print the init parameter
    System
    ...
    println("Test Param: " + testParam);
    }
    public void doFilter(ServletRequest request,
    ServletResponse response,
    FilterChain chain)
    throws IOException, ServletException {
    // Log the current timestamp
    ...
    out
    ...
    toString());

    // Pass request back down the filter chain
    chain
    ...
    java in the usual way and put your class file in /webapps/ROOT/WEB-INF/classes
    ...
    You will see the
    following output on the web page
    ...
    There, you will find the value of the init parameter testparam and the current timestamp along with servlet notification messages
    Title: discrete mathematics full notes (engineering) btech
    Description: this PDF will provide you full notes of discrete mathematics subject ! it's easy way to understand critical solution in easy way ! try it