serv let complete tutorial

Upload: ankit-jain

Post on 03-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 7/28/2019 Serv Let Complete Tutorial

    1/77

    Tutorials Point, Simply Easy Learning

    1 | P a g e

    Servlets Tutorial

    Tutorialspoint.com

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

    Servlets have access to the entire family of Java APIs, including the JDBC API toaccess enterprise databases. This tutorial gives an initial push to start you with JavaServlets. For more detail kindly checktutorialspoint.com/servlets

    What are Servlets?

    Java Servlets are programs that run on a Web or Application server and act as a middle layerbetween a request coming from a Web browser or other HTTP client and databases orapplications on the HTTP server.

    Using Servlets, you can collect input from users through web page forms, present records froma database or another source, and create web pages dynamically.

    Java Servlets often serve the same purpose as programs implemented using the CommonGateway Interface (CGI). But Servlets offer several advantages in comparison with the CGI.

    Performance is significantly better. Servlets execute within the address space of a Web server. It is not necessary to create

    a separate process to handle each client request.

    Servlets are platform-independent because they are written in Java. Java security manager on the server enforces a set of restrictions to protect the

    resources on a server machine. So servlets are trusted. The full functionality of the Java class libraries is available to a servlet. It can

    communicate with applets, databases, or other software via the sockets and RMImechanisms that you have seen already.

    Servlets Architecture:

    Following diagram shows the position of Servelts in a Web Application.

    Servlets Packages:

    Java Servlets are Java classes run by a web server that has an interpreter that supports theJava Servlet specification.

    http://www.tutorialspoint.com/jsphttp://www.tutorialspoint.com/servletshttp://www.tutorialspoint.com/servletshttp://www.tutorialspoint.com/servletshttp://www.tutorialspoint.com/servletshttp://www.tutorialspoint.com/jsp
  • 7/28/2019 Serv Let Complete Tutorial

    2/77

    Tutorials Point, Simply Easy Learning

    2 | P a g e

    Servlets can be created using thejavax.servlet andjavax.servlet.http packages, which are astandard part of the Java's enterprise edition, an expanded version of the Java class library thatsupports large-scale development projects.

    These classes implement the Java Servlet and JSP specifications. At the time of writing thistutorial, the versions are Java Servlet 2.5 and JSP 2.1.

    Java servlets have been created and compiled just like any other Java class. After you install theservlet packages and add them to your computer's Classpath, you can compile servlets with theJDK's Java compiler or any other current compiler.

    Setting up Java Development Kit

    This step involves downloading an implementation of the Java Software Development Kit (SDK)and setting up PATH environment variable appropriately.

    You can download SDK from Sun's Java servlet site:http://java.sun.com/products/servlet/.

    Once you download your Java implementation, follow the given instructions to install andconfigure the setup. 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_dirrespectively.

    If you are running Windows and installed the SDK in C:\jdk1.5.0_20, you would put thefollowing line in your C:\autoexec.bat file.

    set PATH=C:\jdk1.5.0_20\bin;%PATH%set JAVA_HOME=C:\jdk1.5.0_20

    Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, selectProperties, then Advanced, then Environment Variables. Then, you would update the PATH valueand press the OK button.

    On Unix (Solaris, Linux, etc.), if the SDK is installed in /usr/local/jdk1.5.0_20 and you use the Cshell, you would put the following into your .cshrc file.

    setenv PATH /usr/local/jdk1.5.0_20/bin:$PATHsetenv JAVA_HOME /usr/local/jdk1.5.0_20

    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.

    Setting up Web Server: Tomcat

    A number of Web Servers that support servlets are available in the market. Some web serversare freely downloadable and Tomcat is one of them.

    Apache Tomcat is an open source software implementation of the Java Servlet and JavaServerPages technologies and can act as a standalone server for testing servlets and can be integratedwith the Apache Web Server. Here are the steps to setup Tomcat on your machine:

    Download latest version of Tomcat fromhttp://tomcat.apache.org/. Once you downloaded the installation, unpack the binary distribution into a convenientlocation. For example in C:\apache-tomcat-5.5.29 on windows, or /usr/local/apache-

    http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/http://java.sun.com/products/servlet/http://tomcat.apache.org/http://tomcat.apache.org/http://tomcat.apache.org/http://tomcat.apache.org/http://java.sun.com/products/servlet/
  • 7/28/2019 Serv Let Complete Tutorial

    3/77

    Tutorials Point, Simply Easy Learning

    3 | P a g e

    tomcat-5.5.29 on Linux/Unix and create CATALINA_HOME environment variablepointing to these locations.

    Tomcat can be started by executing the following commands on windows machine:

    $CATALINA_HOME\bin\startup.bat

    or

    C:\apache-tomcat-5.5.29\bin\startup.bat

    Tomcat can be started by executing the following commands on Unix (Solaris, Linux, etc.)machine:

    $CATALINA_HOME/bin/startup.sh

    or

    /usr/local/apache-tomcat-5.5.29/bin/startup.sh

    After startup, the default web applications included with Tomcat will be available by visitinghttp://localhost:8080/. If everything is fine then it should display following result:

    Further information about configuring and running Tomcat can be found in the documentationincluded here, as well as on the Tomcat web site: http://tomcat.apache.org

    Tomcat can be stopped by executing the following commands on windows machine:

    C:\apache-tomcat-5.5.29\bin\shutdown

    Tomcat can be stopped by executing the following commands on Unix (Solaris, Linux, etc.)machine:

  • 7/28/2019 Serv Let Complete Tutorial

    4/77

    Tutorials Point, Simply Easy Learning

    4 | P a g e

    /usr/local/apache-tomcat-5.5.29/bin/shutdown.sh

    Setting up CLASSPATH

    Since servlets are not part of the Java Platform, Standard Edition, you must identify the servletclasses to the compiler.

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

    set CATALINA=C:\apache-tomcat-5.5.29set CLASSPATH=%CATALINA%\common\lib\servlet-api.jar;%CLASSPATH%

    Alternatively, on Windows NT/2000/XP, you could also right-click on My Computer, selectProperties, then Advanced, then Environment Variables. Then, you would update the

    CLASSPATH value and press the OK button.

    On Unix (Solaris, Linux, etc.), if you are using the C shell, you would put the following lines intoyour .cshrc file.

    setenv CATALINA=/usr/local/apache-tomcat-5.5.29setenv CLASSPATH $CATALINA/common/lib/servlet-api.jar:$CLASSPATH

    NOTE: Assuming that your development directory is C:\ServletDevel (Windows) or

    /usr/ServletDevel (Unix) then you would need to add these directories as well in CLASSPATH insimilar way as you have added above.

    Sample Code for Hello World:Following is the sample source code structure of a servlet example to write Hello World:

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

    // Extend HttpServlet classpublic class HelloWorld extends HttpServlet {

    private String message;

    public void init() throws ServletException{

    // Do required initializationmessage = "Hello World";

    }

    public void doGet(HttpServletRequest request,HttpServletResponse response)

    throws ServletException, IOException{

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

    // Actual logic goes here.PrintWriter out = response.getWriter();

  • 7/28/2019 Serv Let Complete Tutorial

    5/77

  • 7/28/2019 Serv Let Complete Tutorial

    6/77

    Tutorials Point, Simply Easy Learning

    6 | P a g e

    You are almost done, now let us start tomcat server using \bin\startup.bat (on windows) or /bin/startup.sh (on

    Linux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's addressbox. If everything goes fine, you would get following result:

    everything goes fine, you would get following result:

    Further Detail:

    Refer to the linkhttp://www.tutorialspoint.com/servlets

    List of Tutorials fromTutorialsPoint.com Learn JSP Learn Servlets Learn log4j Learn iBATIS Learn Java Learn JDBC

    Java Examples Learn Best Practices Learn Python Learn Ruby Learn Ruby on Rails Learn SQL Learn MySQL Learn AJAX Learn C Programming Learn C++ Programming Learn CGI with PERL Learn DLL

    Learn ASP.Net Learn HTML Learn HTML5 Learn XHTML Learn CSS Learn HTTP

    Learn JavaScript Learn jQuery Learn Prototype Learn script.aculo.us Web Developer's Guide Learn RADIUS Learn RSS Learn SEO Techniques Learn SOAP Learn UDDI Learn Unix Sockets Learn Web Services

    http://www.tutorialspoint.com/servletshttp://www.tutorialspoint.com/servletshttp://www.tutorialspoint.com/servletshttp://www.tutorialspoint.com/http://www.tutorialspoint.com/http://www.tutorialspoint.com/http://www.tutorialspoint.com/jsphttp://www.tutorialspoint.com/servlets/index.htmhttp://www.tutorialspoint.com/log4j/index.htmhttp://www.tutorialspoint.com/ibatis/index.htmhttp://www.tutorialspoint.com/java/index.htmhttp://www.tutorialspoint.com/jdbc/index.htmhttp://www.tutorialspoint.com/javaexamples/index.htmhttp://www.tutorialspoint.com/developers_best_practices/index.htmhttp://www.tutorialspoint.com/python/index.htmhttp://www.tutorialspoint.com/ruby/index.htmhttp://www.tutorialspoint.com/ruby-on-rails-2.1/index.htmhttp://www.tutorialspoint.com/sql/index.htmhttp://www.tutorialspoint.com/mysql/index.htmhttp://www.tutorialspoint.com/ajax/index.htmhttp://www.tutorialspoint.com/ansi_c/index.htmhttp://www.tutorialspoint.com/cplusplus/index.htmhttp://www.tutorialspoint.com/perl/perl_cgi.htmhttp://www.tutorialspoint.com/dll/index.htmhttp://www.tutorialspoint.com/asp.net/index.htmhttp://www.tutorialspoint.com/html/index.htmhttp://www.tutorialspoint.com/html5/index.htmhttp://www.tutorialspoint.com/xhtml/index.htmhttp://www.tutorialspoint.com/css/index.htmhttp://www.tutorialspoint.com/http/index.htmhttp://www.tutorialspoint.com/javascript/index.htmhttp://www.tutorialspoint.com/jquery/index.htmhttp://www.tutorialspoint.com/prototype/index.htmhttp://www.tutorialspoint.com/script.aculo.us/index.htmhttp://www.tutorialspoint.com/web_developers_guide/index.htmhttp://www.tutorialspoint.com/radius/index.htmhttp://www.tutorialspoint.com/rss/index.htmhttp://www.tutorialspoint.com/seo/index.htmhttp://www.tutorialspoint.com/soap/index.htmhttp://www.tutorialspoint.com/uddi/index.htmhttp://www.tutorialspoint.com/unix_sockets/index.htmhttp://www.tutorialspoint.com/webservices/index.htmhttp://www.tutorialspoint.com/webservices/index.htmhttp://www.tutorialspoint.com/unix_sockets/index.htmhttp://www.tutorialspoint.com/uddi/index.htmhttp://www.tutorialspoint.com/soap/index.htmhttp://www.tutorialspoint.com/seo/index.htmhttp://www.tutorialspoint.com/rss/index.htmhttp://www.tutorialspoint.com/radius/index.htmhttp://www.tutorialspoint.com/web_developers_guide/index.htmhttp://www.tutorialspoint.com/script.aculo.us/index.htmhttp://www.tutorialspoint.com/prototype/index.htmhttp://www.tutorialspoint.com/jquery/index.htmhttp://www.tutorialspoint.com/javascript/index.htmhttp://www.tutorialspoint.com/http/index.htmhttp://www.tutorialspoint.com/css/index.htmhttp://www.tutorialspoint.com/xhtml/index.htmhttp://www.tutorialspoint.com/html5/index.htmhttp://www.tutorialspoint.com/html/index.htmhttp://www.tutorialspoint.com/asp.net/index.htmhttp://www.tutorialspoint.com/dll/index.htmhttp://www.tutorialspoint.com/perl/perl_cgi.htmhttp://www.tutorialspoint.com/cplusplus/index.htmhttp://www.tutorialspoint.com/ansi_c/index.htmhttp://www.tutorialspoint.com/ajax/index.htmhttp://www.tutorialspoint.com/mysql/index.htmhttp://www.tutorialspoint.com/sql/index.htmhttp://www.tutorialspoint.com/ruby-on-rails-2.1/index.htmhttp://www.tutorialspoint.com/ruby/index.htmhttp://www.tutorialspoint.com/python/index.htmhttp://www.tutorialspoint.com/developers_best_practices/index.htmhttp://www.tutorialspoint.com/javaexamples/index.htmhttp://www.tutorialspoint.com/jdbc/index.htmhttp://www.tutorialspoint.com/java/index.htmhttp://www.tutorialspoint.com/ibatis/index.htmhttp://www.tutorialspoint.com/log4j/index.htmhttp://www.tutorialspoint.com/servlets/index.htmhttp://www.tutorialspoint.com/jsphttp://www.tutorialspoint.com/http://www.tutorialspoint.com/servlets
  • 7/28/2019 Serv Let Complete Tutorial

    7/77

    Tutorials Point, Simply Easy Learning

    7 | P a g e

    Learn ebXML Learn Euphoria Learn GDB Debugger Learn Makefile Learn Parrot Learn Perl Script Learn PHP Script Learn Six Sigma Learn SEI CMMI Learn WiMAX Learn Telecom Billing

    Learn XML-RPC Learn UML Learn UNIX Learn WSDL Learn i-Mode Learn GPRS Learn GSM Learn WAP Learn WML Learn Wi-Fi

    [email protected]

    http://www.tutorialspoint.com/ebxml/index.htmhttp://www.tutorialspoint.com/euphoria/index.htmhttp://www.tutorialspoint.com/gnu_debugger/index.htmhttp://www.tutorialspoint.com/makefile/index.htmhttp://www.tutorialspoint.com/parrot/index.htmhttp://www.tutorialspoint.com/perl/index.htmhttp://www.tutorialspoint.com/php/index.htmhttp://www.tutorialspoint.com/six_sigma/index.htmhttp://www.tutorialspoint.com/cmmi/index.htmhttp://www.tutorialspoint.com/wimax/index.htmhttp://www.tutorialspoint.com/telecom-billing/index.htmhttp://www.tutorialspoint.com/xml-rpc/index.htmhttp://www.tutorialspoint.com/uml/index.htmhttp://www.tutorialspoint.com/unix/index.htmhttp://www.tutorialspoint.com/wsdl/index.htmhttp://www.tutorialspoint.com/i-mode/index.htmhttp://www.tutorialspoint.com/gprs/index.htmhttp://www.tutorialspoint.com/gsm/index.htmhttp://www.tutorialspoint.com/wap/index.htmhttp://www.tutorialspoint.com/wml/index.htmhttp://www.tutorialspoint.com/wi-fi/index.htmhttp://www.tutorialspoint.com/http://www.tutorialspoint.com/http://www.tutorialspoint.com/http://www.tutorialspoint.com/wi-fi/index.htmhttp://www.tutorialspoint.com/wml/index.htmhttp://www.tutorialspoint.com/wap/index.htmhttp://www.tutorialspoint.com/gsm/index.htmhttp://www.tutorialspoint.com/gprs/index.htmhttp://www.tutorialspoint.com/i-mode/index.htmhttp://www.tutorialspoint.com/wsdl/index.htmhttp://www.tutorialspoint.com/unix/index.htmhttp://www.tutorialspoint.com/uml/index.htmhttp://www.tutorialspoint.com/xml-rpc/index.htmhttp://www.tutorialspoint.com/telecom-billing/index.htmhttp://www.tutorialspoint.com/wimax/index.htmhttp://www.tutorialspoint.com/cmmi/index.htmhttp://www.tutorialspoint.com/six_sigma/index.htmhttp://www.tutorialspoint.com/php/index.htmhttp://www.tutorialspoint.com/perl/index.htmhttp://www.tutorialspoint.com/parrot/index.htmhttp://www.tutorialspoint.com/makefile/index.htmhttp://www.tutorialspoint.com/gnu_debugger/index.htmhttp://www.tutorialspoint.com/euphoria/index.htmhttp://www.tutorialspoint.com/ebxml/index.htm
  • 7/28/2019 Serv Let Complete Tutorial

    8/77

    http://www.tutorialspoint.com/servlets/servlets-life-cycle.htm Copyright tutorialspoint.com

    SERVLETS - LIFE CYCLE

    A servlet life cycle can be def ined as the entire process f rom its creation till the dest ruct ion. Thefollowing are the paths followed by a servlet

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

    The servlet calls service() method to process a client's request .

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

    Finally, servlet is garbage collected by the garbage collect or of the JVM.

    Now let us discuss the life cycle methods in details.

    The init() method :

    The init method is designed to be called only once. It is called when the servlet is first created,and not called again for each user request. So, it is used for one-time initializat ions, just as withthe init method of applets.

    The servlet is normally created when a user first invokes a URL corresponding to the servlet, butyou can also specify that the servlet be loaded when the server is first started.

    When a user invokes a servlet , a single inst ance of each servlet gets created, with each userrequest result ing in a new thread that is handed off to doGet or doPost as appropriate. The init()method simply creates or loads some data that will be used throughout t he life of the servlet .

    The init method def inition looks like this:

    publicvoid init()throwsServletException{

    // Initialization code...}

    The service() method :

    The service() method is the main method to perform the actual task. The servlet container (i.e.web server) calls the service() method t o handle requests coming from the client( browsers) andto write the formatted response back to the client.

    Each t ime t he server receives a request for a servlet , the server spawns a new thread and callsservice. The service() method checks t he HTTP request type (GET, POST, PUT, DELETE, etc.) andcalls doGet , doPost, doPut, doDelete, et c. methods as appropriate.

    Here is the signature of this method:

    publicvoid service(ServletRequest request,

    ServletResponse response)

    throwsServletException,IOException{

    }

    The service () method is called by the container and service method invokes doGe, doPost, doPut,doDelete, etc. methods as appropriate. So you have nothing to do with service() method but youoverride either doGet() or doPost () depending on what type of request you receive from theclient.

    The doGet() and doPost () are most frequently used methods with in each service request . Hereare the signature of these two methods.

    The doGet() Method

    http://www.tutorialspoint.com/servlets/servlets-life-cycle.htm
  • 7/28/2019 Serv Let Complete Tutorial

    9/77

    A GET request results from a normal request for a URL or from an HTML form that has no METHODspecified and it should be handled by doGet () method.

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException{

    // Servlet code

    }

    The doPost() MethodA POST request results from an HTML form that specifically lists POST as t he METHOD and itshould be handled by doPost() method.

    publicvoid doPost(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException{

    // Servlet code

    }

    The destroy() method :

    The dest roy() method is called only once at t he end of the life cycle of a servlet . This methodgives your servlet a chance t o close database connect ions, halt background threads, write cookielists or hit counts to disk, and perform other such cleanup act ivities.

    After the dest roy() method is called, the servlet object is marked for garbage collect ion. Thedestroy method definition looks like this:

    publicvoid destroy(){

    // Finalization code...

    }

    Architecture Digram:The following figure depicts a typical servlet life-cycle scenario.

    First the HTTP request s coming to t he server are delegated to t he servlet container.

    The servlet container loads the servlet before invoking the service() method.

    Then the servlet container handles multiple requests by spawning mult iple threads, eachthread executing the service() method of a single inst ance of the servlet .

  • 7/28/2019 Serv Let Complete Tutorial

    10/77

  • 7/28/2019 Serv Let Complete Tutorial

    11/77

    http://www.tutorialspoint.com/servlets/servlets-first-example.htm Copyright tutorialspoint.com

    SERVLETS - EXAMPLES

    Servlets are Java classes which service HTTP requests and implement thejavax.servlet.Servletinterface. Web applicat ion developers typically write servlets t hat extend

    javax.servlet .http.Htt pServlet , an abstract class that implements the Servlet interface and isspecially designed to handle HTTP requests.

    Sample Code for Hello World:

    Following is the sample source code st ructure of a servlet example to write Hello World:

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    // Extend HttpServlet class

    publicclassHelloWorldextendsHttpServlet{

    privateString message;

    publicvoid init()throwsServletException

    {

    // Do required initialization

    message ="Hello World";

    }

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Set response content type

    response.setContentType("text/html");

    // Actual logic goes here.

    PrintWriterout= response.getWriter();

    out.println(""+ message +"");

    }

    publicvoid destroy()

    {

    // do nothing.

    }

    }

    Compiling a Servlet:

    Let us put above code if HelloWorld.java file and put this file in C:\ServletDevel (Windows) or/usr/ServletDevel (Unix) then you would need to add these direct ories as well in CLASSPATH.

    Assuming your environment is setup properly, go in ServletDevel directory and compileHelloWorld.java as follows:

    $ javac HelloWorld.java

    If the servlet depends on any other libraries, you have to include t hose JAR files on yourCLASSPATH as well. I have included only servlet-api.jar JAR file because I'm not using any otherlibrary in Hello World program.

    This command line uses the built- in javac compiler that comes with the Sun Microsystems JavaSoftware Development Kit (JDK). For this command to work properly, you have to include thelocation of the Java SDK that you are using in the PATH environment variable.

    If everything goes fine, above compilation would produce HelloWorld.class file in the same

    http://www.tutorialspoint.com/servlets/servlets-first-example.htmhttp://www.tutorialspoint.com/servlets/servlets-first-example.htm
  • 7/28/2019 Serv Let Complete Tutorial

    12/77

    directory. Next section would explain how a compiled servlet would be deployed in production.

    Servlet Deployment:

    By default , a servlet application is located at the path /webapps/ROOT and t he class file would reside in /webapps/ROOT/WEB-INF/classes.

    If you have a fully qualified class name ofcom.myorg.MyServlet , then this servlet class must

    be located in WEB-INF/classes/com/myorg/MyServlet .class.

    For now, let us copy HelloWorld.class into /webapps/ROOT/WEB-INF/classes and create following entries in web.xml file located in /webapps/ROOT/WEB-INF/

    HelloWorld

    HelloWorld

    HelloWorld

    /HelloWorld

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

    You are almost done, now let us start tomcat server using \bin\startup.bat (on windows) or /bin/startup.sh (onLinux/Solaris etc.) and finally type http://localhost:8080/HelloWorld in browser's addressbox. If everything goes fine, you would get following result:

  • 7/28/2019 Serv Let Complete Tutorial

    13/77

    http://www.tutorialspoint.com/servlets/servlets-form-data.htm Copyright tutorialspoint.com

    SERVLETS FORM DATA

    You must have come across many situations when you need to pass some information from yourbrowser to web server and ultimately to your backend program. The browser uses two methodsto pass this information to web server. These methods are GET Method and POST Method.

    GET method:

    The GET method sends the encoded user information appended to the page request. The pageand the encoded information are separated by the ? character as follows:

    http://www.test.com/hello?key1=value1&key2=value2

    The GET method is the defualt method to pass information from browser to web server and itproduces a long string that appears in your browser's Location:box. Never use the GET method ifyou have password or other sensitive information to pass to the server. The GET method has sizelimtation: only 1024 characters can be in a request st ring.

    This information is passed using QUERY_STRING header and will be accessible throughQUERY_STRING environment variable and Servlet handles this t ype of requests using doGet()method.

    POST method:

    A generally more reliable method of passing information to a backend program is the POSTmethod. This packages the information in exact ly the same way as GET methods, but instead ofsending it as a text st ring aft er a ? in the URL it sends it as a separate message. This messagecomes to the backend program in the form of the standard input which you can parse and use foryour processing. Servlet handles this type of request s using doPost() method.

    Reading Form Data using Servlet:

    Servlets handles form data parsing automatically using the following methods depending on thesituation:

    getParameter(): You call request .getParameter() method to get the value of a formparameter.

    getParameterValues(): Call this method if the parameter appears more than once andreturns multiple values, for example checkbox.

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

    the current request.

    GET Method Example Using URL:

    Here is a simple URL which will pass two values to HelloForm program using GET method.

    http://localhost:8080/HelloForm?first_name=ZARA&last_name=ALI

    Below is HelloForm.java servlet program to handle input given by web browser. We are going touse getParameter() method which makes it very easy to access passed information:

    // Import required java libraries

    import java.io.*;

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

    // Extend HttpServlet class

    publicclassHelloFormextendsHttpServlet{

    http://www.tutorialspoint.com/servlets/servlets-form-data.htm
  • 7/28/2019 Serv Let Complete Tutorial

    14/77

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Using GET Method to Read Form Data";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n"+

    ""+ title +"\n"+

    "\n"+

    " First Name: "

    + request.getParameter("first_name")+"\n"+

    " Last Name: "

    + request.getParameter("last_name")+"\n"+

    "\n"+

    "");

    }

    }

    Assuming your environment is setup properly, compile HelloForm.java as follows:

    $ javac HelloForm.java

    If everything goes fine, above compilation would produce HelloForm.class file. Next you wouldhave to copy this class file in /webapps/ROOT/WEB-INF/classesand create following entries inweb.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'sLocation:box and make sure you already started tomcat server, before firing above command inthe browser. This would generate following result:

    USING GET METHOD TO READ FORM DATA

    First Name: ZARA

    Last Name: ALI

    GET Method Example Using Form:

    Here is a simple example which passes two values using HTML FORM and submit button. We aregoing to use same Servlet HelloForm to handle this imput.

  • 7/28/2019 Serv Let Complete Tutorial

    15/77

    First Name:

    Last Name:

    Keep this HTML in a file Hello.htm and put it in /webapps/ROOT

    directory. When you would access http://localhost:8080/Hello.htm , here is t he actual output ofthe above form.

    First Name:

    Last Name:

    Try to enter First Name and Last Name and then click submit button to see the result on your localmachine where tomcat is running. Based on the input provided, it will generate similar result asmentioned in the above example.

    POST Method Example Using Form:

    Let us do litt le modification in the above servlet , so that it can handle GET as well as POSTmethods. Below is HelloForm.java servlet program to handle input given by web browser usingGET or POST methods.

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    // Extend HttpServlet class

    publicclassHelloFormextendsHttpServlet{

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

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Using GET Method to Read Form Data";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n"+

    ""+ title +"\n"+

    "\n"+

    " First Name: "

    + request.getParameter("first_name")+"\n"+

    " Last Name: "

    + request.getParameter("last_name")+"\n"+

    "\n"+

    "");

    }

    // Method to handle POST method request.

    publicvoid doPost(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException{

    doGet(request, response);

    }

    }

  • 7/28/2019 Serv Let Complete Tutorial

    16/77

    Now compile, deploy the above Servlet and test it using Hello.htm with the POST method asfollows:

    First Name:

    Last Name:

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

    First Name:

    Last Name:

    Based on the input provided, it would generate similar result as mentioned in the above examples.

    Passing Checkbox Data to Servlet Program

    Checkboxes are used when more than one opt ion is required to be selected.

    Here is example HTML code, CheckBox.htm, for a form with two checkboxes

    Maths

    Physics

    Chemistry

    The result of t his code is the following form

    Maths Physics Chemistry

    Below is CheckBox.java servlet program to handle input given by web browser for checkbox

    button.

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    // Extend HttpServlet class

    publicclassCheckBoxextendsHttpServlet{

    // Method to handle GET method request.

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    { // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Reading Checkbox Data";

    String docType =

  • 7/28/2019 Serv Let Complete Tutorial

    17/77

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n"+

    ""+ title +"\n"+

    "\n"+

    " Maths Flag : : "

    + request.getParameter("maths")+"\n"+

    " Physics Flag: : "

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

    " Chemistry Flag: : "

    + request.getParameter("chemistry")+"\n"+

    "\n"+

    "");

    }

    // Method to handle POST method request.

    publicvoid doPost(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,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 t he generic example which uses getParameterNames() method ofHttpServletRequest to read all the available form parameters. This method returns anEnumeration that contains the parameter names in an unspecified order.

    Once we have an Enumeration, we can loop down the Enumeration in the standard manner, usinghasMoreElements() method to determine when to stop and using nextElement()method to geteach parameter name.

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

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.util.*;

    // Extend HttpServlet class

    publicclassReadParamsextendsHttpServlet{

    // Method to handle GET method request.

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Reading All Form Parameters";

    String docType =

  • 7/28/2019 Serv Let Complete Tutorial

    18/77

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n"+

    ""+ title +"\n"+

    "\n"+

    "\n"+

    "Param NameParam Value(s)\n"+

    "\n");

    Enumeration paramNames = request.getParameterNames();

    while(paramNames.hasMoreElements()){

    String paramName =(String)paramNames.nextElement();

    out.print(""+ paramName +"\n");

    String[] paramValues =

    request.getParameterValues(paramName);

    // Read single valued data

    if(paramValues.length ==1){

    String paramValue = paramValues[0];

    if(paramValue.length()==0)

    out.println("No Value");

    else

    out.println(paramValue);

    }else{

    // Read multiple valued data

    out.println("");

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

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

    }

    out.println("");

    }

    }

    out.println("\n\n");

    }

    // Method to handle POST method request.

    publicvoid doPost(HttpServletRequest request, HttpServletResponse response)

    throwsServletException,IOException{

    doGet(request, response);

    }

    }

    Now, try above servlet with the following form:

    Maths

    Physics Chem

    Now calling servlet using above form would generate following result:

    READING ALL FORM PARAMETERS

    Param Name Param Value(s)

    maths on

    chemistry on

  • 7/28/2019 Serv Let Complete Tutorial

    19/77

    You can try above servlet to read any other form's data which is having other objects like textbox, radio button or drop down box etc.

  • 7/28/2019 Serv Let Complete Tutorial

    20/77

    http://www.tutorialspoint.com/servlets/servlets-client-request.htm Copyright tutorialspoint.com

    SERVLETS - CLIENT HTTP REQUEST

    When a browser request s for a web page, it sends lot of information to the web server which cannot be read direct ly because this information travel as a part of header of HTTP request. You cancheck HTTP Protocol for more information on this.

    Following is the important header information which comes f rom browser side and you would usevery frequently in web programming:

    Header Description

    Accept This header specifies the MIME types that the browser or otherclients can handle. Values ofimage/png or image/jpeg are thetwo most common possibilit ies.

    Accept-Charset This header specif ies the character sets the browser can use todisplay the information. For example ISO-8859-1.

    Accept-Encoding This header specif ies the types of encodings that the browserknows how to handle. Values ofgzip or compress are the twomost common possibilities.

    Accept-Language This header specifies the client's preferred languages in case theservlet can produce results in more than one language. Forexample en, en-us, ru, etc.

    Authorizat ion This header is used by clients to ident ify themselves whenaccessing password-protected Web pages.

    Connect ion This header indicates whether the client can handle persistentHTTP connections. Persistent connections permit the client orother browser to ret rieve mult iple files with a single request . Avalue ofKeep-Alive means that persistent connections shouldbe used

    Content-Length This header is applicable only to POST requests and gives the sizeof the POST data in bytes.

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

    Host This header specifies the host and port as given in the originalURL.

    If-Modified-Since This header indicates that t he client wants t he page only if it hasbeen changed aft er the specified date. The server sends a code,304 which means Not Modified header if no newer result isavailable.

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

    Referer This header indicates the URL of the referring Web page. For

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

    User-Agent This header ident ifies the browser or other client making therequest and can be used to return different content to different

    http://www.tutorialspoint.com/servlets/servlets-client-request.htmhttp://localhost/var/www/apps/conversion/tmp/scratch_11/http/index.htmhttp://www.tutorialspoint.com/servlets/servlets-client-request.htm
  • 7/28/2019 Serv Let Complete Tutorial

    21/77

    types of browsers.

    Methods to read HTTP Header:

    There are following methods which can be used to read HTTP header in your servlet program.These method are available with HttpServletRequestobject.

    S.N. Method & Description

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

    2 Enumeration getAttributeNames()Returns an Enumeration containing t he names of the att ributes available to this request.

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

    4 Enumeration getParameterNames()

    Returns an Enumeration of String objects containing the names of the parameterscontained in this request.

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

    6 HttpSession getSession(boolean create)Returns t he current HttpSession associated with this request or, if if t here is no currentsession and create is t rue, returns a new session.

    7 Locale getLocale()

    Returns t he preferred Locale that the client will accept content in, based on theAccept-Language header

    8 Object getAttribute(String name)Returns t he value of the named attribute as an Object, or null if no attribute of the givenname exists.

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

    10 String getAuthType()Returns t he name of the authentication scheme used t o protect the servlet , forexample, "BASIC" or "SSL," or null if the JSP was not protected

    11 String getCharacterEncoding()Returns t he name of the character encoding used in the body of t his request.

    12 String getContentType()Returns t he MIME type of the body of the request , or null if the type is not known.

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

    14 String getHeader(String name)Returns t he value of the specified request header as a String.

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

    16 String getParameter(String name)

  • 7/28/2019 Serv Let Complete Tutorial

    22/77

    Returns the value of a request parameter as a St ring, or null if the parameter does notexist.

    17 String getPathInfo()Returns any ext ra path information associated with the URL the client sent when itmade this request.

    18 String getProtocol()Returns t he name and version of the protocol the request .

    19 String getQueryString()Returns t he query st ring that is contained in the request URL after the path.

    20 String getRemoteAddr()Returns the Internet Protocol (IP) address of the client t hat sent t he request .

    21 String getRemoteHost()Returns t he fully qualified name of the client t hat sent t he request .

    22 String getRemoteUser()Returns the login of the user making this request, if the user has been authenticated, ornull if the user has not been authenticated.

    23 String getRequestURI()Returns t he part of t his request's URL from the protocol name up to the query st ring inthe f irst line of the HTTP request.

    24 String getRequestedSessionId()Returns t he session ID specified by the client.

    25 String getServletPath()Returns t he part of t his request's URL that calls the JSP.

    26 String[] getParameterValues(String name)

    Returns an array of String objects containing all of the values the given requestparameter has, or null if the parameter does not exist.

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

    28 int getContentLength()Returns the length, in bytes, of the request body and made available by the inputst ream, or -1 if the length is not known.

    29 int getIntHeader(String name)

    Returns t he value of the specified request header as an int.

    30 int getServerPort()Returns the port number on which this request was received.

    HTTP Header Request Example:

    Following is t he example which uses getHeaderNames() method of Htt pServletRequest toread the HTTP header infromation. This method returns an Enumeration that contains the headerinformation associated with the current HTTP request.

    Once we have an Enumeration, we can loop down the Enumeration in the st andard manner, usinghasMoreElements() method to det ermine when to st op and using nextElement() method to geteach parameter name.

    // Import required java libraries

    import java.io.*;

  • 7/28/2019 Serv Let Complete Tutorial

    23/77

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.util.*;

    // Extend HttpServlet class

    publicclassDisplayHeaderextendsHttpServlet{

    // Method to handle GET method request.

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="HTTP Header Request Example";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n"+

    ""+ title +"\n"+

    "\n"+

    "\n"+

    "Header NameHeader Value(s)\n"+

    "\n");

    Enumeration headerNames = request.getHeaderNames();

    while(headerNames.hasMoreElements()){

    String paramName =(String)headerNames.nextElement();

    out.print(""+ paramName +"\n");

    String paramValue = request.getHeader(paramName);

    out.println(" "+ paramValue +"\n");

    }

    out.println("\n"); }

    // Method to handle POST method request.

    publicvoid doPost(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException{

    doGet(request, response);

    }

    }

    Now calling the above servlet would generate following result:

    HTTP HEADER REQUEST EXAMPLE

    Header Name Header Value(s)

    accept */*

    accept-language en-us

    user-agent Mozilla/4.0 (compat ible; MSIE 7.0; Windows NT 5.1; Trident /4.0;InfoPath.2; MS-RTC LM 8)

    accept-encoding gzip, deflate

    host localhost:8080

    connection Keep-Alive

    cache-control no-cache

  • 7/28/2019 Serv Let Complete Tutorial

    24/77

  • 7/28/2019 Serv Let Complete Tutorial

    25/77

    http://www.tutorialspoint.com/servlets/servlets-server-response.htm Copyright tutorialspoint.com

    SERVLETS - SERVER HTTP RESPONSE

    As discussed in previous chapter, when a Web server responds to a HTTP request to the browser,the response typically consists of a status line, some response headers, a blank line, and thedocument. A typical response looks like this:

    HTTP/1.1200 OKContent-Type: text/html

    Header2:...

    ...

    HeaderN:...

    (BlankLine)

    ...

    ...

    The status line consist s of the HTTP version (HTTP/1.1 in the example), a st atus code (200 in theexample), and a very short message corresponding to t he status code (OK in the example).

    Following is a summary of the most useful HTTP 1.1 response headers which go back t o t hebrowser 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.) thatthe server supports.

    Cache-Control This header specif ies the circumstances in which the responsedocument can safely be cached. It can have values public,private or no-cache etc. Public means document is cacheable,Private means document is for a single user and can only bestored in private (nonshared) caches and no-cache meansdocument should never be cached.

    Connect ion This header inst ructs the browser whether to use persistent inHTTP connect ions or not. A value ofclose inst ructs t he browsernot to use persistent HTTP connect ions and keep-alive meansusing persistent connections.

    Content-Disposition This header lets you request that the browser ask the user tosave the response t o disk in a file of the given name.

    Content-Encoding This header specifies the way in which the page was encodedduring transmission.

    Content-Language This header signifies the language in which the document iswritten. For example en, en-us, ru, etc.

    Content-Length This header indicates the number of bytes in the response. Thisinformation is needed only if t he browser is using a persistent(keep-alive) HTTP connect ion.

    Content-Type This header gives the MIME (Multipurpose Internet Mail Extension)type of the response document.

    Expires This header specifies the t ime at which the content should beconsidered out-of-date and thus no longer be cached.

    http://www.tutorialspoint.com/servlets/servlets-server-response.htm
  • 7/28/2019 Serv Let Complete Tutorial

    26/77

    Last-Modif ied This header indicates when the document was last changed. Theclient can then cache t he document and supply a date by an If-Modified-Since request header in later request s.

    Location This header should be included with all responses t hat have astatus code in the 300s. This notifies t he browser of thedocument address. The browser automatically reconnect s t o thislocat ion and retrieves the new document.

    Refresh This header specifies how soon the browser should ask for anupdated page. You can specify time in number of seconds aft erwhich a page would be refreshed.

    Ret ry-After This header can be used in conjunct ion with a 503 (ServiceUnavailable) response to tell the client how soon it can repeat itsrequest.

    Set -Cookie This header specifies a cookie associat ed wit h t he page.

    Methods to Set HTTP Response Header:There are following methods which can be used to set HTTP response header in your servletprogram. These met hod are available with HttpServletResponse object.

    S.N. Method & Description

    1 String encodeRedirectURL(String url)Encodes the specified URL for use in the sendRedirect method or, if encoding is notneeded, returns the URL unchanged.

    2 String encodeURL(String url)Encodes the specified URL by including the session ID in it, or, if encoding is not needed,returns t he URL unchanged.

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

    4 boolean isCommitted()Returns a boolean indicating if the response has been committed.

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

    6 void addDateHeader(String name, long date)Adds a response header with the given name and date-value.

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

    8 void addIntHeader(String name, int value)Adds a response header with the given name and integer value.

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

    10 void reset()Clears any data that exists in the buffer as well as the status code and headers.

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

  • 7/28/2019 Serv Let Complete Tutorial

    27/77

    12 void sendError(int sc)Sends an error response to the client using the specified status code and clearing thebuffer.

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

    14 void sendRedirect(String location)Sends a temporary redirect response to the client using the specified redirect location

    URL.

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

    16 void setCharacterEncoding(String charset)Sets the character encoding (MIME charset) of the response being sent to the client, forexample, to UTF-8.

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

    18 void setContentType(String type)Sets the content type of the response being sent t o the client, if t he response has notbeen committed yet.

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

    20 void setHeader(String name, String value)Sets a response header with the given name and value.

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

    22 void setLocale(Locale loc)Sets t he locale of the response, if t he response has not been committed yet.

    23 void setStatus(int sc)Sets the st atus code for this response.

    HTTP Header Response Example:

    You already have seen setContentType() method working in previous examples and following

    example would also use same method, additionally we would use setIntHeader() method to setRefresh header.

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.util.*;

    // Extend HttpServlet class

    publicclassRefreshextendsHttpServlet{

    // Method to handle GET method request.

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Set refresh, autoload time as 5 seconds

    response.setIntHeader("Refresh",5);

  • 7/28/2019 Serv Let Complete Tutorial

    28/77

    // Set response content type

    response.setContentType("text/html");

    // Get current time

    Calendar calendar =newGregorianCalendar();

    String am_pm;

    int hour = calendar.get(Calendar.HOUR);

    int minute = calendar.get(Calendar.MINUTE);

    int second = calendar.get(Calendar.SECOND);

    if(calendar.get(Calendar.AM_PM)==0)

    am_pm ="AM";

    else

    am_pm ="PM";

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

    PrintWriterout= response.getWriter();

    String title ="Auto Refresh Header Setting";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n"+

    ""+ title +"\n"+

    "

    Current Time is: "+ CT +"

    \n");

    }

    // Method to handle POST method request.

    publicvoid doPost(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException{

    doGet(request, response);

    }

    }

    Now calling the above servlet would display current system time after every 5 seconds as follows.Just run the servlet and wait to see the result:

    AUTO REFRESH HEADER SETTING

    Current Time is: 9:44:50 PM

  • 7/28/2019 Serv Let Complete Tutorial

    29/77

    http://www.tutorialspoint.com/servlets/servlets-http-status-codes.htm Copyright tutorialspoint.com

    SERVLETS - HTTP STATUS CODES

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

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

    Zero or more header lines + CRLF

    A blank line ie. a CRLF

    An opt ioanl message body like f ile, query data or query output.

    For example, a server response header looks as follows:

    HTTP/1.1200 OK

    Content-Type: text/html

    Header2:...

    ...

    HeaderN:... (BlankLine)

    ...

    ...

    The status line consist s of the HTTP version (HTTP/1.1 in the example), a st atus code (200 in theexample), and a very short message corresponding to t he status code (OK in the example).

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

    Code: Message: Description:

    100 Continue Only a part of the request has been received by theserver, but as long as it has not been reject ed, theclient should continue with the request

    101 Swit ching Protocols The server swit ches prot ocol.

    200 OK The request is OK

    201 Created The request is complete, and a new resource is created

    202 Accepted The request is accepted for processing, but theprocessing is not complete.

    203 Non-aut horit at iveInformation

    204 No Content

    205 Reset Content

    206 Part ial Content

    300 Mult iple Choices A link list . The user can select a link and go t o t hatlocation. Maximum five addresses

    http://www.tutorialspoint.com/servlets/servlets-http-status-codes.htmhttp://www.tutorialspoint.com/servlets/servlets-http-status-codes.htm
  • 7/28/2019 Serv Let Complete Tutorial

    30/77

    301 Moved Permanent ly The requested page has moved to a new url

    302 Found The requested page has moved temporarily to a newurl

    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. It is no longerused, but the code is reserved.

    307 Temporary Redirect The requested page has moved temporarily to a newurl.

    400 Bad Request The server did not understand the request

    401 Unauthorized The requested page needs a username and a password

    402 Payment Required You can not use this code yet

    403 Forbidden Access is forbidden to the requested page

    404 Not Found The server can not find the requested page.

    405 Method Not Allowed The method specif ied in the request is not allowed.

    406 Not Acceptable The server can only generat e a response t hat is notaccepted by the client.

    407 Proxy Authent icat ionRequired

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

    408 Request Timeout The request t ook longer t han t he server was preparedto wait.

    409 Conflict The request could not be completed because of aconflict.

    410 Gone The requested page is no longer available.

    411 Length Required The "Content -Length" is not defined. The server will notaccept t he request without it.

    412 Precondit ion Failed The precondit ion given in the request evaluated to falseby the server.

    413 Request Entity Too Large The server will not accept t he request, because therequest entity is too large.

    414 Request-url Too Long The server will not accept the request, because the urlis too long. Occurs when you convert a "post" requestto a "get " request with a long query information.

    415 Unsupported Media Type The server will not accept the request, because themedia type is not supported.

    417 Expectat ion Failed

    500 Internal Server Error The request was not completed. The server met anunexpected condition

    501 Not Implement ed The request was not complet ed. The server did not

  • 7/28/2019 Serv Let Complete Tutorial

    31/77

    support the functionality required.

    502 Bad Gateway The request was not completed. The server received aninvalid response from the upst ream server

    503 Service Unavailable The request was not completed. The server istemporarily overloading or down.

    504 Gateway Timeout The gateway has timed out.

    505 HTTP Version NotSupported

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

    Methods to Set HTTP Status Code:

    There are following methods which can be used to set HTTP Status Code in your servlet program.These method are available with HttpServletResponse object.

    S.N. Method & Description

    1 public void setStatus ( int statusCode )This method sets an arbitrary status code. The setStatus method takes an int (thest atus code) as an argument. If your response includes a special st atus code and adocument, be sure to call setStatus before actually returning any of the content withthe PrintWriter.

    2 public void sendRedirect(String url)This method generates a 302 response along with a Location header giving the URL ofthe new document.

    3 public void sendError(int code, String message)

    This method sends a st atus code (usually 404) along with a short message that isautomatically formatted inside an HTML document and sent to t he client.

    HTTP Status Code Example:

    Following is the example which would send 407 error code to the client browser and browser wouldshow you "Need authentication!!!" message.

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

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

    // Extend HttpServlet class

    publicclass showError extendsHttpServlet{

    // Method to handle GET method request.

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Set error code and reason.

    response.sendError(407,"Need authentication!!!");

    }

    // Method to handle POST method request. publicvoid doPost(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException{

    doGet(request, response);

    }

    }

  • 7/28/2019 Serv Let Complete Tutorial

    32/77

    Now calling the above servlet would display following result:

    HTTP STATUS 407 - NEED AUTHENTICATION!!!

    type Status report

    message Need authentication!!!

    description The client must first authenticate itself with the proxy (Need authentication!!!).

    Apache Tomcat/5.5.29

  • 7/28/2019 Serv Let Complete Tutorial

    33/77

    http://www.tutorialspoint.com/servlets/servlets-writing-filters.htm Copyright tutorialspoint.com

    SERVLETS - WRITING FILTERS

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

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

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

    There are are various types of filters suggest ed by the specificat ions:

    Authentication Filters.

    Data compression Filters.

    Encryption Filters.

    Filters that trigger resource access events.

    Image Conversion Filters.

    Logging and Auditing Filters.

    MIME-TYPE Chain Filters.

    Tokenizing Filters .

    XSL/T Filters That Transform XML Content.

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

    When the web container st arts up your web application, it creates an inst ance of each filter thatyou have declared in the deployment descriptor. The filters execute in the order that t hey aredeclared in the deployment descriptor.

    Servlet Filter Methods:

    A filter is simply a Java class that implements the javax.servlet.Filter interface. Thejavax.servlet .Filter interface defines t hree methods:

    S.N. Method & Description

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

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

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

    Servlet Filter Example:

    Following is the Servlet Filter Example that would print the clients IP address and current datetime. This example would give you basic understanding of Servlet Filter, but you can write more

    http://www.tutorialspoint.com/servlets/servlets-writing-filters.htmhttp://www.tutorialspoint.com/servlets/servlets-writing-filters.htm
  • 7/28/2019 Serv Let Complete Tutorial

    34/77

    sophisticated filter applications using the same concept:

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.util.*;

    // Implements Filter class

    publicclassLogFilterimplementsFilter {

    publicvoid init(FilterConfig config)throwsServletException{

    // Get init parameter

    String testParam = config.getInitParameter("test-param");

    //Print the init parameter

    System.out.println("Test Param: "+ testParam);

    }

    publicvoid doFilter(ServletRequest request,

    ServletResponse response,

    FilterChain chain)

    throws java.io.IOException,ServletException{

    // Get the IP address of client machine.

    String ipAddress = request.getRemoteAddr();

    // Log the IP address and current timestamp.

    System.out.println("IP "+ ipAddress +", Time "

    +newDate().toString());

    // Pass request back down the filter chain

    chain.doFilter(request,response);

    }

    publicvoid destroy(){

    /* Called before the Filter instance is removed

    from service by the web container*/

    }

    }

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

    Servlet Filter Mapping in Web.xml:

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

    LogFilter

    LogFilter

    test-param

    Initialization Paramter

    LogFilter

    /*

    The above filter would apply to all the servlet s because we specified /* in our configuration. Youcan specicy a particular servlet path if you want t o apply filter on few servlets only.

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

    Using Multiple Filters:

  • 7/28/2019 Serv Let Complete Tutorial

    35/77

    Your web application may define several different filters with a specific purpose. Consider, youdefine t wo filters AuthenFilterand LogFilter. Rest of the process would remain as explainedabove except you need t o create a different mapping as mentioned below:

    LogFilter

    LogFilter

    test-param

    Initialization Paramter

    AuthenFilter

    AuthenFilter

    test-param

    Initialization Paramter

    LogFilter

    /*

    AuthenFilter

    /*

    Filters Application Order:

    The order of filter-mapping elements in web.xml determines t he order in which the web containerapplies the f ilter to the servlet . To reverse the order of t he f ilter, you just need to reverse the

    filter-mapping elements in the web.xml file.

    For example, above example would apply LogFilter first and then it would apply AuthenFilter to anyservlet but the following example would reverse the order:

    AuthenFilter

    /*

    LogFilter

    /*

  • 7/28/2019 Serv Let Complete Tutorial

    36/77

    http://www.tutorialspoint.com/servlets/servlets-exception-handling.htm Copyright tutorialspoint.com

    SERVLETS - EXCEPTION HANDLING

    When a servlet throws an except ion, the web container searches the configurations in web.xmlthat use the except ion-type element for a match with the thrown exception type.

    You would have to use the error-page element in web.xml to specify the invocat ion of servlets

    in response to certain exceptions or HTTP status codes.

    web.xml Configuration:

    Consider, you have anErrorHandlerservelt which would be called whenever there is any def inedexception or error. Following would be the entry created in web.xml.

    ErrorHandler

    ErrorHandler

    ErrorHandler

    /ErrorHandler

    404

    /ErrorHandler

    403

    /ErrorHandler

    javax.servlet.ServletException

    /ErrorHandler

    java.io.IOException

    /ErrorHandler

    If you want to have a generic Error Handler for all the exceptions then you should define followingerror-page inst ead of def ining separate error-page elements for every exception:

    java.lang.Throwable

    /ErrorHandler

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

    The servelt ErrorHandler is def ined in usual way as any other servlet and configured in

    web.xml.

    If there is any error with status code either 404 ( Not Found) or 403 ( Forbidden ), thenErrorHandler servlet would be called.

    If the web applicat ion throws either ServletException or IOException, then the web

    http://www.tutorialspoint.com/servlets/servlets-exception-handling.htmhttp://www.tutorialspoint.com/servlets/servlets-exception-handling.htm
  • 7/28/2019 Serv Let Complete Tutorial

    37/77

    container invokes the /ErrorHandler servlet.

    You can def ine different Error Handlers to handle different type of errors or except ions.Above example is very much generic and hope it serve the purpose to explain you the basicconcept.

    Request Attributes - Errors/Exceptions:

    Following is the list of request att ributes t hat an error-handling servlet can access t o analyse the

    nature of error/exception.

    S.N. Attribute & Description

    1 javax.servlet.error.status_codeThis attribute give status code which can be st ored and analysed after storing in ajava.lang.Integer data type.

    2 javax.servlet.error.exception_typeThis attribute gives information about except ion type which can be st ored and analysedafter storing in a java.lang.Class data type.

    3 javax.servlet.error.messageThis attribute gives information exact error message which can be st ored and analysedafter storing in a java.lang.String data type.

    4 javax.servlet.error.request_uriThis attribute gives information about URL calling the servlet and it can be st ored andanalysed after storing in a java.lang.String data type.

    5 javax.servlet.error.exceptionThis attribute gives information the exception raised which can be st ored and analysedaft er storing in a java.lang.Throwable data type.

    6 javax.servlet.error.servlet_nameThis attribute gives servlet name which can be st ored and analysed after storing in ajava.lang.String data type.

    Error Handler Servlet Example:

    Following is the Servlet Example that would be used as Error Handler in case of any error orexcept ion occurs with your any of the servlet defined.

    This example would give you basic underst anding of Exception Handling in Servlet , but you canwrite more sophist icated filter applications using the same concept :

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.util.*;

    // Extend HttpServlet class

    publicclassErrorHandlerextendsHttpServlet{

    // Method to handle GET method request.

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException {

    // Analyze the servlet exception

    Throwable throwable =(Throwable)

    request.getAttribute("javax.servlet.error.exception");

    Integer statusCode =(Integer)

    request.getAttribute("javax.servlet.error.status_code");

  • 7/28/2019 Serv Let Complete Tutorial

    38/77

    String servletName =(String)

    request.getAttribute("javax.servlet.error.servlet_name");

    if(servletName ==null){

    servletName ="Unknown";

    }

    String requestUri =(String)

    request.getAttribute("javax.servlet.error.request_uri");

    if(requestUri ==null){

    requestUri ="Unknown";

    }

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Error/Exception Information";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n");

    if(throwable ==null&& statusCode ==null){

    out.println("Error information is missing");

    out.println("Please return to the Home Page.");

    }elseif(statusCode !=null){

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

    }else{

    out.println("Error information");

    out.println("Servlet Name : "+ servletName +

    "");

    out.println("Exception Type : "+

    throwable.getClass().getName()+

    "");

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

    ");

    out.println("The exception message: "+

    throwable.getMessage());

    }

    out.println("");

    out.println("");

    }

    // Method to handle POST method request.

    publicvoid doPost(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException{

    doGet(request, response);

    }

    }

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

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

    ErrorHandler

    ErrorHandler

    ErrorHandler

    /ErrorHandler

    404

    /ErrorHandler

  • 7/28/2019 Serv Let Complete Tutorial

    39/77

    java.lang.Throwable

    /ErrorHandler

    Now try to use a servlet which raise any except ion or type a wrong URL, this would t rigger WebContainer to call ErrorHandler servlet and display an appropriate message as programmed. Forexample, if you type a wrong URL then it would display the following result:

    The status code :404

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

  • 7/28/2019 Serv Let Complete Tutorial

    40/77

    http://www.tutorialspoint.com/servlets/servlets-cookies-handling.htm Copyright tutorialspoint.com

    SERVLETS - COOKIES HANDLING

    Cookies are text files stored on the client computer and they are kept for various informationtracking purpose. Java Servlets transparently supports HTTP cookies.

    There are three steps involved in identifying returning users:

    Server script sends a set of cookies to the browser. For example name, age, oridentification number etc.

    Browser stores this information on local machine for future use.

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

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

    The Anatomy of a Cookie:

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

    HTTP/1.1200 OK

    Date:Fri,04Feb200021:03:38 GMT

    Server:Apache/1.3.9(UNIX) PHP/4.0b3

    Set-Cookie: name=xyz; expires=Friday,04-Feb-0722:03:38 GMT;

    path=/; domain=tutorialspoint.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 adomain. The name and value will be URL encoded. The expires f ield is an instruct ion to the browserto "forget" the cookie after the given t ime and date.

    If the browser is configured to store cookies, it will then keep this information until the expirydate. 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. The browser's headers might look something like this:

    GET / HTTP/1.0

    Connection:Keep-Alive

    User-Agent:Mozilla/4.6(X11; I;Linux2.2.6-15apmac ppc)

    Host: zink.demon.co.uk:1126

    Accept: image/gif,*/*

    Accept-Encoding: gzipAccept-Language: en

    Accept-Charset: iso-8859-1,*,utf-8

    Cookie: name=xyz

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

    Servlet Cookies Methods:

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

    S.N. Method & Description

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

    http://www.tutorialspoint.com/servlets/servlets-cookies-handling.htm
  • 7/28/2019 Serv Let Complete Tutorial

    41/77

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

    3 public void setMaxAge(int expiry)This method set s how much time (in seconds) should elapse before the cookie expires.If you don't set this, the cookie will last only for the current session.

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

    1 indicating the cookie will persist until browser shutdown.

    5 public String getName()This method returns the name of t he cookie. The name cannot be changed aftercreation.

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

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

    8 public void setPath(String uri)

    This method set s the path to which this cookie applies. If you don't specify a path, thecookie is returned for all URLs in the same direct ory as the current page as well as allsubdirectories.

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

    10 public void setSecure(boolean flag)This method set s the boolean value indicating whether the cookie should only be sentover encrypted (i.e. SSL) connections.

    11 public void setComment(String purpose)

    This method specifies a comment that describes a cookie's purpose. The comment isuseful if the browser presents the cookie to the user.

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

    Setting Cookies with Servlet:

    Setting cookies with servlet involves three steps:

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

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

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

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

    (2) Sett ing the maximum age: You use setMaxAge to specify how long (in seconds) the

    cookie should be valid. Following would set up a cookie for 24 hours.

    cookie.setMaxAge(60*60*24);

    (3) Sending the Cookie into the HTTP response headers: You useresponse.addCookie to add cookies in the HTTP response header as follows:

  • 7/28/2019 Serv Let Complete Tutorial

    42/77

    response.addCookie(cookie);

    Example:

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

    // Import required java libraries

    import java.io.*;

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

    // Extend HttpServlet class

    publicclassHelloFormextendsHttpServlet{

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    // Create cookies for first and last names.

    Cookie firstName =newCookie("first_name",

    request.getParameter("first_name"));

    Cookie lastName =newCookie("last_name",

    request.getParameter("last_name"));

    // Set expiry date after 24 Hrs for both the cookies.

    firstName.setMaxAge(60*60*24);

    lastName.setMaxAge(60*60*24);

    // Add both the cookies in the response header.

    response.addCookie( firstName );

    response.addCookie( lastName );

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Setting Cookies Example";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n"+

    ""+ title +"\n"+

    "\n"+

    " First Name: "

    + request.getParameter("first_name")+"\n"+

    " Last Name: "

    + request.getParameter("last_name")+"\n"+

    "\n"+

    "");

    }

    }

    Compile above servlet HelloForm and create appropriate entry in web.xml file and f inally tryfollowing HTML page to call servlet .

    First Name:

    Last Name:

    http://localhost/var/www/apps/conversion/tmp/scratch_11/servlets/servlets-form-data.htm
  • 7/28/2019 Serv Let Complete Tutorial

    43/77

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

    First Name:

    Last Name:

    Try to enter First Name and Last Name and then click submit button. This would display first nameand last name on your screen and same time it would set two cookies firstName and lastNamewhich would be passed back to the server when next t ime you would press Submit button.

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

    Reading Cookies with Servlet:

    To read cookies, you need to create an array ofjavax.servlet.http.Cookie objects by calling thegetCookies( ) method ofHttpServletRequest. Then cycle through the array, and use getName()and getValue() methods to access each cookie and associated value.

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

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    // Extend HttpServlet class

    publicclassReadCookiesextendsHttpServlet{

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    Cookie cookie =null;

    Cookie[] cookies =null;

    // Get an array of Cookies associated with this domain

    cookies = request.getCookies();

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Reading Cookies Example";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n");

    if( cookies !=null){

    out.println(" Found Cookies Name and Value");

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

    cookie = cookies[i];

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

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

    }

    }else{

    out.println( "No cookies founds");

    }

    out.println("");

    out.println("");

    }

    }

  • 7/28/2019 Serv Let Complete Tutorial

    44/77

    Compile above servlet ReadCookies and create appropriate entry in web.xml file. If you wouldhave set first _name cookie as "John" and last _name cookie as "Player" then runninghttp://localhost:8080/ReadCookieswould display the following result:

    Found Cookies Name and Value

    Name : f irst _name, Value: JohnName : last_name, Value: Player

    Delete Cookies with Servlet:

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

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

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

    Add this cookie back into response header.

    Example:

    Following example would delete and exist ing cookie named "first _name" and when you would runReadCookies servlet next time it would return null value for first_name.

    // Import required java libraries

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    // Extend HttpServlet classpublicclassDeleteCookiesextendsHttpServlet{

    publicvoid doGet(HttpServletRequest request,

    HttpServletResponse response)

    throwsServletException,IOException

    {

    Cookie cookie =null;

    Cookie[] cookies =null;

    // Get an array of Cookies associated with this domain

    cookies = request.getCookies();

    // Set response content type

    response.setContentType("text/html");

    PrintWriterout= response.getWriter();

    String title ="Delete Cookies Example";

    String docType =

    "\n";

    out.println(docType +

    "\n"+

    ""+ title +"\n"+

    "\n");

    if( cookies !=null){

    out.println(" Cookies Name and Value");

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

    cookie = cookies[i];

    if((cookie.getName()).compareTo("first_name")==0){

    cookie.setMaxAge(0);

    response.addCookie(cookie);

    out.print("Deleted cookie : "+

    cookie.getName()+"
    ");

    }

  • 7/28/2019 Serv Let Complete Tutorial

    45/77

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

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

    }

    }else{

    out.println(

    "No cookies founds");

    }

    out.println("");

    out.println("");

    }

    }

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

    Cookies Name and Value

    Deleted cookie : first _nameName : f irst _name, Value: JohnName : last_name, Value: Player

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

    Found Cookies Name and Value

    Name : last_name, Value: Player

    You can delete your cookies in Internet Explorer manually. Start at t he Tools menu and select

    Internet Opt ions. To delete all cookies, press Delete Cookies.

  • 7/28/2019 Serv Let Complete Tutorial

    46/77

    http://www.tutorialspoint.com/servlets/servlets-session-tracking.htm Copyright tutorialspoint.com

    SERVLETS - SESSION TRACKING

    HTTP is a "stateless" protocol which means each time a client retrieves a Web page, the clientopens a separate connect ion to the Web server and the server automatically does not keep anyrecord of previous client request .

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

    Cookies:

    A webserver can assign a unique session ID as a cookie to each web client and for subsequentrequest s f rom the client they can be recognized using the recieved cookie.

    This may not be an effect ive way because many time browser does not support a cookie, so Iwould not recommend to use this procedure t o maintain the sessions.

    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 areautomatically included in the GET or POST data. Each time when web browser sends request back,then session_id value can be used to keep the track of different web browsers.

    This could be an effect ive way of keeping track of the session but clicking on a regular () hypertext link does not result in a form submission, so hidden form fields also cannotsupport general session tracking.

    URL Rewriting:

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

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

    URL rewriting is a better way to maintain sessions and works for the browsers when they don'tsupport cookies but here drawback is t hat you would have generate every URL dynamically toassign a session ID though page is simple static HTML page.

    The HttpSession Object:Apart from the above mentioned three ways, servlet provides Htt pSession Interface whichprovides a way to identify a user across more than one page request or visit to a Web site and tostore information about that user.

    The servlet container uses this interface to create a session between an HTTP client and an HTTPserver. The session persists for a specified t ime period, across more than one connect ion or pagerequest from the user.

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

    HttpSession session = request.getSession();

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

    http://www.tutorialspoint.com/servlets/servlets-session-tracking.htmhttp://www.tutorialspoint.com/servlets/servlets-session-tracking.htm
  • 7/28/2019 Serv Let Complete Tutorial

    47/77

    S.N. Method & Description

    1 public Object getAttribute(String name)This method returns the object bound with the specified name in this session, or null ifno object is bound under the name.

    2 public Enumeration getAttributeNames()This method returns an Enumeration of String objects containing the names of all theobjects bound to this session.

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

    4 public String getId()This method returns a st ring containing the unique identifier assigned to this session.

    5 public long getLastAccessedTime()This method returns the last t ime the client sent a request associated with thissession, as t he number of milliseconds since midnight January 1, 1970 GMT.

    6 public int getMaxInactiveInterval()This method returns the maximum time interval, in seconds, that the servlet containerwill keep this session open between client accesses.

    7 public void invalidate()This method invalidates this session and unbinds any objects bound to it.

    8 public boolean isNew(This method returns true if the client does not yet know about the session or if theclient