servlets by srinivasa reddy challa (corporate java trainer)

Upload: srinivasa-reddy-challa

Post on 08-Apr-2018

225 views

Category:

Documents


0 download

TRANSCRIPT

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    1/39

    Comspark Info India Pvt Ltd. CSREDDY

    SERVLETS

    At the beginning stages of computers we have client server architecture. Where themain purpose of the server is to share the static resources to the client requirements. In

    this case when we send a request to the server machine, server will identify the requestedresource and send back to the client machine as a response. Here server is generating the

    response without executing any application at server machine so that this kind of responseis called as static response. As per the application requirements we need to get dynamic

    response from server machine. To generate dynamic response server must execute someapplications at server machine, for this we should provide server side applications.

    To provide server side programming for the sake of dynamic response we should usethe fallowing server side technologies.

    1) CGI

    2) Servlets

    3) JSP . Etc

    1) To generate dynamic response we have already CGI technology then why

    you go for Servlets technology?

    CGI:

    a) CGI is a technology which was designed on the basis of C technology andsome scripting technology. As we know C technology is a process based

    technology.

    b) If we deploy any CGI application at server for every new request came fromclient automatically server will create a separate process at server machine.

    c) Process is a heavy weight component thats why to handle it system mustconsume more number of system resources.

    d) In the above situation if we increase more number of requests to the sameCGI application then server will create more number of processes. Thisapproach will increase burden to the server machine as a result application

    quality could be degraded.

    Servlets [email protected] 1

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    2/39

    Comspark Info India Pvt Ltd. CSREDDY

    SERVLETS:

    a) Servlets is a server side technology which was designed on the basis ofJava Technology. As we know Java is a Thread Based Technology thats

    why Servlets is also a Thread Based Technology.

    b) If we deploy any Servlets application at server machine then for everynew request came from clients automatically servlet may create a

    separate thread on the servlet object.

    c) If we increase more number of client requests then more number of

    threads will be created instead of process.

    d) Thread is a light weight component when compare to process thats why

    this approach will not increase burden to the server machine.

    2) Write the differences between Servlets and Jsps?

    a) To design any web application if we use Servlets as a technology then we shouldrequire minimum java knowledge.

    To design the same web application if we use JSP as a technology then it is not atall require to have java knowledge.

    b) Servlets are good at the time of pickup the request and process the requests.

    Jsps are good at the time of delivering the dynamic response to client with very

    good look and feel.

    c) In case of Servlets we are enable to separate presentation logic and business

    logic.

    But in case of Jsps we are able to separate both presentation logic and business

    logic due to the availability of separate tags for presentation and separate tags for businesslogic.

    d) If we made any modifications on the existed servlet then we should requirerecompiling and reloaded to server explicitly.

    If we made any modifications on the existed Jsps is it not require to recompilingand reloaded to server explicitly. Why bcz JSP pages are auto compiled and auto loaded.

    e) If we go for any MVC Based Web applications where we should use Servlets as aController and Jsps as a View Part.

    Eg: In Struts Frame Work we will use ActionServlet as a controller and some set of andsome set ofJsps as a view part.

    Eg: In case of JSF Frame Work we should use FacesServlet as a controller and some set

    ofJsps as a view part.

    MVC Diagram:

    Servlets [email protected] 2

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    3/39

    Comspark Info India Pvt Ltd. CSREDDY

    Client Server Architecture:

    To design any web application minimum we should require 2-tier architecture i.e.

    client server architecture. In this c-s architecture we have mainly three components arethere. They are given bellow.

    1) CLIENT

    2) PROTOCOL

    3) SERVER

    CLIENT:

    The job of the client machine in client server architecture is to send request and toget the responses from the server machine.

    From client machine to send request and to get the responses we should use a toolat client machine called as Browser, here Browser is acting like a Client.

    In client server architecture we will send request from client to the server byspecifying a string at clients address bar called as URI.

    3) Write the differences between URI, URL & URN?

    URI (Uniform Resource Identifier) is a string specification which can be used to

    refer an object available at server machine. There are two types of URIs and these are

    I) URL: is a string specification which can be used to refer anobject available at server machine through its locator. In case of

    Servlets URL Pattern is the Locator.

    II) URN: is a string specification which can be used to refer anobject available at server machine through its Logical name. Incase of Servlets Logical Name is a name specified along with theservlet name tag in web.xml file.

    In the web applications almost all the servers are supporting the URL

    representation not URN.

    SYN:

    Protocolname:\\ServerIPAddress:ServerPortNumber\ApplicationContext\

    Resource Path [ ?name1:value1&name2:value2]

    4) Write the Difference between IP Address and Port Number?

    IP Address is an unique identification to each and every machine over the network,which could be provided by the network manager.

    Port Number is an unique identification to each and every process being executed atthe single machine, which could be provided by the local operating system.

    5) What do you mean by Query String?

    It is a collection of name value pairs appended to URL in order to send input data to

    a particular web resource from client machine.

    Servlets [email protected] 3

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    4/39

    Comspark Info India Pvt Ltd. CSREDDY

    PROTOCOL:

    It is a set of rules and regulations, which can be used to carry the data from one

    machine to another machine over the network.

    The main purpose of protocol in the client server architecture is to carry request fromclient to the server and to carry response from server to the client. TCP, IP, UDP,

    HTTP, ARP, RARP etc

    In general we will use Http protocol in our web applications why?

    In general web application requires a protocol and it must satisfy the fallowing

    properties.

    1) Connection less protocol: Not to have physical connection, to have a logical

    connection.

    2) Stateless protocol: Not to remember the previous request data at the time of

    processing the later request.

    3) A compatible protocol should carry hypertext data: In general we will carry

    only hypertext data as a request from client to server and as a response from serverto client.

    Http protocol is a connection less, stateless and a compatible protocol to

    carry hypertext data from client to server and from server to client.

    6)How Http protocol maintain its stateless nature?

    In the web applications we send a request from client machine when protocol will

    establish a virtual socket connection in between client and the server.

    After getting the connection, protocol will prepare a request format having header

    part and body part, where header part will maintain all the request headers i.e. clientand servers IP Address, Port Numbers, accepted language, client URL . Where

    Body part will maintain client specified input data.

    After getting the request format protocol will carry request format to the server,

    where server will generate response while execution of a particular web application.

    Upon receiving response from server, protocol will prepare response format having

    header part and body part. Where header part will maintain response headers likecontent type, client URI, Status line. Where body part will maintain server generated

    dynamic response.

    After getting the response format protocol will carry that to the client machine.Where client Browser will take that html response and executed and display the

    response on the client Browser. When response was reached to the client machine protocol will terminate the

    established virtual socket connection.

    The data which we transferred along with the request and along with the response

    could be remembered by the protocol up to the existence of virtual socketconnection.

    At the time of processing the later request protocol could not maintain previous

    request data; there fore Http protocol is a stateless protocol.

    Servlets [email protected] 4

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    5/39

    Comspark Info India Pvt Ltd. CSREDDY

    HTTP PROTOCOL:

    Http protocol will provide an advantage for the developers to specify different types

    of request at client machine. This flexibility is possible due to the availability of 7number of Http methods at Http Protocol.

    As per the Http 1.0 version the Http methods are 1) GET 2) POST 3) HEAD

    As per the Http 1.1 version the Http methods

    1) Options 2) PUT 3) TRACE 4) DELETE

    The common name for all the above Http methods is BIG-7 Http Methods.

    Http 1.1 version has introduced one reserved Http Method that is Connect.

    7) Write the differences between GET Request and POST Request?

    What are the diff b/w DOGET method & DOPOST Method? (Invalid Question)

    1) GET Request is a default request where as POST request is not a default request.

    2) GET Request should not have the Body Part where as POST Request should have Body

    Part.

    3) Due to unavailability of the Body Part with the GET Request if we specify any input dataat client machine then GET Request will carry that to the server through the request

    format header part but request format header part should have memory limitation. Itcan able to accommodate up to 256 number of characters. Hence GET Request able to

    carry less volume of the data.Due to availability of Body Part in POST Request if we specify any

    input data at client machine then POST Request will carry that to the server throughRequest Format Body part. Here Request Format Body Part should not have any

    memory limitation hence POST Request able to carry large volumes of the data.

    4) If we specify any secure data at client machine along with the get request then that

    client data will be appended on the client address bar as a query string along with URL.There fore GET Request will not provide security for the client specified input data.

    If we specify any input data with the POST Request at the clientmachine then that input data could not appear on the client address bar hence POST

    Request will provide security for the client data.

    5) In general GET request can be used to download the data from server and POSTRequest can be used to upload the data on to the server.

    6) In general GET request could support Book Marks at the Browser but POSTRequest could not support Book Marks at Browser.

    8) What are the differences between GET Request and HEAD Request? When we send a GET Request for a particular resource available at server machinethen server will send back only the requested resource as a response to the client machine.

    If we send HEAD Request for a particular web resource then server will send backthe requested resource as well as the Meta data of the requested resource as a response to

    the client machine.

    HEAD Request internally uses GET Request.

    Servlets [email protected] 5

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    6/39

    Comspark Info India Pvt Ltd. CSREDDY

    OPTIONS Request: This request type can be used to identify which Http Methods could besupported by the present server available at the server machine.

    9)What are the differences between POST Request and PUT Request?

    Both POST and PUT Request can be used to upload the data on to the server.

    To upload the data if we use POST Request then it is not mandatory to specify any

    location on server machine along with the request at the client machine.

    To upload the data on to the server if we use PUT Request then it is mandatory tospecify particular location on server machine along with the request at client

    machine.

    NOTE: almost all the servers are not supporting PUT Request as per their security

    constraints.

    TRACE Request:

    This Request type can be used to check out the working status of a particularresource available at server machine. TRACE Request is a simulation of echo server.

    DELETE Request:This Request type can be used to delete a particular resource available at server

    machine. Almost all the servers are not supporting DELETE Request as per their securityconstraints.

    Http Status Codes:

    Http protocol has introduced a concept called as Status Codes to get the status ofthe request processing from server machine.

    To do the above Http 1.1 version has introduced the fallowing status codes.

    Status Code Range Description

    1XX 100-199 INFORMATION STATUS CODES

    2XX 200-299 SUCCESS RELATED STATUS CODES

    3XX 300-399 REDIRECTIONAL STATUS CODES

    4XX 400-499 CLIENT SIDE ERRORS

    5XX 500-599 SERVER SIDE ERRORS

    SERVER:

    To the job of the server in Client Server Architecture is to get the request and togenerate the response. If we want to make a machine as a server machine then we need to

    install a piece of software called as server software.

    Eg:

    1) Apache Tomcat

    2) BEA Web logic (Oracle)

    3) IBM Web sphere

    4) Macromedia JRUN

    5) Sun Micro Systems J2EE, SUNONE, Glass Fish .. etc..

    There are two types of servers are there.

    Servlets [email protected] 6

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    7/39

    Comspark Info India Pvt Ltd. CSREDDY

    Web Servers

    Application Servers

    10) What are the differences between Web server and Application Server?

    > Web servers are the servers which will provide the environment to execute only

    Web Applications.

    Application Servers are the servers, which will provide the environment to execute

    both Web Applications and Distributed Applications.

    > Web servers are the servers which will not provide middle ware services like logging,

    authentication security, transactions, JNDI etc..

    Application Servers are the servers, which will provide all the above specified

    middle ware services.

    > Web Servers are the servers, which could work with only Web Clients (html clients).

    Application Servers are the servers which could work with any kind of clients(html, wml...) like web clients, mobile clients.

    NOTE: Up to Tomcat 4.0 Version Web Server Tomcat 5.0 Version behaves like aApplication Server. Every server trying to convert as Application Server because of Web

    Servers bounded nature.

    When we install server software on the server machine automatically server

    software will be available in the form of the fallowing two modules.

    1) Main Server 2) Container

    11) What are the differences between Main server and Container?

    When we send a request from client to the server then main server will pick up therequest and validate the request data i.e. whether the request data having any harmful

    code or not. If the request data validation succeeded then main server will bypass therequest to container.

    Container is a component, which will accommodate the Web Applications, upon

    receiving a request from main server container will execute the requested web application

    and generate the dynamic response. After generating the dynamic response container willbypass dynamic response to the main server where main server will forward dynamic

    response to the protocol.

    Types of Containers:

    Containers could be classified in the fallowing two ways.

    1) As per the technology which we are used.

    a) Servlet Container to execute Servlets

    b) JSP Container to execute Jspsc) EJB Container to execute EJB Components

    d) CGI Container to execute CGI Components. . Etc

    2) As per the Containers physical existence there are three types of containers.

    i) Standalone Containers: It is an integration of Main Server and Container.

    ii) In Process Containers: It is a container existed inside the Main Server.

    Servlets [email protected] 7

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    8/39

    Comspark Info India Pvt Ltd. CSREDDY

    iii) Out of Process Container: It is a container existed in out side of the Main Server.

    Note: Now a days all the servers are using Standalone Containers for the easy of

    maintenance.

    Steps to Design Web Application

    To design any Web Application we should use the fallowing steps.

    1) Prepare Web Applications Directory Structure

    2) Design Deployment Descriptor

    3) Design the Web Resources as per the ApplicationRequirements

    4) Start the server and execute the Web Application

    STEP: 1 Web Applications Directory Structure:

    When we install the Tomcat Server automatically Tomcat 5.5 (if the version is 5.5)folder will be created. Tomcat server provides webapps is a folder to accommodate the

    developers Web Applications as Shown bellow.

    Tomcat 5.5

    bin webapps

    lib application folder/ context root

    config themes (.css) WEB-INF

    common images (.jpg, .img) web.xml classes

    log literature (.doc) lib (.jar) .class

    work .html .class

    .jsp

    As per the application requirements we should prepare our own folder under

    webapps folder called as application folder/context root.

    Application folder includes

    1. themes: To maintain cascade style sheets

    2. images: To maintain back ground scenarios, logos of the organization in theform of .jif, .jpeg etc...

    3. literature: To maintain documentations about the web applications.4. static resources: .html files

    5. dynamic resources: .jsp files

    6. WEB-INF: To maintain web applications deployment information. Where WEB-INF folder includes

    a) Deployment Descriptor: To provide the description about the webapplications deployment.

    Servlets [email protected] 8

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    9/39

    Comspark Info India Pvt Ltd. CSREDDY

    b) lib folder: To maintain the explicit .jar files which are required for theweb application design.

    c) classes: Which includes all the .class files like servlets, filters, listeners .

    The above web application directory structure could be divided into the fallowing twoparts. They are given bellow

    1) Public Area/ Client Area: The area which comes under outside of theWEB-INF folder. If we deploy any resource under public area then clientable to access it with its file name directly.

    2) Private Area/ Server Area: The area which comes under inside theWEB-INF folder is called as private area or server area. If we deploy anyresource under private area then client unable to access that resources

    with their names directly, client able to access that resources throughindirection.

    In general servlets could be deployed under private area to access these servlets we

    must define the uri patterns, through these uri patterns only client able to access therespective servlet.

    STEP: 2 Deployment Descriptor:

    It is a web.xml file, which will provide the complete description about the web

    applications deployment.

    Deployment Descriptor should provide the fallowing

    1. servlet configuration

    2. filters configuration

    3. listeners configuration

    4. welcome files configuration5. initialization parameters

    6. context parameters

    7. session timed out

    8. load-on-start up

    9. error pages configuration

    10. Security constraints etc

    In general in the web applications we are able to deploy the servlets under

    classes folder i.e. private area, where client able to access the servlets throughindirection i.e. through URL pattern.

    > To provide the mapping between servlet class and the respective URL pattern as part of

    the servlet configuration we will use the fallowing xml tags in web.xml file.

    logical name

    fully qualified name of servlet

    Servlets [email protected] 9

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    10/39

    Comspark Info India Pvt Ltd. CSREDDY

    logical name

    /url pattern name

    Eg:

    rep

    reports

    rep

    /report

    admin.html

    Aspart of the web applications we should define the URL patterns in web.xml file by

    using the fallowing three approaches.

    1) Exact Match Method

    2) Directory Match Method

    3) Extension Match Method

    Exact Match Method:

    In case of Exact Match Method we will define a URL pattern in web.xml file, where

    client must provide the URL pattern in its URL the same URL pattern defined in web.xml file.

    Eg: /first

    http://localhost:8080/app1/first (valid)http://localhost:8080/app1/first/second (in valid)

    http://localhost:8080/app1/second (in valid)

    Directory Match Method:

    In case of Directory Match Method we will define the URL pattern like bellow.

    /a/*

    In this case client must provide the URL pattern may starts with a and may ends with

    anything.

    http://localhost:8080/app1/a(valid)http://localhost:8080/app1/a/b(valid)

    http://localhost:8080/app1/b/a (in valid)

    Extension Match Method:

    In this case we will define the URL pattern like bellow in web.xml file.

    Servlets [email protected] 10

    http://localhost:8080/app1/firsthttp://localhost:8080/app1/first/secondhttp://localhost:8080/app1/secondhttp://localhost:8080/app1/ahttp://localhost:8080/app1/a/bhttp://localhost:8080/app1/b/ahttp://localhost:8080/app1/firsthttp://localhost:8080/app1/first/secondhttp://localhost:8080/app1/secondhttp://localhost:8080/app1/ahttp://localhost:8080/app1/a/bhttp://localhost:8080/app1/b/a
  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    11/39

    Comspark Info India Pvt Ltd. CSREDDY

    *.do

    In this case client must provide the URL pattern may starts with anything and must endswith the specified extension in web.xml file i.e. (.do)

    http://localhost:8080/app1/a.do (valid)http://localhost:8080/app1/a (in valid)

    http://localhost:8080/app1/a.xyz (in valid) http://localhost:8080/app1/a/b.do (valid)

    STEP: 3

    Design Web Resources as for the Application Requirements:

    To design a servlet servlet API has provided the fallowing pre defined library in theform of the packages javax.servlet.*; javax.servlet.http.*;

    12) What is meant by servlet and in how many ways we are able to design

    servlets?

    Servlet is an object available at server machine, which was implemented eitherdirectly or indirectly Servlet Interface. As per the predefined library provided by the Servlet

    API there are three ways to design servlets.

    Implementing Servlet Interface:

    In this case take one user defined class which is implementing Servlet Interface.

    public class Myservlet implements Servlet Interface

    {

    // Body of the Servlet

    }

    Extending Genericservlet Abstract Class:

    In this case take one user defined class which is extending from Genericservlet abstractclass.

    public class Myservlet extends Genericservlet

    {

    // Body of the Servlet

    }

    Extending Httpservlet Abstract Class:

    In this case take one user defined class which is extending from Httpservlet abstract class.

    public class Myservlet extends Httpservlet

    {

    // Body of the Servlet}

    STEP: 4

    Start server and access the web application:

    After design the web application to execute the web applications we need to start theserver. Here we are able to start the server in the fallowing three ways.

    1) Use startup.batch file available in c:\Tomcat5.0\bin\stratup.batch

    Servlets [email protected] 11

    http://localhost:8080/app1/a.dohttp://localhost:8080/app1/ahttp://localhost:8080/app1/a.xyzhttp://localhost:8080/app1/a/b.dohttp://localhost:8080/app1/a.dohttp://localhost:8080/app1/ahttp://localhost:8080/app1/a.xyzhttp://localhost:8080/app1/a/b.do
  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    12/39

    Comspark Info India Pvt Ltd. CSREDDY

    2) Use system program Tomcat, for this we are using the path

    start-> programs-> Apache Tomcat -> start Tomcat

    3) Use system service apache Tomcat for this we are using the path

    start-> Run -> services.msc ->ok -> select Apache Tomcat -> click on start

    service

    First Approach to Design the SERVLET:

    In this approach we will take one user defined class, which is implementing ServletInterface.

    Public interface Servlet

    { public void init(ServletConfig config)throws ServletException;

    public void service(ServletRequest req,ServletResponse res)throwsServletException,IOException;

    public ServletConfig getServletConfig();

    public String getServletInfo();

    public void destroy();}

    Public class Myservlet implements Servlet

    {

    //Body of the Servlet Class

    }

    Where init() can be used to provide servlet initialization.

    Where service() can be used to provide required service for the request. Service() is

    like main() in java applications, which will have the complete application logic and

    which could be executed by the container upon receiving a request from the clientmachine automatically.

    Where getServletConfig() can be used to return the generated Servlet Config object

    reference.

    NOTE: Where ServletConfig is an object, which will maintain the configuration details

    of a particular servlet like the logical name of the servlet, initialization parameters

    and the reference of the servlet context object.

    Where getServletInfo() can be used to return the generalized description of theparticular servlet.

    Where destroy() can be used to destroy servlet object.

    EX: The fallowing example demonstrates how to design a servlet by implementingthe ServletInterface and how to access from client machine?

    Firstservletapp - WEB-INF web.xml, classes Myservlet.classWeb.xml

    ms

    Myservlet

    Servlets [email protected] 12

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    13/39

    Comspark Info India Pvt Ltd. CSREDDY

    ms

    /first

    Myservlet.java:

    import javax.servlet.*;

    import java.io.*;

    public class Myservlet implements Servlet

    {

    public void init(ServletConfig config)throws ServletException

    {

    }

    public ServletConfig getServletConfig()

    {return null;

    }

    public String getServletInfo()

    {

    return null;

    }

    public void destroy()

    {

    }

    public void service(ServletRequest req,ServletResponse res)throwsServletException,IOException

    { res.setContentType("text/html");

    PrintWriter out=res.getWriter();

    out.println("");

    out.println("");

    out.println("");

    out.println("Hellow _____First Servlet Using Servlet Interface");

    out.println("");

    }

    } After getting the Servlets.java file we should compile it and we should keep the

    generated .class file under the classes folder.

    To compile the servlets.java files we need to set the class path environment variable

    to the location where we have Servlet-api.jar file.

    i.e.set classpath=%classpath%;C:\Tomcat 5.0\Common\lib\Servlet-api.jar;

    set classpath=%classpath%;C:\Tomcat 6.0\ lib\Servlet-api.jar;

    Servlets [email protected] 13

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    14/39

    Comspark Info India Pvt Ltd. CSREDDY

    > In the web applications we send a request from client machine when protocol willestablish a virtual socket connection in between client and the server.

    After getting the connection, protocol will prepare a request format having headerpart and body part, where header part will maintain all the request headers i.e. client

    and servers IP Address, Port Numbers, accepted language, client URL . WhereBody part will maintain client specified input data.

    Protocol will carry request format to the server. Main server will pickup the request

    and check out whether the request data having any harmful data or not, if thevalidation success the main server will by pass the request to the container.

    When container receives a request from main server then container will take the

    fallowing steps.1. Identify the application context and resource name

    2. Container will check whether the resource is html or jsp page, if the resource is html

    or jsp page then container will search them under the application folder.

    3. If the resource name is not having .html or .jsp extension container wouldunderstand the resource name is a URL pattern for a particular servlet

    available under classes folder.

    4. Container will identify the name and location of the servlet with respect to the urlpattern by gone through web.xml file.

    5. When container identifies the requested resource then container will take thefallowing steps.

    I) Servlet loading: Here the container will load the requested servlet byte code tothe memory.

    II) Servlet instantiation: Here the container will create an object for loadedservlet.

    III) Servlet initialization: Here the container will execute the init() to performinitialization of the servlet.

    IV) Creating Request and Response Objects: After the servlet initializationcontainer will create a thread to access service method. To access service()

    container must create servlet request and servlet response objects.

    V) Generating Dynamic Response:After getting the request and response objectscontainer will execute service() method, here container will generate dynamic

    response to the response object.

    VI) Dispatching Dynamic Response to the Client: As part of the executing theservice method when container generated thread reaches to the ending part of

    the service method then automatically thread will be in dead state, by this

    container will dispatch response to the main server, here main server will by passthe response to the protocol. Now protocol will prepare a response format having

    header part to maintain response headers and having body part to maintain thedynamic response. Now protocol will carry response to the respective client.

    Servlets [email protected] 14

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    15/39

    Comspark Info India Pvt Ltd. CSREDDY

    VII) Destroying Request and Response Objects: When response was reached tothe client machine then protocol will terminate the virtual socket connection; bythis container will destroy request and response objects.

    VIII) Servlet Deinstantiation: After destroying request and response objectscontainer will wait up to some time, depends on the container implementation,when container identifies no further request for the same resource then container

    will destroy the servlet object.

    IX) Servlet Unloading: As per the servers memory management container willunloads the loaded servlet Byte Code.

    Drawbacks about first approach of designing:

    In this approach if we want to design servlets we need to implement directly servlet

    interface i.e. we should provide the implementation for all the methods got declared inservlet interface irrespective of the application requirement.

    This approach will increase burden for the developers and it will increase burden forthe developers and it will increase unnecessary methods in the applications.

    For the above requirement sun Microsystems have provided a solution in the form of

    Generic Servlet Abstract Class.

    Second Approach to Design the Servlets:

    In this approach we need to take a user defined class, which is extending from

    Generic Servlet Abstract class.

    Where Generic Servlet is an abstract class which was implemented directly servlet

    interface.

    public abstract GenericServlet implements Servlet,ServletConfig,Serializable

    { private transient ServletConfig config;

    public void init(ServletConfig config)throws ServletException

    { this.config=config;

    init();

    }

    public void init()

    {

    }

    public abstract void Service(ServletRequest req,ServletResponse res)throwsSevletException,IOException;

    publicServletConfig getServletConfig()

    { return config;

    }

    public String getServletInfo(){ return null;

    }

    public void destroy()

    { config=null;

    }

    }

    Servlets [email protected] 15

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    16/39

    Comspark Info India Pvt Ltd. CSREDDY

    public class Myservlet extends GenericServlet

    {

    public void Service(ServletRequest req,ServletResponse res)throws

    SevletException,IOException

    {

    }}

    From the above representation Generic Servlet is an Abstract class which was

    implemented directly implemented Serializable interface thats why we are able toserialize directly Generic Servlet object.

    In predefined Generic Servlet Abstract class config reference variable is

    transient thats why it could not be participated in Generic Servlet objectserialization.

    In predefined Generic Servlet Abstract class init() is overloaded, the second init() isfor the sake of the developers customization in servlet initialization.

    In predefined Generic Servlet Abstract class still service() is an abstract method to

    improve the sharability.

    EX: The fallowing example demonstrates how to design a servlet by implementingthe ServletInterface and how to access from client machine?

    Genericservletapp - WEB-INF web.xml, classes Myservlet.classweb.xml:

    gs

    Myservlet

    gs

    /generic

    Myservlet.java:

    import javax.servlet.*;

    import java.io.*;

    public class Myservlet extends GenericServlet{ public void service(ServletRequest req,ServletResponse res)throws

    ServletException,IOException

    { res.setContentType("text/html");

    PrintWriter out=res.getWriter();

    out.println("");

    out.println("");

    out.println("");

    Servlets [email protected] 16

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    17/39

    Comspark Info India Pvt Ltd. CSREDDY

    out.println("");

    out.println("");

    out.println("

    ");

    out.println("Hellow.......... Generic Servlet");

    out.println("");

    }

    }

    Modifications to first & second approach of designing:

    In first approach of designing the servlet container will execute only one init() aspart of the servlet initialization.

    But in Generic Servlet flow of execution container will execute two init() as part ofthe servlet initialization.

    Third Approach to Design the Servlets:

    12) What are the differences between GenericServlet and HttpServlet?

    > GenericServlet is protocol independent i.e. GenericServlet able to process any kind ofprotocol request including Http.

    HttpServlet is Http protocol dependent i.e. HttpServlet able to process only HttpProtocol Request.

    > GenericServlet will not provide any option for the developers to specify different typesof request at client machine.

    HttpServlet will provide an option for the developers to specify different types ofrequests at client machine.

    > Due to the above reason GenericServlet is not compatible with the protocol but

    HttpServlet is very much compatible with the Http Protocol.

    Note:

    In case of GenericServlet if you specify get request or post request... at client machine theGenericServlet will treat that request as a normal request and in the normal wayGenericServlet will process that request by executing service().

    In case of HttpServlet if we specify Get Request, Post Request... then HttpServlet willconsider that request types and provide a separate execution process like doGet(),doPost()

    respectively.

    > In case of GenericServlet as part of the request processing container will execute only one

    service method but incase of HttpServlet to process a request container will executeservice(ServletRequest req,ServletResponse res) from where container call the

    service(HttpServletRequest req,HttpServletResponse res) and from where containerwill call doXXX() depends on the request type.

    web.xml:

    ms

    Myservlet

    Servlets [email protected] 17

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    18/39

    Comspark Info India Pvt Ltd. CSREDDY

    ms

    /http

    Myservlet.java:

    import java.io.*;

    import javax.servlet.*;

    import javax.servlet.http.*;

    public class Myservlet extends HttpServlet

    {

    public void service(HttpServletRequest req,HttpServletResponse res)throwsServletException,IOException

    {

    PrintWriter out=res.getWriter();

    java.util.Date now=new java.util.Date();

    out.println("Hello Http Servlet");

    out.println("Current Date and Time is :"+now);

    }

    }

    Servlet Life Cycle:

    When we send a request to the particular servlet then container will perform thefallowing servlet life cycle mechanisms.

    Servlet Loading Container c=Class.forName (myservlet);

    Servlet Instantiation c.newInstance ();

    Servlet Initialization init ();

    Request Processing service ();

    Servlet Deinstantiation destroy ();

    From the above representation while processing one request if you send many morenumber of request then servlet container should not perform servlet loading, servlet

    Servlets [email protected] 18

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    19/39

    Comspark Info India Pvt Ltd. CSREDDY

    instantiation, servlet initialization, for the later request directly servlet container will bringthem to the request processing phase.

    From the above representation servlets by default able to handle multiple number of

    requests at a time i.e. allowing multiple number of threads at a time without having any

    side effects. Thats why servlets are by default thread safe.

    Load on startup tag:

    As part of the web applications in general container will perform servlet loading,servlet instantiation, and servlet initialization when it receives a request from client machine

    after starting the server.

    As per the application requirements to improve the performance of the web

    application we need to make servlet container to perform servlet loading, servletinstantiation, and servlet initialization at the time of startup the server.

    To achieve the above requirement we should use the fallowing tag in web.xml file.

    -----

    -----

    1 (priority value)

    ----

    ----

    If more than one servlet is having load on startup tag with different values then the servlet

    which is having less priority value should have more priority i.e. this servlet could performloading, instantiation, initialization in earlier stages at the time of startup the server, whichservlet is having highest priority value then that servlet should have least priority i.e. this

    servlet should be perform servlet loading, servlet instantiation, initialization in the laterstages at the time of startup the server.

    If more than one servlet having same load on startup value then which servletshould have highest priority is depending on that container implementation.

    Form Design:

    In the web application if we want to send any input data from client to server for a

    particular server we should require user interface in the form of forms at client machine.

    As part of the web application we require to specify different request types at client

    machine apart from the default request as per the application requirement.

    To specify a particular request type at client machine we should require a userinterface in the form of forms at client machine.

    The entire web application quality depends on the fallowing 2 factors in general.

    Less Response Time

    Servlets [email protected] 19

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    20/39

    Comspark Info India Pvt Ltd. CSREDDY

    Very good look and feel of design part

    To improve look and feel of the web application we should require very good userinterface in the form of forms at client machine.

    In general in the web application if we want to design user interface thenwe may use the technologies like AWT, Swings, Html, Jsp, Velocity, Free

    markers.

    In general we will use Html as a scripting technology to design user forms.

    In the web application we are able to design user forms in the fallowing two

    ways.

    Form Generation At Deployment

    Form Generation At Request Processing Time.

    At the time of designing the web application if we design any html page and if we

    keep that under application folder then it is called as Static Form Generation.

    If we specify the complete html logic inside a servlet and generating form byexecuting a particular servlet is called as Dynamic Form Generation.

    If we specify any input data at client machine in user form then when we submit user

    form to the server then client specified input data will stored on the request object in theform of name value pairs through the protocols request format.

    If we want to get the value of particular name value parameter from request object,we will use the fallowing method from request object.

    public String getParameter(String name);

    To get all the names of the name value parameters on request object we will use the

    fallowing method.

    public Enumeration getParameterNames();

    13) What is the difference between Parameters and Attributes?

    Parameter is a name value pair which could be stored on to the request object at the

    time of creation.

    Attribute is a name value pair which could be stored on to the request object after

    the request object creation, not at the time of creation.

    Parameter will specify static inclusion of the data where attribute will specify dynamic

    inclusion of the data.

    To specify an Attribute into the request object we will use the following method.

    public void setAttribute(String name,Objectvalue);

    To get the value of particular attribute from request object we will use the fallowing

    method.

    public Object getAttribute(String name);

    To get all the names of the attributes from request object we will use the followingmethod.

    public Enumeration getAttributeNames();

    Servlets [email protected] 20

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    21/39

    Comspark Info India Pvt Ltd. CSREDDY

    To get multiple values which are associated with a single name in the request objectwe will use the fallowing.

    Public String [] getParameterValues(String name);

    EX: The fallowing example demonstrates how to design a form at deployment and

    how to send input data from this form.

    Formapp -> form.html, WEB-INF -> web.xml, classes -> Myservlet.class

    Form.html

    User Details

    User Name

    UserPwd

    UserQualification Bsc

    Mca

    Mtech

    UserGender



    UserLocation

    Hyderabad

    Banglore

    Pune



    usercoments



    web.xml:

    f

    Servlets [email protected] 21

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    22/39

    Comspark Info India Pvt Ltd. CSREDDY

    Myservlet

    f

    /form

    Myservlet.java:

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    public class Myservlet extends HttpServlet

    { protected void doPost(HttpServletRequest req,HttpServletResponse res)throwsServletException,IOException

    { res.setContentType("text/html");

    PrintWriter out=res.getWriter();

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

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

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

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

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

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

    String []uloc=req.getParameter("uloc");

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

    out.println("");

    out.println("");

    out.println("User Details");

    out.println("

    ");

    out.println("");

    out.println("");

    out.println("User Name.......... "+uname);

    out.println("

    ");

    out.println("User Qualification
    ");

    if(bsc!=null)

    out.println(bsc+"
    ");

    if(mca!=null)

    out.println(mca+"
    ");

    if(mtech!=null)

    out.println(mtech+"
    ");

    out.println("
    ");

    out.println("User Gender"+ugen);

    Servlets [email protected] 22

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    23/39

    Comspark Info India Pvt Ltd. CSREDDY

    out.println("

    ");

    out.println("User Locations");

    out.println("
    ");

    for(int i=0;i

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    24/39

    Comspark Info India Pvt Ltd. CSREDDY

    out.println("

    ");

    out.println("Qualification ");

    out.println("

    ");

    out.println("Email ");

    out.println("

    ");

    out.println("");

    out.println("");

    }

    public void doPost(HttpServletRequest req,HttpServletResponse res)throwsServletException,IOException

    {

    res.setContentType("text/html");

    PrintWriter out=res.getWriter();

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

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

    String equal=req.getParameter("equal");String email=req.getParameter("email");

    out.println("");

    out.println("");

    out.println("Employee Name:"+ename);

    out.println("

    ");

    out.println("Employee Age:"+eage);

    out.println("

    ");

    out.println("Employee Qualification:"+equal);

    out.println("

    ");

    out.println("Email ID:"+email);out.println("");

    }

    }

    Servlet Config:

    Servlet Config is an object which can be used to maintain all the configuration details

    of a particular servlet, where that configuration details are like logical name of the servlet,initialization parameters and reference of Servlet Context Object.

    Servlet Config object will be created by the container just after the servletinstantiation and just before calling init() as part of servlet initialization.

    Servlet Config object will be destroyed by the container just before the servletDeinstantiation. Due to the above reasons the life of the servlet config object is the life of

    servlet.

    Servlet Config is an object, which will provide the complete view of a single servlet.

    I.e. with respect to the particular servlet an individual servlet config object will be created.

    Servlets [email protected] 24

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    25/39

    Comspark Info India Pvt Ltd. CSREDDY

    If we specify any data in Servlet Config object then that data could be shared torespective servlet only. Due to this reason the scope of the Servlet Config object is

    particular servlet only.

    Logical name of the servlet is a name specified along with servlet name tag in

    web.xml file. To get the particular servlet we will use the fallowing method from

    servlet config object. public String getServletName(); To get the reference of the Servlet Config object we will use the fallowing method

    from servlet interface. public ServletConfig getServletConfig();

    If we want to specify initialization parameters on to the Servlet Config object first we

    need to specify them in web.xml file as part of the particular servlet configuration

    i.e... Under servlet tag for this we will use fallowing tags in web.xml file.

    name

    value

    ------

    ----

    ----

    ----

    When we send a request to a particular servlet from client machine then container

    will go for web.xml file, where container will check whether the servlet is having anyinitialization parameters or not, if we have initialization parameters then container will read

    them and stored on to the ServletConfig Object at the time of creation.

    To get the value of a particular initialization parameter from ServletConfig Object

    then we will use the fallowing method.

    public String getInitParameter(String name);

    To get the names of the initialization parameters from ServletConfig Object we willuse the fallowing method.

    public Enumeration getInitParameterNames();

    EX: The fallowing example demonstrates how to specify initialization parameters

    for a servlet and how to get them from ServletConfig Object?

    web.xml

    a

    abc

    Servlets [email protected] 25

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    26/39

    Comspark Info India Pvt Ltd. CSREDDY

    b

    bcd

    ms

    Myservlet

    ms

    /config

    Myservlet.java:

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    public class Myservlet extends HttpServlet

    {public void doGet(HttpServletRequest req,HttpServletResponse res)throws

    ServletException,IOException

    { res.setContentType("text/html");

    PrintWriter out=res.getWriter();

    ServletConfig config=getServletConfig();

    out.println("");

    out.println(""+config.getInitParameter("a"));

    out.println(""+config.getInitParameter("b"));

    out.println("

    ");

    java.util.Enumeration e=config.getInitParameterNames();while(e.hasMoreElements)

    { out.println(e.nextElement());

    out.println("

    ");

    }

    out.println("Logical Name"+config.getServletName();

    out.println("");

    }

    }

    14) What is the difference between ServletConfig and ServletContext Objects?

    > ServletConfig is an object, which will provide Configuration details of a particularservlet like logical name of the servlet, initialization parameters..

    ServletContext is an object, which will provide the context details of a particular

    web application, like logical name of the web application and context parameters of the webapplication.

    ServletConfig is an object, which will provide the complete view of a single

    servlet. ServletContext is an object, which will provide the complete view of a

    single web application.

    Servlets [email protected] 26

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    27/39

    Comspark Info India Pvt Ltd. CSREDDY

    Servlet Config object will be created by the container just after the servlet

    instantiation and just before calling init() as part of servlet initialization.

    ServletContext is an object will be created by the container the movement when

    we start up the server.

    Servlet Config object will be destroyed by the container just before the servlet

    Deinstantiation. Due to the above reasons the scope of the servlet config object isthe scope of the particular servlet only. ServletContext Object will be destroyed bythe container the movement when we shut down server. Due to the above reasons

    the scope of the ServletContext Object is the scope of particular web application.

    ServletConfig Object will provide less sharability i.e. if we specify any data onto

    the ServletConfig Object then it could be shared to a particular servlet.

    ServletContext Object will provide more sharability i.e. if we specify any data onto

    the ServletContext Object then that data could be shared to all the number ofresources which are available at the particular web application.

    ServletConfig Object will allow only parameters data i.e. static inclusion of the

    data. ServletContext Object will allow both parameters data and dynamic inclusion

    of the data. ServletConfig Object will be created by the container when it receives a request

    from client machine except in load-on-stratup case. ServletContext Object will be

    created by the container with or without receiving request from client machine.

    To get the reference of the ServletContext Object we will use the fallowing method

    from ServletConfig Object or from ServletContext Object.

    public ServletContext getServletContext();

    To specify logical name for the web application we will use the fallowing tag inweb.xml file.

    name

    -----

    ----

    To get the logical name of the web application we will use the fallowing method from

    ServletContext Object.

    public String getServletContextName();

    if we want to specify context parameters on to the ServletContext Object first we

    need to define them in the web.xml file, for this we will use the fallowing xml tags inweb.xml file.

    name

    value

    Servlets [email protected] 27

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    28/39

    Comspark Info India Pvt Ltd. CSREDDY

    ------

    When we start the server, automatically container will recognize all the web

    applications which were deployed. As part of this container will recognize read and pass therespective web.xml files.

    At the time of recognizing the web.xml file container will read the specified ContextParameters in the respective web.xml file and store them in the respective servlet Context

    Object at the time of creation.

    To get the value of a particular Context Parameter we will use the fallowing method

    from ServletContext Object.

    public String getInitParameter(String name);

    To get the all the names of the context parameters from servlet context object wewill use the fallowing method.

    public Enumeration getInitParameterNames();

    To set an attribute on to the ServletContext Object we will use the fallowing method.

    public void setAttribute(String name, Object value);

    To get the value of a particular ContextAttribute from servlet Context object we wii

    use the fallowing.

    public Object getAttribute(String name);

    To get all the names of Context Attributes from ServletContext Object we will use thefallowing method.

    public Enumeration getAttributeNames();

    15) What is meant by foreign context?

    It is a ServletContext Object of another web application being executed at the sameserver.

    To get the foreign Context Object reference we will use the fallowing method.

    public ServletContext getContext(String path);

    Almost all the servers are not supporting foreign Context Object as per the securityconcerns in this case getContext() will return null as a value.

    Ex: Context parameters program?

    web.xml

    mycontextapp

    a

    abc

    b

    Servlets [email protected] 28

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    29/39

    Comspark Info India Pvt Ltd. CSREDDY

    bcd

    ms

    Myservlet

    ms

    /context

    Myservlet.java:

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    public class Myservlet extends HttpServlet{

    public void doGet(HttpServletRequest req,HttpServletResponse res)throws

    ServletException,IOException

    {

    res.setContentType("text/html");

    PrintWriter out=res.getWriter();

    ServletConfig config=getServletConfig();

    ServletContext context=getServletContext();

    String lname=Context.getServletContextName();

    out.println("");out.println("Logical name:"+lname);

    out.println("

    ");

    out.println("a---->"+context.getInitParameter("a"));

    out.println("b---->"+context.getInitParameter("b"));

    out.println("

    ");

    java.util.Enumeration e=context.getInitParameterNames();

    while(e.hasMoreElements)

    {

    out.println(e.nextElement());

    out.println("

    ");}

    context.setAttribute("1","123");

    context.setAttribute("2","234");

    out.println("1--->"+context.getAttribute("1"));

    out.println("

    ");

    out.println("2---->"+context.getAttribute("2"));

    out.println("

    ");

    Servlets [email protected] 29

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    30/39

    Comspark Info India Pvt Ltd. CSREDDY

    e=context.getAttributeNames();

    while(e.hasMoreElements)

    {

    out.println(e.nextElement());

    out.println("

    ");

    }

    out.println("ForeignContext..."+context.getContext("/configapp"));

    out.println("");

    }

    }

    Servlet Communication:

    As part of the web applications design it is not at all suggestible to provide thecomplete application logic with in a single servlet. It is suggestible to distribute the web

    application logic over many more number of web resources.

    Once if you distribute web application logic over many more number of webresources then to execute the web application we should go for providing thecommunication between web resources called as Servlet Communication.

    Servlet Communication can be divided into the fallowing two ways.

    Servlet Communication

    Browser Servlet Communication Web Component Communication

    Sending Normal Request Normal Response Include Forward Sending Error Messages

    Request Redirection

    Request Redirection by Using Hyperlinks

    Request Redirection by Setting Response Header

    Request Redirection by using Send Redirect ()

    As part of the client server architecture in general client will send request to a

    particular servlet, servlet could be executed and generate dynamic response to client

    machine. This is best suitable for Browser to Servlet Communication.

    Sending Error Messages:In general in web applications design servlets needs to generate some error

    messages due to client side mistakes / server side mistakes. This is possible with theBrowser to Servlet Communication only.

    As per the application requirements if you want to send any error messages in astandardized pattern from a servlet to the browser then we should use the fallowing

    method from servlet Response Object.

    public void sendError(int sc, String desc);

    Servlets [email protected] 30

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    31/39

    Comspark Info India Pvt Ltd. CSREDDY

    Where Status code should be 5xx

    EX: The fallowing application demonstrates how to generate error messages to the

    client in a standardized pattern?

    Senderrorapp - form.html, WEB-INF - web.xml, classes - ErrorServlet.class

    e

    Errorservlet

    e

    /error

    Form.html:

    ABC Fashoin Show


    Name

    Age

    Errorservlet.java:

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

    import java.io.*;

    public class Errorservlet extends HttpServlet

    {

    public void doGet(HttpServletRequest req,HttpServletResponse res)throws

    ServletException,IOException

    {

    res.setContentType("text/html");

    PrintWriter out=res.getWriter();

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

    int uage=Integer.parseInt(req.getParameter("uage"));

    if(uage

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    32/39

    Comspark Info India Pvt Ltd. CSREDDY

    out.println("");

    out.println("");

    out.println("


    ");

    out.println("U R Name:"+uname);

    out.println("

    ");

    out.println("U R Age"+uage);

    out.println("U R Registration ID :12345");

    out.println("");

    }

    }

    }

    Request Redirection:

    The process of redirecting a request from one web application to another webapplication is called as request re direction. We are able to achieve Request Redirection in

    the fallowing three ways.

    1) Request Redirection by Using Hyperlinks2) Request Redirection by Setting Response Header

    3) Request Redirection by using Send Redirect () Mechanism

    Request Redirection by Using Hyperlinks:

    In this approach when we send a request to OLD Web Application client able to

    receive a response with a Hyperlink. Customer may click on the Hyperlink automatically anew request will be send to NEW Web Application. At final client able to receive the required

    response from the NEW Web Application.

    Hutchapp WEB-INF web.xml, classes Hutch.classVodaphoneapp welcome.html, WEB-INF classesWeb.xml:

    h

    Hutch

    h

    /hutch

    Hutch.java:

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    public class Hutch extends HttpServlet

    {

    Servlets [email protected] 32

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    33/39

    Comspark Info India Pvt Ltd. CSREDDY

    public void doGet(HttpServletRequest req,HttpServletResponse res)throwsServletException,IOException

    { res.setContentType("text/html");

    PrintWriter out=res.getWriter();

    out.println("");

    out.println("");

    out.println("

    ");

    out.println("To get the Services of HUtch Click Here");

    out.println("");

    out.println

    ("[email protected]");

    out.println(""); } }

    welcome.html

    Welcome to Vodaphone World

    Drawback:

    This approach will provide extra risk by providing hyperlinks to the customers, to click on

    the hyperlinks. In business point of view this approach is not at all suggestible thats whywe should go for an alternative.

    Request Redirection by Setting ResponseHeaders:

    In this approach when we send a request to OLD Web Application then it will set thelocation of the New Web Application as a response header in the response format with the

    respective status code.

    When client receive the response format client will get new web application URL as avalue of Response Header Location and keep it on its address bar, as per this client browserwill send new request to the new web application automatically without having customer

    interaction.

    To set new web application URL as a response header first we need to set the

    respective status code to the response format, for this we will use the fallowing method.

    public void setStatus(int sc);

    Where status code should be either

    HttpServletResponse.SC_MOVED_TEMPORARLY or

    HttpServletResponse.SC_MOVED_PERMANANTLY

    To set new web application URL as a response header we will use the fallowingmethod from HttpServletResponse Object.

    public void setHeader(String name, String url);

    Where name should be location.

    Ex:

    res.setStatus (HttpServletResponse.SC_MOVED_PERMANANTLY);

    res.setHeader(Location,http://localhost:8080/vodaphoneapp/welcome.html);

    Servlets [email protected] 33

    http://localhost:8080/vodaphoneapp/welcome.htmlhttp://localhost:8080/vodaphoneapp/welcome.htmlhttp://localhost:8080/vodaphoneapp/welcome.html
  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    34/39

    Comspark Info India Pvt Ltd. CSREDDY

    Drawback:

    If you want to perform request redirection with this approach every time we shouldremember status codes, which is difficult for the developers thats why we should go for an

    alternative.

    RequetRedirection by using sendRedirect ()

    In this approach to perform Request Redirection we will use the fallowing method

    from HttpServletResponse Object.

    public void sendRedirect (String url);

    res.sendRedirect (http://localhost:8080/vodaphoneapp/welcome.html);

    Web Component Communication:

    The process of providing communication between web resources available at servermachine is called as Web Component Communication.

    Web Component Communication could be existed in between servlet to servlet,

    servlet to Jsp, Jsp to Jsp, servlet to html, jsp to servlet, Jsp to Html.

    As part of the Web Applications we are able to provide the Web Component

    Communication in the fallowing two ways.

    1) include mechanism

    2) forward mechanism

    To provide Web Component Communication in our web applications we should use

    the fallowing two steps.

    1) Get Request Dispatched Object

    2) Call either include () or forward () method.

    Request Dispatcher Object:

    Request Dispatcher is an object, which will provide very good environment to

    forward request from one web resource to another web resource or to include another webresource response to the present web resource response.

    To get the Request Dispatcher Object we will use the fallowing mechanisms.

    1) From ServletContext Object we will use the fallowing two methods.

    i) getRequestDispatcher ();

    ii) getNamedDispatcher ();

    2) From ServletRequest Object we will use the fallowing method.

    i) getRequestDispatcher ();

    16) What is the difference between getRequestDispatcher ()and getNamedDispatcher () from ServletContext Object?

    Servlets [email protected] 34

    http://localhost:8080/vodaphoneapp/welcome.htmlhttp://localhost:8080/vodaphoneapp/welcome.html
  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    35/39

    Comspark Info India Pvt Ltd. CSREDDY

    To get the Request Dispatcher Object we will use getRequestDispatcher () thenwe must pass the locator of the target resource as a parameter.

    In case of Servlets Locator is a URL pattern.

    public RequestDispatcher getRequestDispatcher (String target);

    To get the Request Dispatcher Object we will use getNamedDispatcher () then wemust pass Logical Name of the target resource.

    In case of servlets logical name is a name specified along with servlet name tag inweb.xml file.

    public RequestDispatcher getNamedDispatcher (String target);

    17)What is the difference between getRequestDispatcher () from ServletRequestObject and from ServletContext Object?

    To get the Request Dispatcher Object we will use getRequestDispatcher ()from ServletContext Object then we must pass only Relative path of the target resource.

    To get the Request Dispatcher Object we will use getRequestDispatcher ()from ServletRequest Object we must pass either Relative path or absolute path of the

    target resource.

    Note: The difference between Relative path and Absolute path is (/) forward slash i.e.Relative path should prefix with (/) and absolute path should not.

    2) After getting RequestDispatcher Object reference we should use either of the

    fallowing methods to perform Web Component Communication.

    public void include (ServletRequest req, ServletResponse res);

    public void forward (ServletRequest req, ServletResponse res);

    18) What is the difference between include () and forward () mechanisms?

    In case of the include mechanism when we send a request to the first resource,where container will execute some part of the first resource and generate some response on

    to the response object, when container encounter include () then container will bypass theflow of control to the target resource along with the same request and response objects

    without Refreshing the response object.

    By executing the target resource some more response to be added to the response

    object, at the end of the target resource container will dispatch the same request andresponse objects to the first resource along with the flow of control without dispatching

    response to the client machine. At the end of the first resource container will dispatch the

    final response to the client machine. Therefore incase of include mechanism client able toreceive all the resources responses which are included in the request processing.

    In case of the forward mechanism when we send a request to the first resource

    container will execute some part of first resource and generate response to the responseobject, when container encounter forward method then container will dispatch the same

    request and response object to the target resource along with the flow of control byrefreshing the response object i.e. by eliminating the previous response at

    response object.

    Servlets [email protected] 35

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    36/39

    Comspark Info India Pvt Ltd. CSREDDY

    By executing the target resource some response to be added to the response object,at the end of the target resource container will dispatch the response to the client machine

    directly without return to the first resource. Therefore incase of forward mechanism clientable to receive only the target resource response which was included in the request

    processing.

    19) What is meant by Servlet Chaining?

    The process of including many numbers of servlets to process a single request eitherby using include mechanism or by using forward mechanism.

    20) What is the difference between forward mechanism and sendRedirect ()mechanism?

    Forward mechanism can be used to provide the communication between two web

    resources which are available at the same server but sendRedirect() mechanism can beused to provide the communication between two web resources which are available at the

    same server or at different servers.

    web.xml:

    l

    logo

    l

    /logo

    h

    home

    h

    /home

    home.java

    import javax.servlet.*;

    import javax.servlet.http.*;

    import java.io.*;

    public class home extends HttpServlet

    { public void doGet(HttpServletRequest req,HttpServletResponse res)throwsServletException,IOException

    {

    res.setContentType("text/html");

    PrintWriter out=res.getWriter();

    ServletConfig config=getServletConfig();

    ServletContext context=config.getServletContext();

    RequestDispatcher rd=context.getRequestDispatcher("/logo");

    rd.include(req,res);

    Servlets [email protected] 36

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    37/39

    Comspark Info India Pvt Ltd. CSREDDY

    out.println("");

    out.println("");

    out.println("");

    out.println("Challa Software Solutions");

    out.println("To get the details of this test click the bellow link");

    out.println("
    MockTest Details");

    out.println("The First Prize for the topper is 5000");

    out.println("");

    rd=context.getRequestDispatcher("/footer.html");

    rd.include(req,res);

    }

    }

    logo.java

    import javax.servlet.*;

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

    import java.util.*;

    public class logo extends HttpServlet

    { public void doGet(HttpServletRequest req,HttpServletResponse res)throws

    ServletException,IOException

    { res.setContentType("text/html");

    PrintWriter out=res.getWriter();

    out.println(new Date());

    out.println("

    Challa Software Solutions



    ");

    }

    }

    mocktestdetails.html:

    Challa Software Solutions

    Test Details


    Test type:SCJP


    Qualification: Any Graduation


    Requirements: Java Knowledge


    Entry Fee: Rs 100/-

    Servlets [email protected] 37

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    38/39

    Comspark Info India Pvt Ltd. CSREDDY

    Address

    Block -203,204


    Cellar
    Taj Banjara
    Banjara Hills


    [email protected]

    Footer.html:



    [email protected]

    Welcome Files:

    Welcome file is a file which could be open for us when we specify up to applicationname in URL, specified at the client browser.

    To specify a file as a welcome file we should use the fallowing tags in web.xml file.

    file1

    file2

    ---

    ---

    From the above tags representation it is possible to specify more than one welcome

    file configuration in web.xml file.

    From the web.xml file which welcome file could be executed is depending on the

    module name which we specified in user URL at client machine.

    Container will search for the respective welcome file in the respective module until it

    encounter the respective welcome file as per the welcome files order specified in web.xmlfile.

    Servlets [email protected] 38

  • 8/7/2019 Servlets by Srinivasa Reddy Challa (Corporate Java Trainer)

    39/39

    Comspark Info India Pvt Ltd. CSREDDY