Unit 5 Servlet

download Unit 5 Servlet

of 105

Transcript of Unit 5 Servlet

  • 7/30/2019 Unit 5 Servlet

    1/105

    1

    Java Servlets

  • 7/30/2019 Unit 5 Servlet

    2/105

    2

    Servlet

    A servlet is a web component, managed by acontainer, that generates dynamic content.

    It is a server-side program written in Java. After

    writing the source code, it has to be compiledinto a class file, like any Java program.

    Whenever a HTTP request comes, requesting forthe execution of this Servlet, the class file is

    interpreted by the Java Virtual Machine (JVM).

    This produces HTML output and is sent back tothe browser in the form of HTTP response.

  • 7/30/2019 Unit 5 Servlet

    3/105

    3

    Why Servlets?

    Web pages with dynamic content

    Easy coordination between Servlets tomake Web applications

    Containers support many features Sessions, persistence, resource management

    (e.g., database connections), security, etc.

  • 7/30/2019 Unit 5 Servlet

    4/105

    4

    Where are Servlets?

    HTTPWeb

    Server

    File system

    Servlet

    Server

    Static

    Dynamic

    Ex : Tomcat = Web Server + Servlet Server

  • 7/30/2019 Unit 5 Servlet

    5/105

    5

    Servlet job

    Read explicit data sent by client (form data) Read implicit data sent by client (request headers) Generate the results

    Send the explicit data back to client(HTML)

    Send the implicit data to client (status codes and response headers)

  • 7/30/2019 Unit 5 Servlet

    6/105

    6

    When Servlets?

    Receive Request for

    Servlet S

    Is Sloaded?

    Is Scurrent? (re)Load S

    Forward Request

    to S

    Servlets die when

    Servlet Server dies

    Loaded when first used,

    or after modifiedno

    no

    yes

    yes

  • 7/30/2019 Unit 5 Servlet

    7/105

    7

    CGI Scripts

    CGIstands for Common GatewayInterface

    Client sends a request to server

    Server starts a CGI script

    Script computes a result for server

    and quits

    Another client sends a request

    client server

    clientscript

    Server starts the CGI script again

    script

    Server returns response to client

  • 7/30/2019 Unit 5 Servlet

    8/105

    8

    Servlets

    A servlet is like an applet, but on theserver side

    Client sends a request to server

    Server starts a servlet

    Servlet computes a result for

    server and does not quit

    Another client sends a request

    client server

    clientservlet

    Server calls the servlet again

    Server returns response to client

  • 7/30/2019 Unit 5 Servlet

    9/105

    9

    Servlets vs. CGI scripts

    Running a servlet doesnt require creating aseparate process each time (threads used)

    A servlet stays in memory, so it doesnt haveto be reloaded each time

    There is only one instance handling multiplerequests, not a separate instance for every

    request A variety of different languages were used to

    build CGI programs. These included C, C++,and Perl. Where as Servlet are coded in java

  • 7/30/2019 Unit 5 Servlet

    10/105

    10

    Servlets vs. CGI scripts

    CGI suffered serious performanceproblems. It was expensive in terms ofprocessor and memory resources to createa separate process for each client request.

    It was also expensive to open and closedatabase connections for each clientrequest.

    In addition, the CGI programs were notplatform-independent. Servlet is platform-independent.

  • 7/30/2019 Unit 5 Servlet

    11/105

    11

    What are the advantages of servlets?

    Portability

    Portable across operating systems and across webservers.

    Power Harness the full power of the core Java APIs: networking

    and URL access, multithreading, image manipulation,data compression, JDBC.

    Efficiency & Endurance

    Memory resident, so invocation highly efficientnoprocess to spawn or interpreter to invoke.

  • 7/30/2019 Unit 5 Servlet

    12/105

    12

    What are the advantages of servlets?

    (Contd)

    Safety

    Support safe programming since inherit Javas strong typesafety, exception-handling mechanism.

    Security

    the Java security manager on the server enforces a set ofrestrictions to protect the resources on a server machine

    Elegance Code is clean, object-oriented, modular, and simple (i.e..

    Session tracking, cookie).

    Integration

    Tightly integrated with the servertranslate file paths,perform logging, check authorization, and MIME type mapping.

  • 7/30/2019 Unit 5 Servlet

    13/105

    13

    What are the disadvantages of

    servlets?

    Developers MUST know JAVA

    Web Administrator will need to learn howto install and maintain Java Servlets

    Less choice of languages (CGI scripts canbe in any language)

    Tedious uses of out.println() statements

    Can be remedied by using Java Server Page(JSP)

  • 7/30/2019 Unit 5 Servlet

    14/105

    14

    Servlet Container

    A servlet runs inside a Servlet container.

    A Servlet container is the hosting

    environment for Java Servlets. A compilerplus run-time hosting environment forServlets.

    Ex : Tomcat is a Servlet container whichruns inside a Web server, Apache.

  • 7/30/2019 Unit 5 Servlet

    15/105

    15

    What is HTTP

    Hypertext Transfer Protocol is used to describehow HTML documents are sent over the Internet.

    It is stateless protocol HTTP Request Model

    A client application, such as web browser opens a socketto the web servers HTTP port (80) Through the connection, the client writes an ASCII text

    request line, followed by zeros and more HTTP headers,an empty line, and any data that accompanies therequest

    The web server parses the request and locates thespecified resource The server writes a copy of the resource to the socket,

    where its read by the client The server closes the connection

  • 7/30/2019 Unit 5 Servlet

    16/105

    16

    HTTP Request methodsMethod Description

    GET A simple request to retrieve identified in the URI

    HEAD Same as GET, except server doesnt return the requesteddocument. The server returns only the status line and

    headers

    POST A request for the server to accept data that will be writtento the clients output stream

    PUT A request for the server to store the data in the request asthe new contents of the specified URI

    DELETE A request for the server to delete the resource named inthe URI

    OPTIONS A request for information about what request methods theserver supports

    TRACE A request for the web server to echo the HTTP request andits headers

    CONNECT A documented but currently unimplemented methodreserved for use with a tunneling proxy.

  • 7/30/2019 Unit 5 Servlet

    17/105

    17

    Flow of execution in the Servlet Environment

    1. The browser sends an HTTP request to the Web server forexecuting a Servlet.

    2. The Web server hands it over to the servlet container, afterproviding the appropriate execution environment.

    3. The Servlet container loads and executes the Servlet (.class fileof the Servlet) by interpreting its contents via the JVM. Theresult is usually some HTML output.

    4. This HTML output is sent back to the Web browser via the webserver, as a part of the HTTP response.

  • 7/30/2019 Unit 5 Servlet

    18/105

    18

    Apache

    Apache is a verypopular server 66% of the web sites on the Internet use

    Apache

    Apache is: Full-featured and extensible

    Efficient

    Robust

    Secure (at least, more secure than otherservers)

    Up to date with current standards

    Open source

    Free

  • 7/30/2019 Unit 5 Servlet

    19/105

    19

    Ports

    A port is a connection between a server and aclient Ports are identified by positive integers

    A port is a software notion, not a hardware notion, so

    there may be very many of them A service is associated with a specific port

    Typical port numbers: 21FTP, File Transfer Protocol

    22SSH, Secure Shell

    25SMTP, Simple Mail Transfer Protocol 53DNS, Domain Name Service

    80HTTP, Hypertext Transfer Protocol

    8080HTTP (used for testing HTTP)

    7648, 7649CU-SeeMe

    These are the ports

    of most interest to us

  • 7/30/2019 Unit 5 Servlet

    20/105

    20

    Tomcat Tomcat is the Servlet Engine than handles

    servlet requests for Apache

    Tomcat is a helper application for Apache

    Its best to think of Tomcat as a servlet container

    Its easier to install Tomcat standalone than aspart of Apache

    By itself, Tomcat can handle web pages, servlets,

    and JSP

    Apache and Tomcat are open source (andtherefore free)

  • 7/30/2019 Unit 5 Servlet

    21/105

    21

  • 7/30/2019 Unit 5 Servlet

    22/105

    22

    Servlet lifecycle

    Servlet initialization -init() method

    Happens once in lifecycle

    Service client requests-service() method happens once for every client request

    Servlet destruction- destroy() method happens once in life cycle

  • 7/30/2019 Unit 5 Servlet

    23/105

    23

    Servlet Life Cycle

  • 7/30/2019 Unit 5 Servlet

    24/105

    24

    Servlet Life Cycle

    A user enters a Uniform Resource Locator(URL) to a Web browser. The browserthen generates an HTTP request for thisURL. This request is then sent to theappropriate server.

    This HTTP request is received by the Webserver. The server maps this request to aparticular servlet.

    The servlet is dynamically retrieved andloaded into the address space of theserver.

  • 7/30/2019 Unit 5 Servlet

    25/105

    25

    Servlet Life Cycle

    The server invokes the init( ) method of theservlet. This method is invoked only when theservlet is first loaded into memory. It is possibleto pass initialization parameters to the servlet so

    it may configure itself. The server invokes the service( ) method of the

    servlet. This method is called to process the HTTPrequest. You will see that it is possible for the

    servlet to read data that has been provided in theHTTP request. It may also formulate an HTTPresponse for the client.

  • 7/30/2019 Unit 5 Servlet

    26/105

    26

    Servlet Life Cycle

    The servlet remains in the servers address spaceand is available to process any other HTTPrequests received from clients. The service( )method is called for each HTTP request.

    Finally, the server may decide to unload theservlet from its memory. The algorithms by whichthis determination is made are specific to eachserver. The server calls the destroy( ) methodto relinquish any resources such as file handles

    that are allocated for the servlet. Important data may be saved to a persistent

    store. The memory allocated for the servlet andits objects can then be garbage collected.

  • 7/30/2019 Unit 5 Servlet

    27/105

    27

    Installation of Apache Tomcat

    First install j2sdk1.4.2_13 for access of Java classes & interfaces asthe servlet is written in Java language.

    Set the environment variable PATH to c:\j2sdk1.4.2_13\bin;c:\j2sdk1.4.2_13\lib

    Next install Tomcat

    Create a new SYSTEM environment variable CLASSPATH toc:\Program Files\Apache Group\Tomcat 4.1\common\lib\servlet.jar

    Alternatively, you can specify this class file when you compile theservlets.

    For example, the following command compiles the first servlet

    example: javac HelloServlet.java -classpath "C:\Program Files\Apache Tomcat

    4.0\common\lib\servlet.jar"

    To execute already provided examples of servlet

    In Internet Explorer add the URL http://localhost:8080

  • 7/30/2019 Unit 5 Servlet

    28/105

    28

    Execution in Tomcat

    Create .java file in c:\j2sdk1.4.2_13\bin

    Compile it there usingjavac filename.java

    Copy the .class file to Tomcat server. C:\ProgramFiles\Apache Group\Tomcat4.1\webapps\examples\WEB-INF\classes\

    Start the Tomcat server and minimize the

    window.

    Open Internet Explorer and in the URL enterhttp://localhost:8080/examples/servlet/filename

  • 7/30/2019 Unit 5 Servlet

    29/105

    29

    Steps to create Servlet

    Create and compile the servlet sourcecode.

    Start Tomcat.

    Start a Web browser and request theservlet.

  • 7/30/2019 Unit 5 Servlet

    30/105

    30

    Create and compile the servlet source

    code

    create a file named HelloServletpro.java that contains thefollowing program

    import java.io.*;import javax.servlet.*;public class HelloServletpro extends GenericServlet {public void service(ServletRequest request,

    ServletResponse response)throws ServletException, IOException {response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("Hello welcome to servlet programming!");pw.close();}} Copy the .class file to Tomcat server. C:\Program Files\Apache

    Group\Tomcat 4.1\webapps\examples\WEB-INF\classes\

  • 7/30/2019 Unit 5 Servlet

    31/105

    31

    Explanation of program First, note that it imports thejavax.servlet package.

    This package contains the classes and interfaces required to buildservlets.

    Next, the program defines HelloServlet as a subclass ofGenericServlet. The GenericServlet class provides functionality that makes it easy to

    handle requests and responses. Inside HelloServet, the service( ) method (which is inherited from

    GenericServlet) is overridden. This method handles requests from aclient. Notice that the first argument is a ServletRequest object.

    This enables the servlet to read data that is provided via the clientrequest.

    The second argument is a ServletResponse object. This enables the servlet to formulate a response for the client.

    The call to setContentType( ) establishes the MIME type of the HTTPresponse. In this program, the MIME type is text/html. This indicates that the

    browser should interpret the content as HTML source code. Next, the getWriter( ) method obtains a PrintWriter.

    Anything written to this stream is sent to the client as part of the HTTPresponse.

    Then println( ) is used to write some simple HTML source code as theHTTP response.

  • 7/30/2019 Unit 5 Servlet

    32/105

    32

    Start Tomcat

    As explained, to start Tomcat, select StartTomcat in the Start | Programs menu, orrun

    startup.bat from the C:\ProgramFiles\Apache Tomcat 4.0\bin\directory.

  • 7/30/2019 Unit 5 Servlet

    33/105

    33

    Start a Web Browser and Request the

    Servlet

    Start a Web browser and enter the URLshown here:

    http://localhost:8080/examples/servlet/HelloS

    ervletpro Alternatively, you may enter the URL

    shown here:

    http://127.0.0.1:8080/examples/servlet/Hello

    Servletpro

  • 7/30/2019 Unit 5 Servlet

    34/105

    34

    Servlet Architecture

    javax.servlet.Servlet interface

    javax.servlet.GenericServlet and

    javax.servlet.http.HttpServlet class

    Sun has provided a Java class calledHttpServlet having methods for

    initialization, servicing, and destruction ofServlets. A new Servlet has to be writtenby extending from HttpServlet class.

  • 7/30/2019 Unit 5 Servlet

    35/105

    35

    The Servlet API

    javax.servlet

    javax.servlet.http

  • 7/30/2019 Unit 5 Servlet

    36/105

    36

    Thejavax.servlet Package

  • 7/30/2019 Unit 5 Servlet

    37/105

    37

    Thejavax.servlet Package

  • 7/30/2019 Unit 5 Servlet

    38/105

    38

    Servlet Interface

  • 7/30/2019 Unit 5 Servlet

    39/105

    39

    ServletConfig Interface

  • 7/30/2019 Unit 5 Servlet

    40/105

    40

    ServletContext Interface

  • 7/30/2019 Unit 5 Servlet

    41/105

    41

    ServletRequest Interface

  • 7/30/2019 Unit 5 Servlet

    42/105

    42

    ServletRequest Interface

  • 7/30/2019 Unit 5 Servlet

    43/105

    43

    ServletRequest Interface

  • 7/30/2019 Unit 5 Servlet

    44/105

    44

    ServletResponse Interface

  • 7/30/2019 Unit 5 Servlet

    45/105

    45

    SingleThreadModel Interface

    only a single thread will execute theservice( ) at a time

    First, it can create several instances of the

    servlet. Second, it can synchronize access to the

    servlet

    No constant, no methods declared

  • 7/30/2019 Unit 5 Servlet

    46/105

    46

    GenericServlet Class

    Basic life cycle of servlet

    Implements servlet and servletconfiginterface

    void log(String s) void log(String s, Throwable e)

    a method to append a string to the server logfile

  • 7/30/2019 Unit 5 Servlet

    47/105

    47

    ServletInputStream Class

    Extends InputStream

    Implemented by the server

    It defines the default constructor.

    int readLine(byte[ ] buffer, int offset, int size)throws IOException

    Here, bufferis the array into which size bytes areplaced starting at offset. The method returns theactual number of bytes read or 1 if an end-of-stream condition is encountered.

  • 7/30/2019 Unit 5 Servlet

    48/105

    48

    ServletOutputStream Class

    extends OutputStream

    implemented by the server

    A default constructor is defined.

    the print( ) and println( ) methods

  • 7/30/2019 Unit 5 Servlet

    49/105

    49

    Servlet Exception Classes

    javax.servlet defines two exceptions.

    The ServletException, which indicatesthat a servlet problem has occurred.

    The UnavailableException, whichextends ServletException. It indicatesthat a servlet is unavailable.

  • 7/30/2019 Unit 5 Servlet

    50/105

    50

    Servlets

    A servlet is any class that implements thejavax.servlet.Servlet interface

    In practice, most servlets extend thejavax.servlet.http.HttpServlet class

    Some servlets extendjavax.servlet.GenericServlet instead

    Servlets, like applets, usually lack a mainmethod, but must implement or overridecertain other methods

  • 7/30/2019 Unit 5 Servlet

    51/105

    51

    Example

  • 7/30/2019 Unit 5 Servlet

    52/105

    52

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

    // Get print writer.

    PrintWriter pw = response.getWriter();// Get enumeration of parameter names.Enumeration e = request.getParameterNames();

    // Display parameter names and values.while(e.hasMoreElements()) {String pname = (String)e.nextElement();pw.print(pname + " = ");String pvalue = request.getParameter(pname);pw.println(pvalue);}pw.close();}}

    PostParametersServlet.java

    http://c/j2sdk1.4.2_13/bin/PostParametersServlet.javahttp://c/j2sdk1.4.2_13/bin/PostParametersServlet.java
  • 7/30/2019 Unit 5 Servlet

    53/105

    53

    How to Run

    Compile the servlet and perform thesesteps to test this example:

    1. Start Tomcat (if it is not already

    running). 2. Display the Web page in a browser.

    3. Enter an employee name and phonenumber in the text fields.

    4. Submit the Web page.

  • 7/30/2019 Unit 5 Servlet

    54/105

    54

    javax.servlet.http Package

  • 7/30/2019 Unit 5 Servlet

    55/105

    55

    HttpServletRequest

  • 7/30/2019 Unit 5 Servlet

    56/105

    56

  • 7/30/2019 Unit 5 Servlet

    57/105

    57

  • 7/30/2019 Unit 5 Servlet

    58/105

    58

    HttpServletResponse

  • 7/30/2019 Unit 5 Servlet

    59/105

    59

  • 7/30/2019 Unit 5 Servlet

    60/105

    60

    HttpSession

    All of these methods throw an IllegalStateException ifthe session has already been invalidated

  • 7/30/2019 Unit 5 Servlet

    61/105

    61

  • 7/30/2019 Unit 5 Servlet

    62/105

    62

    HttpSessionBindingListener

    Is implemented by objects that need to be

    notified when they are bound to or unbound froman HTTP session.

    void valueBound(HttpSessionBindingEvent e)

    void valueUnbound(HttpSessionBindingEvent e)

    Here, e is the event object that describes thebinding.

  • 7/30/2019 Unit 5 Servlet

    63/105

    63

    Cookie Class

    A cookie is stored on a client and contains stateinformation.

    Cookies are valuable for tracking user activities A servlet can write a cookie to a users machine via the

    addCookie( ) method of the HttpServletResponseinterface

    Cookie data includes The name of the cookie The value of the cookie The expiration date of the cookie The domain and path of the cookie

    Constructor Cookie(String name, String value)

  • 7/30/2019 Unit 5 Servlet

    64/105

    64

    Cookie Class

  • 7/30/2019 Unit 5 Servlet

    65/105

    65

  • 7/30/2019 Unit 5 Servlet

    66/105

    66

    HttpServlet Class

    It extends GenericServlet class

  • 7/30/2019 Unit 5 Servlet

    67/105

    67

  • 7/30/2019 Unit 5 Servlet

    68/105

    68

    HttpSessionEvent Class

    It encapsulates session events

    It extents EventObject and is generatedwhen a change occurs to the session

    HttpSessionEvent(HttpSession session) session is the source of the event

    HttpSession getSession( )

    It returns the session in which the eventoccurred.

  • 7/30/2019 Unit 5 Servlet

    69/105

    69

    HttpSessionBindingEvent Class

    It extends HttpSessionEvent HttpSessionBindingEvent(HttpSession

    session, String name)

    HttpSessionBindingEvent(HttpSessionsession, String name, Object val) Here, session is the source of the event and

    name is the name associated with the objectthat is being bound or unbound. If an attribute

    is being bound or unbound, its value is passedin val.

  • 7/30/2019 Unit 5 Servlet

    70/105

    70

    methods

    String getName( ) obtains the name that is being bound or

    unbound

    HttpSession getSession( ) obtains the session to which the listener is

    being bound or unbound

    Object getValue( ) obtains the value of the attribute that is being

    bound or unbound

  • 7/30/2019 Unit 5 Servlet

    71/105

    71

    Servlets

    A servlet is any class that implements thejavax.servlet.Servlet interface

    In practice, most servlets extend thejavax.servlet.http.HttpServlet class

    Some servlets extendjavax.servlet.GenericServlet instead

    Servlets, like applets, usually lack a mainmethod, but must implement or overridecertain other methods

  • 7/30/2019 Unit 5 Servlet

    72/105

    72

    Important servlet methods, I When a servlet is first started up, its init(ServletConfig config)method iscalled

    init should perform any necessary initializations init is called only once, and does not need to be thread-safe

    (syncronization not required)

    Every servlet request results in a call to

    service(ServletRequest request, ServletResponse response) service calls another method depending on the type of service

    requested Usually you would override the called methods of interest, not service

    itself service handles multiple simultaneous requests, so it and the methods

    it calls must be thread safe (syncronization required)

    When the servlet is shut down, destroy()is called destroy is called only once, but must be thread safe (because other

    threads may still be running)

  • 7/30/2019 Unit 5 Servlet

    73/105

    73

    HTTP requests

    When a request is submitted from a Web page, itis almost always a GET or a POST request

    The HTTP tag has an attribute action will bethe URL,method whose value can be "get" or"post"

    The "get" action results in the form informationbeing put after a ? in the URL

    Example:http://www.google.com/search?hl=en&ie=UTF-8&oe=UTF-

    8&q=servlets

    The& separates the various parameters

    Only a limited amount of information can be sent thisway

    "put" can send large amounts of information

  • 7/30/2019 Unit 5 Servlet

    74/105

    74

    Important servlet methods, II

    The service method dispatches the following kinds of requests:DELETE, GET, HEAD, OPTIONS, POST, PUT, and TRACE

    A GET request is dispatched to the doGet(HttpServletRequestrequest, HttpServletResponse response)method

    A POST request is dispatched to the doPost(HttpServletRequestrequest, HttpServletResponse response) method

    These are the two methods you will usually override

    doGet and doPost typically do the same thing, so usually you do

    the real work in one, and have the other just call it

    public void doGet(HttpServletRequest request,

    HttpServletResponse response) {

    doPost(request, response);

    }

  • 7/30/2019 Unit 5 Servlet

    75/105

    75

    HTTP requests & responses with respect to Servlets

    The browsers HTTP request is sent to the server. The servlets doGet() method receives this request as a

    parameter.

    Similarly, when the server needs to send back an HTTP response,it populates the corresponding attributes or calls methods in the

    other parameter HttpServletResponse, which is used to send backinformation to the browser in the form of an HTTP response.

  • 7/30/2019 Unit 5 Servlet

    76/105

    76

    Hello World Example A (.java)

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

    public class HelloServlet extends HttpServlet{public void doGet(HttpServletRequest request, HttpServletResponse response) throws

    IOException, ServletException

    {response.setContentType("text/html");PrintWriter out = response.getWriter();out.println("");out.println("");out.println("");out.println("Hello World!");

    out.println("");out.println("");out.println("Hello World!");out.println("");out.println("");}}

    http://localhost:8080/examples/servlet/HelloServlet

    http://localhost:8080/examples/servlet/HelloServlethttp://localhost:8080/examples/servlet/HelloServlet
  • 7/30/2019 Unit 5 Servlet

    77/105

    77

    The superclass

    public class HelloServlet extends HttpServlet {

    Every class must extend GenericServlet or a subclass ofGenericServlet

    GenericServletis protocol independent, so you couldwrite a servlet to process any protocol

    In practice, you almost always want to respond to anHTTP request, so you extendHttpServlet

    A subclass ofHttpServlet must override at least onemethod, usually one doGet, doPost, doPut, doDelete, initand destroy, or getServletInfo

  • 7/30/2019 Unit 5 Servlet

    78/105

    78

    The doGet method

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException {

    This method services a GET request

    The method uses request to get the information that was

    sent to it The method does not return a value; instead, it uses

    response to get an I/O stream, and outputs its response

    Since the method does I/O, it can throw an IOException

    Any other type of exception should be encapsulated as a

    ServletException The doPost method works exactlythe same way

  • 7/30/2019 Unit 5 Servlet

    79/105

    79

    Parameters to doGet

    Input is from the HttpServletRequestparameter

    Output is via the HttpServletResponseobject,which we have named response

    I/O in Java is very flexible but also quitecomplex, so this object acts as an assistant

  • 7/30/2019 Unit 5 Servlet

    80/105

    80

    Using the HttpServletResponse

    The second parameter to doGet(or doPost) isHttpServletResponse response

    Everything sent via the Web has a MIME type

    The first thing we mustdo with responseis set the

    MIME type of our reply:response.setContentType("text/html");

    This tells the client to interpret the page as HTML

    Because we will be outputting character data, we

    need a PrintWriter, handily provided for us by thegetWritermethod ofresponse:PrintWriter out = response.getWriter();

    Now were ready to create the actual page to be

    returned

  • 7/30/2019 Unit 5 Servlet

    81/105

    81

    Using the PrintWriter

    From here on, its just a matter of using ourPrintWriter, named out, to produce the Web page

    First we create a header string:String docType =

    "\n";

    This line is technically required by the HTML spec

    Browsers mostly dont care, but HTML validators docare

    Then use the println method ofout one or moretimesout.println(docType +

    "\n" +

    " ... ");

  • 7/30/2019 Unit 5 Servlet

    82/105

    82

    Input to a servlet

    A GET request supplies parameters in the formURL?name=value&name=value&name=value Actual spaces in the parameter values are

    encoded by+ signs Other special characters are encoded in hex;

    for example, an ampersand is represented by%26

    Parameter names can occur more than once, withdifferent values

    A POST request supplies parameters in the same

    syntax, only it is in the body section of therequest and is therefore harder for the user tosee

  • 7/30/2019 Unit 5 Servlet

    83/105

    83

    Getting the parameters

    Input parameters are retrieved via messages tothe HttpServletRequest object request Most of the interesting methods are inherited from the

    superinterface ServletRequest

    public Enumeration getParameterNames() Returns an Enumeration of the parameter names

    If no parameters, returns an empty Enumeration

    public String getParameter(String name) Returns the value of the parameter name as a String

    If the parameter doesnt exist, returns null Ifname has multiple values, only the first is returned

    public String[] getParameterValues(name) Returns an array of values of the parameter name

    If the parameter doesnt exist, returns null

  • 7/30/2019 Unit 5 Servlet

    84/105

    84

    Example of input parameters

    public void doGet(HttpServletRequest request,HttpServletResponse response) {

    ...

    ...

    out.println("Hello");String names[] =

    request.getParameterValues("name");

    if (names != null)

    for (int i = 0; i < names.length; i++)

    out.println(" " + names[i]);

    out.println("Done");

    }

  • 7/30/2019 Unit 5 Servlet

    85/105

    85

    Java review: Data from Strings

    All parameter values are retrieved as Strings

    Frequently these Strings represent numbers, and youwant the numeric value

    int n = new Integer(param).intValue();

    double d = new Double(param).doubleValue(); byte b = new Byte(param).byteValue();

    Similarly for short, float, and long

    These can all throw a NumberFormatException,which is a subclass ofRuntimeException

    boolean p = new Boolean(param).booleanValue(); char c =param.charAt(0);

  • 7/30/2019 Unit 5 Servlet

    86/105

    86

    form.html Example

    Introductions

    If you don't mind me asking, what is your name?

    form.html

    http://localhost/var/www/apps/conversion/tmp/material/php%20material/Downloads/form.htmlhttp://localhost/var/www/apps/conversion/tmp/material/php%20material/Downloads/form.html
  • 7/30/2019 Unit 5 Servlet

    87/105

    87

    Hello.java Example

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

    public class Hello extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)

    throws ServletException, IOException {

    res.setContentType("text/html");PrintWriter out = res.getWriter();

    String name = req.getParameter("name");

    out.println("");out.println("Hello, " + name + "");out.println("");out.println("Hello, " + name);out.println("");

    }}

    Handling HTTP Get Request

  • 7/30/2019 Unit 5 Servlet

    88/105

    88

    g q

    Servlet Example 1 (.html file)

    Servlet Example Using an Input Form

    Forms Example Using Servlets

    Enter your email ID:

    form2.html

    Handling HTTP Get Request

    http://localhost/var/www/apps/conversion/tmp/material/php%20material/Downloads/form2.htmlhttp://localhost/var/www/apps/conversion/tmp/material/php%20material/Downloads/form2.html
  • 7/30/2019 Unit 5 Servlet

    89/105

    89

    g q

    Servlet Example 1 (.java file)

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

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

    { String email;email = request.getParameter(email);response.setContentType(text/html); PrintWriter out = response.getWriter();

    out.println(); out.println();out.println(Servlet Example);

    out.println();out.println();out.println(

    The email ID you have entered is :+email+

    );out.println();out.println(); out.close();

    }}

    EmailServlet.java

    http://c/j2sdk1.4.2_13/bin/EmailServlet.javahttp://c/j2sdk1.4.2_13/bin/EmailServlet.java
  • 7/30/2019 Unit 5 Servlet

    90/105

    90

    Servlet Example 2 (.java file)import java.io.*;

    import java.net.*;import javax.servlet.*;import javax.servlet.http.*;

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

    {response.setContentType(text/html);PrintWriter out = response.getWriter();

    out.println();out.println();out.println(Dollars to Rupees Conversion Chart);out.println();out.println();out.println(Currency Conversion Chart);out.println();out.println();out.println(Dollars);out.println(Rupees);out.println();for (int dollars=1; dollars

  • 7/30/2019 Unit 5 Servlet

    91/105

    91

    Servlet Example 3 (.html file)

    Color:

    RedGreenBlue

    Form3.html

    Handling HTTP Post Request

    http://localhost/var/www/apps/conversion/tmp/material/php%20material/Downloads/form3.htmlhttp://localhost/var/www/apps/conversion/tmp/material/php%20material/Downloads/form3.html
  • 7/30/2019 Unit 5 Servlet

    92/105

    92

    Servlet Example 3 (.java file)

    import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class ColorPostServlet extends HttpServlet {public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

    String color = request.getParameter("color");response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("The selected color is: ");pw.println(color);pw.close();

    }}

    ColorPostServlet.java

    http://c/j2sdk1.4.2_13/bin/ColorPostServlet.javahttp://c/j2sdk1.4.2_13/bin/ColorPostServlet.java
  • 7/30/2019 Unit 5 Servlet

    93/105

    93

    Using Cookies

  • 7/30/2019 Unit 5 Servlet

    94/105

    94

    Cookie

    What is a cookie?

    A cookie is a piece of textual information

    Send by the Web server to the client

    browser Every time the browser visits the Web site

    again, the cookie is sent unchanged backto the server

  • 7/30/2019 Unit 5 Servlet

    95/105

    95

    Cookie

    A cookie is a string upto 4K characters that you tell theWeb browser to store on a visitors hard drive.

    Cookies give you a way to store information about the sitevisitor that can retrieve each time the visitor returns to the

    site so long as the visitor uses the same Web browser andcomputer system.

    Each Web browser type stores all cookie data in a single fileunique to the browser.

    Without cookies there is no way of determining whathappened the last time the visitor came to the site or evenif the visitor has ever been to your site before.

  • 7/30/2019 Unit 5 Servlet

    96/105

    96

    Benefits of Cookies

    Identification of a user E-commerce

    Poll

    Customizing a site Portals

    Personal Views

    Avoiding login

    Useful for sites that dont require high security

  • 7/30/2019 Unit 5 Servlet

    97/105

    97

    Drawbacks of Cookies

    User can deny cookies in his Web browser

    Might be a privacy thread

    E.g. search engines remember user specificsearch topics

    Handling cookies using Servlets

  • 7/30/2019 Unit 5 Servlet

    98/105

    98

    (cookie.html)

    Enter a value for MyCookie:

    Handling cookies using Servlets

    http://c/j2sdk1.4.2_13/bin/AddCookieServlet.java
  • 7/30/2019 Unit 5 Servlet

    99/105

    99

    (AddCookieServlet.java)import java.io.*;import javax.servlet.*;import javax.servlet.http.*;

    public class AddCookieServlet extends HttpServlet {public void doPost(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

    // Get parameter from HTTP request.

    String data = request.getParameter("data");// Create cookie.Cookie cookie = new Cookie("MyCookie", data);

    // Add cookie to HTTP response.response.addCookie(cookie);

    // Write output to browser.response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("MyCookie has been set to");

    pw.println(data);pw.close();}}

    Handling cookies using Servlets

    http://c/j2sdk1.4.2_13/bin/AddCookieServlet.javahttp://c/j2sdk1.4.2_13/bin/AddCookieServlet.javahttp://c/j2sdk1.4.2_13/bin/GetCookiesServlet.java
  • 7/30/2019 Unit 5 Servlet

    100/105

    100

    (GetCookiesServlet.java)import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class GetCookiesServlet extends HttpServlet {public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {

    // Get cookies from header of HTTP request.Cookie[] cookies = request.getCookies();

    // Display these cookies.response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.println("");for(int i = 0; i < cookies.length; i++) {String name = cookies[i].getName();String value = cookies[i].getValue();pw.println("name = " + name +"; value = " + value);

    }pw.close();}}

    http://c/j2sdk1.4.2_13/bin/GetCookiesServlet.javahttp://c/j2sdk1.4.2_13/bin/GetCookiesServlet.java
  • 7/30/2019 Unit 5 Servlet

    101/105

    101

    Session Tracking

    S i T ki

  • 7/30/2019 Unit 5 Servlet

    102/105

    102

    Session Tracking

    HTTP is a stateless protocol. Each request isindependent of the previous one.

    However, in some applications, it is necessary to

    save state information so that information can becollected from several interactions between abrowser and a server. Sessions provide such amechanism.

    Session state is shared among all the servletsthat are associated with a particular client.

    P d

  • 7/30/2019 Unit 5 Servlet

    103/105

    103

    Procedure

    A session can be created via the getSession( )method of HttpServletRequest. AnHttpSession object is returned.

    This object can store a set of bindings thatassociate names with objects. The setAttribute( )

    getAttribute( )

    getAttributeNames( )

    removeAttribute( ) methods ofHttpSession managethese bindings.

    D S l j

    When you first request this servlet, the browserdisplays one line with the current date and timeinformation. On subsequent invocations, two linesare displayed The first line shows the date and

  • 7/30/2019 Unit 5 Servlet

    104/105

    104

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

    public class DateServlet extends HttpServlet{

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

    {// Get the HttpSession object.HttpSession hs = request.getSession(true);

    // Get writer.response.setContentType("text/html");PrintWriter pw = response.getWriter();pw.print("");

    // Display date/time of last access.Date date = (Date)hs.getAttribute("date");

    if(date != null){

    pw.print("Last access: " + date + "
    ");}

    // Display current date/time.date = new Date();hs.setAttribute("date", date);pw.println("Current date: " + date);

    }

    }

    are displayed. The first line shows the date andtime when the servlet was last accessed. Thesecond line shows the current date and time.

    C:\j2sdk1.4.2_13\bin\DateServlet.java

    E l i i f D S l j

    http://c/j2sdk1.4.2_13/bin/DateServlet.javahttp://c/j2sdk1.4.2_13/bin/DateServlet.javahttp://c/j2sdk1.4.2_13/bin/DateServlet.javahttp://c/j2sdk1.4.2_13/bin/DateServlet.javahttp://c/j2sdk1.4.2_13/bin/DateServlet.javahttp://c/j2sdk1.4.2_13/bin/DateServlet.javahttp://c/j2sdk1.4.2_13/bin/DateServlet.javahttp://c/j2sdk1.4.2_13/bin/DateServlet.java
  • 7/30/2019 Unit 5 Servlet

    105/105

    Explaination of DateServlet.java

    The getSession( ) method gets the current session. A newsession is created if one does not already exist.

    The getAttribute( ) method is called to obtain the objectthat is bound to the name date.

    That object is a Date object that encapsulates the date andtime when this page was last accessed. (Of course, there isno such binding when the page is first accessed.)

    A Date object encapsulating the current date and time isthen created. The setAttribute( ) method is called to bindthe name date to this object.