Docstoc

sample servlets

Document Sample
sample servlets Powered By Docstoc
					 Servlets




Your IT Partner
Objectives
After completing this chapter, the student will be able to:

 •   Explain Java’s impact on internet and web
 •   Explain the difference between an applet and a
     servlet
 •   Explain the interaction between the browser, web
     server and servlet
 •   Explain the functions of a web server
 •   Explain the environment required to develop servlets
 •   Understand servlet life cycle



                                            CMC Limited
                                     Objectives contd..




•   Explain the steps involved in developing and
    running a servlet
•   Explain HTTP client request
•   Explain HTTP servlet response
•   Explain the difference between GET method and
    POST method
•   Explain servlet APIs
•   Write simple servlet examples
•   Write servlet examples receiving input from
    HTML forms
•   Write servlet examples to demonstrate servlet
    initialization

                                    CMC Limited
Introduction
•   Web is only one of the services offered by internet.
•   Web is a classic example for client server
    application.
•   The two essential components in web are the web
    server and the web browser.
•   Web server is the server and the browser is the
    client.
•   The browser makes some request to the web server.
•   The browser and the web server communicate using
    a protocol called HTTP.
•   HTTP operates above the TCP/IP protocol.


                                         CMC Limited
                                      Introduction contd..

•   The browser generates an HTTP request to the
    appropriate web server.
•   The HTML source code of a web page has an MIME
    type text / html.
•   Java transformed the internet from a giant
    encyclopedia to a giant CPU.
•   RMI and CORBA are two major schemes, to
    implement distributed computing.
•   An applet is a small Java program embedded in an
    HTML page.
•   The web browser running on the client machine
    makes a request to the web server to download the
    HTML document to the client machine.


                                       CMC Limited
Servlets
•   Servlets are loaded and executed by the web server.
•   It accept requests from client, perform tasks to return
    results.
•   The sequence of events are described below.
    • Client makes request via HTTP.
    • Web server receives this request for a service
        and examines. Then it forwards the client request
        to the accurate servlet.
    • Servlet receives the HTTP request from the web
        server and process.
    • Then It returns response back to the web server.
    • Web server will forward the response to the client.


                                            CMC Limited
Servlet Development Environment
•   To develop and run servlets we need the followings:

    •   Java Development Kit installation.
    •   Java Servlet Development Kit installation.
    •   A Web Server.
    •   A client application (generally a web browser).




                                            CMC Limited
The Life Cycle of a Servlet




             Servlet Life Cycle
                                  CMC Limited
Web Server
•   To run the servlet we will require a web server that
    will support servlet API.
•   A server can support multiple concurrent services.
•   A service is an implementation of a specific protocol
    such as HTTP, FTP, SMTP etc.
•   Java Web Server from JavaSoft is the most popular
    web server in use now.
•   A number of third party server products are also
    available.
•   JRun from Live Software is preferred by many
    developers as their web server.
•   These servers are to be installed and configured
    before servlets are installed in them.
                                          CMC Limited
Hello World Servlet
•   A simple Hello World servlet

    import java.io.*;
    import javax.servlet.*;
    public class HelloWorldServlet extends
        GenericServlet
      {
      public void service(ServletRequest
        request,ServletResponse response)
                            throws
        ServletException,IOException
          {


                                         CMC Limited
                             Hello World Servlet contd..



response.setContentType("text/html");
PrintWriter pw=response.getWriter();
pw.println("<B>Hello World");
     pw.close();
     }
  }




                                        CMC Limited
The Request
•   In a client server environment, the client makes a
    request to the server.

•   The server responds to this request by doing some
    processing and then sends a response back to the
    client.

•   In general a request consists of a stream of data sent
    to the server through some protocol.




                                           CMC Limited
The Response
•   After the client sends a request, the server processes
    it and sends a response back to the client.

•   This response also consists of several lines of data
    as shown below.




                                           CMC Limited
                                      The Response contd..


•   As in the case of request, each line in the response
    header has the following general format.
    • parameter-name : parameter-value.

•   Typical response header parameter names and the
    corresponding values are given below.
    • Date : Monday, 10-July-2000       03:25:12 GMT
    • Server : JavaWebServer/1.1.1
    • MIME-Version : 1.0
    • Content_type : text/html




                                         CMC Limited
Servlet API
•   The API required to build servlets are contained in
    two packages. They are:

    package javax.servlet
    package javax.servlet.http




                                         CMC Limited
                                       Servlet API contd..

The javax.servlet package
•   The javax.servlet package contains the following
    interfaces and classes.
    • interface Servlet
    • interface ServletConfig
    • interface ServletContext
    • interface ServletRequest
    • interface ServletResponse
    • interface SingleThreadModel
    • class GenericServlet
    • class ServletInputStream
    • class ServletOutputStream
    • class ServletException
    • class UnavailableException

                                       CMC Limited
                                          Servlet API contd..

The javax.servlet.http Package
•   The javax.servlet.http package contains the following
    interfaces and classes.
    • interface HttpServletRequest
    • interface HttpServletResponse
    • interface HttpSession
    • interface HttpSessionBindingListner
    • interface HttpSessionContext
    • class Cookie
    • class HttpServlet
    • class HttpSessionBindingEvent
    • class HttpUtils



                                          CMC Limited
Session Management: HttpSession API
•   The HTTP session API is an essential component in
    constructing interactive web sites.

•   The session API of the Java Servlet specification
    provides a mechanism for associating a series of
    requests with a specific browser or user.

•   This is required because the HTTP employed for web
    browser to web server requests is a stateless
    protocol.




                                        CMC Limited
HttpSession API
•   The getSession() method is used to either create a
    session object if one does not already exist or to
    associate a request with an existing session.

•   In order to store information in the session object, the
    setAttribute() method is called.

•   The application retrieves information that is stored
    via a call to the getAttribute() method.




                                            CMC Limited
                                  HttpSession API contd..

HttpSession Object
•   Sessions are represented by an HttpSession object.

•   You    access     a  session    by   calling  the
    HttpServletRequest.getSession()                or
    HttpServletRequest .getSession(boolean) method of
    a request object.

•   This method returns the current session associated
    with this request.

•   If the request does not have a session, it creates
    one.


                                         CMC Limited
Saving Client State
•   The Servlet API provides two ways to track client
    state

    •   Session Tracking
    •   Cookies




                                       CMC Limited
                                 Saving Client State contd..

Session tracking
•   Session tracking is a mechanism that servlets use to
    maintain state about a series of requests from the
    same user across some period of time.

•   Sessions are shared among the servlets accessed
    by a client.

•   To use session tracking
    • Obtain a session (an HttpSession object) for a
       user.
    • Store or get data from the HttpSession object.
    • Invalidate the session (optional).


                                         CMC Limited
                                   Saving Client State contd..

Cookie
•   Cookies are a mechanism that a servlet uses to have
    clients hold a small amount of state-information
    associated with the user.
•   Servlets can use the information in a cookie as the
    user enters a site as the user navigates around a site
    or both.
•   Cookies are a way for a server to send some
    information to a client to store, and for the server to
    later retrieve its data from that client.
•   Servlets send cookies to clients by adding fields to
    HTTP response headers.
•   Clients automatically return cookies by adding fields
    to HTTP request headers.
                                            CMC Limited
Request Dispatcher Mechanism
•   RequestDispatcher defines an object that receives
    requests from the client and sends them to any
    resource on the server.
•   The servlet container creates the RequestDispatcher
    object.
•   It is used as a wrapper around a server resource
    located at a particular path or given by a particular
    name.
•   An object implementing the RequestDispatcher
    interface may be obtained via the following methods:
    o ServletContext.getRequestDispatcher
    o ServletContext.getNamedDispatcher
    o ServletRequest.getRequestDispatcher
                                          CMC Limited
Developing and Deploying Web
applications
•   A developer creates the files comprising a Web
    application.

•   Then assembles the Web application components
    into a Web module.

•   Next, the deployer installs the Web application on the
    server.




                                           CMC Limited
      Developing and Deploying Web applications contd..

web.xml file
•   The web.xml file provides configuration and
    deployment information for the Web components.
•   Examples of Web components are servlet
    parameters, servlet and JSP definitions, URL
    mappings.
•   The Java Servlet 2.4 specification defines the
    web.xml deployment descriptor file in terms of an
    XML schema document.
•   The web.xml file must reside in the WEB-INF
    directory under the context of the hierarchy of
    directories that exist for a Web application.



                                       CMC Limited
Listeners – Context, Session and
Request
•   Request listeners allow developers to observe as
    requests are created and destroyed, and as
    attributes are added and removed from a request.

•   Servlet context listeners manage resources at an
    application level.

•   Session listeners manage resources that are
    associated with a series of requests from a single
    client.



                                        CMC Limited
          Listeners – Context, Session and Request contd..

Listener Classes for Servlet Context and
Session Changes
•   The following methods are defined as part of the
    javax.servlet.ServletContextListener interface:
    o void contextInitialized(ServletContextEvent) :
    o void contextDestroyed(ServletContextEvent) :

•   The following methods are defined as part of the
    javax.servlet.ServletRequestListener interface:
    o public void requestInitialized(ServletRequestEvent re) :
    o public void requestDestroyed(ServletRequestEvent re) :




                                          CMC Limited
          Listeners – Context, Session and Request contd..

Servlet Filters

•   Steps to Creating Filters

    1. Create class that implements Filter interface.
       • Methods: doFilter, init, destroy
    2. Put filtering behavior in doFilter.
       • Args: ServletRequest, ServletResponse, FilterChain
    3. Call doFilter method of the FilterChain : This invokes
       next filter (if any) or actual resource
    4. Register the filter with the appropriate servlets and JSP
       pages.
       • Use filter and filter-mapping in web.xml.
    5. Disable invoker servlet.

                                            CMC Limited
          Listeners – Context, Session and Request contd..

The doFilter Method

•   public      void      doFilter(ServletRequest request,
    ServletResponse response, FilterChain chain) throws
    ServletException, IOException
    {
    …
    chain.doFilter(request,response);
    }




                                        CMC Limited
          Listeners – Context, Session and Request contd..

A Simple Reporting Filter

•   public class ReportFilter implements Filter
    {
    public       void      doFilter(ServletRequest     request,
        ServletResponse response,
    FilterChain chain) throws ServletException, IOException
    {
    HttpServletRequest req = (HttpServletRequest)request;
    System.out.println(req.getRemoteHost() + " tried to access
        " + req.getRequestURL() + " on "+new Date() + ".");
    chain.doFilter(request,response);
    }


                                           CMC Limited
        Listeners – Context, Session and Request contd..

Declaring the Reporting Filter

  ….
  <web-app…>
  <!-- Register the name "Reporter"
  for ReportFilter. -->
  <filter>
  <filter-name>Reporter</filter-name>
  <filter-class>
  moreservlets.filters.ReportFilter
  </filter-class>
  </filter>



                                        CMC Limited
          Listeners – Context, Session and Request contd..

Web Application Security

Major Issues

Preventing unauthorized users from accessing sensitive data.
   • Access restriction
       o Identifying which resources need protection
       o Identifying who should have access to them
   • Authentication
       o Identifying users to determine if they are one of the
           authorized ones
Preventing attackers from stealing network data while it is in
   transit.
   • Encryption (usually with SSL)

                                          CMC Limited
          Listeners – Context, Session and Request contd..

Declarative Security

•   To prevent unauthorized access
    • Use the Web application deployment descriptor
       (web.xml) to declare that certain URLs need
       protection.
    • Designate authentication method that server uses to
       identify users.
    • At request time, the server automatically prompts
       users for usernames and passwords when they try to
       access restricted.
•   To safeguard network data
    • Use the deployment descriptor to stipulate that
       certain URLs should be accessible only with SSL.

                                         CMC Limited
          Listeners – Context, Session and Request contd..

Programmatic Security

•   Protected servlets and JSP pages at least partially manage
    their own security.
    • Much more work, but totally portable.
    • No server-specific piece and web.xml entries needed.
•   To prevent unauthorized access
    • Each servlet or JSP page must authenticate the user.
•   To safeguard network data
    • Each servlet or JSP page has to check the network
       protocol used to access it.
    • If users try to use a regular HTTP connection to access
       URLs, the servlet or JSP page must manually redirect
       them to the HTTPS (SSL) equivalent

                                          CMC Limited
          Listeners – Context, Session and Request contd..

Hello World Servlet Revisited

•   Hello World Servlet program repeated

    import java.io.*;
    import javax.servlet.*;
    public class HelloWorldServlet extends GenericServlet
       {
       public             void            service(ServletRequest
       request,ServletResponse response)
                            throws ServletException, IOException
           {



                                            CMC Limited
                  Hello World Servlet Revisited contd..



response.setContentType("text/html");
      PrintWriter pw=response.getWriter();
      pw.println("<B>Hello World");
      pw.close();
      }
 }




                                     CMC Limited
HTTP Request Methods
•   There are several different types of commands.

•   The most frequently used commands are GET and POST.

•   GET command is a directive to the server to read
    information from the HTTP request.

•   The POST method is used for posting information.




                                           CMC Limited
                          HTTP Request Methods contd..


•   In addition to GET and POST methods, there are
    several other methods those are.
    • HEAD method is sent by the client when it wants
       to see only the header of the response.
    • PUT method is used to place a document directly
       on the server.
    • DELETE method does the opposite of PUT
       method.
    • TRACE method is used as a debugging aid. It
       returns to the client the exact content of its
       request.
    • OPTION method can be used to ask the server
       which methods it support.

                                       CMC Limited
Servlet Basics
•   Every        servlet     must       implement     the
    javax.servlet.Servlet interface.
•   Most servlets implement it by extending one of the
    following two classes.
    • javax.servlet.GenericServlet
    • javax.servlet.http.HttpServlet
•   Both       the       above      classes     implement
    javax.servlet.Servlet interface.
•   This is clear from the definitions of the above two
    classes.
    • class       GenericServlet     implements   Servlet,
        ServletConfig, Serializable


                                           CMC Limited
Servlet Examples
A Servlet Program to Print Request
Parameters
•   A servlet program to print the request parameters
    and their values.
    import java.io.*;
    mport java.util.*;
                         import javax.Servlet.*;
    import javax.servlet.http.*;
        public     class     Example1Servlet     extends
       HttpServlet
    {
    public void service(HttpServletRequest request,

                                         CMC Limited
A Servlet Program to Print Request Parameters contd..


HttpServletResponse response)
{
try
  {
response.setContextType(“text/html”);
PrintWriter out=response.getWriter();
response.setStatus(HttpServletResponse.SC_OK);
out.println(“<html>”);
out.println(“<head><title>Hello World</title></head>”;
out.println(“<body>”);
out.println(“<h1>Hello




                                       CMC Limited
                                  Servlet Examples contd..
Submitting HTTP Request from an
HTML Form
•   HTML source code for generating the form.
    <html>
    <body>
    <center>
    <form name=”Form1”
        method=”post”
        action=http://162.16.21.116:8080/servlet/Example
        2Servlet>
    <table>
    <tr>
    <td><B>Employee:</td>

                                          CMC Limited
                                  Servlet Examples contd..
An Example to Demonstrate the Use of
Get Method
•   Source code for Examples3Servlet.html

    <html>
    <body>
    <center>
    <form name=”Forms”
    action=http://localhost:8080/servlet/Example3Servlet
        >




                                          CMC Limited
An Example to Demonstrate the Use of Get Method contd..

    <B>Color:</B>
    <select name=”color” size=”1”>
    <option value=”Red”>Red</option>
    <option value=”Green”>Green</option>
    <option value=”Blue”>Blue</option>
    </select>
    <br><br>
    <input type=submit value=”submit”>
    </form>
    </body>
    </html>




                                       CMC Limited
                                 Servlet Examples contd..
An Example to Demonstrate the Use of
Post Method
•   Source code for the file Example4Servlet.html
    <html>
    <body>
    <center>
    <form name=”Form1”
    method=”post”
    action=http://172.16.21.116:8080/servlet/Example4S
        ervlet>
    <B>Color:</B>
    <select name=”color” size=”1”>



                                         CMC Limited
An Example to Demonstrate the Use of Post Method contd..



    <option value=”Red”>Red</option>
    <option value=”Green”>Green</option>
    <option value=”Blue”>Blue</option>
    </select>
    <br><br>
    <input type=submit value=”Submit”>
    </form>
    </body>
    </html>




                                       CMC Limited
                                 Servlet Examples contd..
Servlet Initialization
•   You have to provide initialization parameters to a
    servlet.
•   The ServletConfig object has methods to enable you
    to read the initialization parameters.
•   Two methods are
    1. Enumeration getInitParameterNames()
    2. String getInitParameter(String pname)
•   ServletConfig object can be made available and
    accessed in two ways:
    1. init() method receives a ServletConfig object as
        parameter
    2. The Servlet interface defines a method


                                         CMC Limited
MC Limited

				
DOCUMENT INFO
Shared By:
Stats:
views:12
posted:9/13/2012
language:English
pages:48
Description: jjava programming