Servlet

Servlets is one of the web technology developed by SUN Microsystem. The basic aim of servlets is to develop Web Application.


Internet: Collection of autonomous computer interconnected and connected to server software which is available in particular location to getting resources that is called internet.


Browser: web browser is a software application for retrieving, presenting, and traversing information resources on the World Wide Web.


WWW:  www full form is world wide web . It means collection of information in the form of web documents we access those documents by using web browser.

Web Application: A web application is a Collection of static web resource programs and dynamic programs.


Server softwares: The basic aim of server software is to provide concurrent access. Based on the place where the programs of web applications are running by residing at Serverside, those programs are divided into two types they are

  1. Static web resource programs
  2. Dynamic web resource programs

Static web resource programs: These are those which are residing at  side and running in the context of client side browser.

The basic role of static web resource application development is to accept the data from client side/browser side. Since static web resource programs are running in the context of client/browser they are also known as client side technologies.

EX: HTML, DHTML, Javascript, vbscript, e.t.c.,

Dynamic web resource programs: These are one which are residing in the context of server and running in the context of server.

The role of dynamic web resource programs in the web application development is to validate the data which is brought from client side by static web resource programs.

EX: Servlets, JSP(java based),ASP,ASP.NET(Microsoft), CGI(Open community).

Since dynamic web resource programs are running in the context of server, they are also known as server side technologies.


Need of web application development: With the concept of J2SE we are able to develop the following applications and unable to develop some other applications also.

  1. JSE allows us to develop standalone applications and unable to develop distributed applications.
  2. With JSE we are able to develop only intranet applications but unable to develop internet applications.
  3. With JSE we are able to get one to one/half duplex/walky-talky applications but unable to develop one to many/ full-duplex applications.
  4. We are able to develop only two tier applications(Client program, Serverside program) but unable to develop 3 tier applications(Client ,server side programs and Database software) hence the above limitations makes us to go for another application development called web application/distributed application by making use of Serverside technologies.
  5. All JSE applications runs in the context of local disk and provides local access and they are unable to run in the context of browser/server/www and unable to provide global access.
  6. JSE applications are not getting explicit support from universal protocols such as HTTP, FTP etc.,
  7. JSE applications are not getting any predefined support from third party server softwares such as Tomcat(Apache Jakartha software Foundation), weblogic(BEA), Websphere(IBM) e.t.c.,
  8. All JSE applications provides language dependency. That is a part of network programming of JSE, both client and server side programs written language Java. But we are unable to develop language independent applications(Client side programs can be written in any language and server side program can be always return in Java) with JSE(including JDBC).

Technologies required for web application/distributed application:

  1. List of Browser software’s
  2. List of server software’s
  3. List of web technologies
  4. List of Database software’s
  1. List of Browser software’s: The following table gives browser software name and whose name corresponding vendor name.

 

   Browsers Vendors
1.      Internet Explorer

2.      Netscape Navigator

3.      Firefox

4.      Google Chrome

5.      Opera

6.      Hotjava

 

Microsoft

Netscape

Mozilla

Google

Opera soft

Redhat

 


  1. List of server softwares:
Webservers Vendors
1.      Tomcat

2.      JWS(Java webserver(outdated))

3.      Weblogic(both web, application server)

4.      Jetty

5.      Resion

6.      Personal web server(non Java)

7.      IIS(internet information server) (non Java)

Apache Jakartha software Foundation

SUN Microsystem

BEA(Oracle)

 

Adobe

Resion soft

Microsoft

Microsoft

 


Application Servers Vendors
1.      Weblogic

2.      Web sphere(Purely application server)

3.      Oracle Application Server

4.      Glass Fish

5.      JBOSS

6.      JRUN

BEA(Oracle)

IBM

 

Oralce

SUN Microsystem

Apache Jakartha Software Foundation

Macromedia

 


Conclusion: The functionalities of application servers are more than the functionalities of webserver. Every application server can act as a webserver but a webserver can’t act as Application server.

  • List of web technologies: Based on the web application development, web technologies classified into two types those are
  1. List of clientside/static web resources technologies
  2. List of Serverside dynamic web resource

  1. List of clientside/static web resources technologies:
Client side technology name Client side technology vendor name.
HTML

Javascript

VB Script

AJAX(Asynchronous Java script and XML processing)

W3C (World wide web consortium)

Netscape

Microsoft

Adaptive Path

 

  1. List of Server side dynamic web resources
Server side technology name Vendor
1.      CGI(Common Gateway interface)

(non java)

2.      Serverside Java script(non Java)

3.      Cold Fusion(non Java)

4.      PHP(Personal home page and hypertext pre processing)(non Java)

5.      ASP, ASP.NET(non Java)

6.      Servlets, JSP(java)

Open Community

 

Netscape

Adobe

Apache

 

Microsoft

SUN Microsystem

 

  1. List of Database softwares
Database Vendor
1.      Oracle

2.      SQL Server

3.      MySql

4.      Sybase

5.      DB2

Oracle Corporation

Microsoft

SUN Microsystem

Redhat

IBM

 


CGI: CGI is one of the specification released by open community for the development of web applications.

  1. CGI is not a language but it is one of the technology/specification
  2. We know that a specification is nothing but set of rules and guidelines developed by vendors for making the developers to develop web applications
  3. In earlier days for development of web applications we have first specification called CGI and it was implemented by various developers by making use of the language like C, Perl, C++, Shell script, VB etc.,
  4. In those days CGI based web applications are not become that much popular because it is having various limitations because of their implementation languages.

Limitations:

  1. CGI based web applications possesses platform dependency because whose implementation language is C.
  2. CGI is one of the Process based server side technology that is in the internet if any user makes a request to the CGI based web application then the server loads(swapping) the CGI application in the server memory and creates a process, process the client request and gives response back to the client. Once response is completed CGI based application swapped out from memory this process is applicable for all the internet users whoever makes a request to the CGI based web application.
  3. All the CGI based web applications are treated as heavy weight components. Because creation of process will take more amount of time and results in poor communication.
  4. In process based applications Context switch is more because switching the control one process to another process is taking more time.
  5. All CGI based web applications are by default Because whose implementation languages are not providing inbuilt security. Hence unsecured web applications leads to unauthorized modification.
  6. CGI based applications possesses low performance because in bottle neck time in the internet many number of users are accessing the CGI based web application then the server memory contains many number of processes created for the same CGI based web application.
  7. CGI based web applications are not scalable(Scalability=fast in communication+higher performance+ Consistent result)
  8. All CGI based web applications are non portable because CGI based web applications to be configurable separately as and when Operating system is changing, server is changing and process architecture is change.
  9. All CGI based web applications are inefficient compare to servlets to eliminate all the above drawbacks of CGI based web applications we need to use an another Serverside technology called Servlets.

Servlets: The basic aim of servlets is to develop web applications.

  1. Servlets is one of the dynamic web technologies developed by SUN Microsystem.
  2. Since servlets comes under technology SUN Microsystem has released specification for servlets which makes us to understand how to develop the strong web applications,
  3. We know that specification is nothing but set of rules and guidelines and they will be given in the form of purely abstract methods which are present in That is all the interfaces related servlets specification developed by SUNMicrosystem.
  4. Servlets are meant for development of web applications and they are running in the context of server, all the server vendors are come forward and developed implementation for the interfaces and given in the form of classes are developed by server vendors.
  5. Hence servlets API is a collection of packages which are classes, interfaces and sub packages. All these interfaces are developed by SUN Microsystem and whose corresponding classes are developed by server vendors.
  6. In order to deal with servlet programming we must import the following two packages
  7. servlet.*
  8. servlet.http.*

The above packages are come along with the server software in the form of jar file but not coming along with JDK software. For example in Tomcat server the above packages are available in the form of servlet api.jar and it presents in C:\Tomcat5.5\common-lib folder.

  1. Similarly in weblogic server software the servlet api available in the form of jar and it present C:\BEA\weblogic 9.0\server\lib folder etc.,
  2. Hence to compile any servlet program it is mandatory to the servlet developer to set the class path for any of the above jar files.

EX: set classpath=C:\tomcat5.5\common\lib\servlet-api.jar;.;

(Or)

set classpath=C:\BEA\weblogic9.0\server\lib\weblogic.jar;.;

Servlet: A servlet is one of the Serverside, dynamic, platform independent multi threaded Java program which is running in the context of server by extending the functionality of either web server or application server.

(or)

Single instance multiple thread technology is known as servlet.


Advantages of Servlets over CGI: When we use servlets for the development of web applications instead of CGI we get following advantages.

  1. Platform independent
  2. Thread based server side technology
  3. Light weight component because threads are use for establishing the communication between internet user and server based web application
  4. Secured
  5. Higher performance is achieved.
  6. Scalable components.

Servlet hierarchy chart: The following hierarchy chart gives number of approaches to develop servlet based web applications.servlethierarchy

The above hierarchy chart makes us to understand the flow of methods inherited from top most base interface to intermediate base classes and from intermediate base classes to bottom most user defined derived classes.

  • servlet.Servlet: Servlet is one of the predefined interface which is available on the top of hierarchy of all the interfaces in servlet programming. This interface contains the following five methods.
  1. public abstract void init(ServletConfig)
  2. public abstract void service(ServletRequest, ServletResponse)
  • public abstract void destroy()
  1. public ServletConfig get ServletConfig()
  2. public String getServletInfo()
  • servlet.GenericServlet: GenericServlet is one of the predefined abstract class which is used for developing protocol independent servlets. This class is one of the universal base class for all type of servlets which are coming in the near future depends on type of protocols. Servlet is implementing Servlet interface and defined all the methods except service(-,-) so that the current GenericServlet class made as abstract.
  • servlet.http.HttpServlet: Here http is one of the sub package of servlet package this package(http) is compatible with http protocol which is currently used in internet world. HttpServlet is one of the predefined abstract class which is used in real industry for the development of protocol dependent servlets. Industry is highly recommended to write protocol dependent servlets only but not protocol independent servlets because the current internet world is using http protocol. Programatically HttpServlet is extending GenericServlet and defined all the methods of GenericServlet with null body methods.
  • MyServlet: It is one of the user defined class which will extend either javax.servlet.GenericServlet or javax.servlet.http.HttpServlet.

Life cycle or loop back methods: Life cycle methods are those which are automatically executed by either web server or application server.

Since servlets are running in the context of web server or application server, the concept of servlets contains life cycle/loop back methods. Servlets contain three life cycle methods they are

  1. public abstract void init(ServletConfig)
  2. public abstract void service(Servlet Rquest, ServletResponse)
  • public abstract void destroy()
  1. public abstract void init(ServletConfig):
  2. It is one of the abstract method present in Servlet interface and defined in GenericServlet and further inherited into HttpServlet. This method called by the server only once whenever we make very first request to the Servlet based web application. Since this method is calling only once as a servlet developer we always write one time operations such as opening the files in read or write mode, obtaining the Database connection, initialization of parameters etc., in general in init(-) we always write the block of statements which illustrate or performs resources gathering logic.
  3. public abstract void service(Servlet Rquest, ServletResponse):
  4. It is one of the predefined abstract method available in Servlet interface and it is un defined in GenericServlet further inherited into HttpServlet and it is defined with null body.
  5. After execution of init(-) at the time of making first request, service(-) will be called by the Container of server.
  6. From second request to further sub sequent requests container will call only service(-,-) will be called by the container each and every time as and when we make a request.
  7. Sine this method is calling catch every time, as a Servlet developer we need to write the block of statements which will perform repeated operations such as reading records from file, reading the records from Database, modification of initiated parameters etc.,
  8. In general service(-,-) contains the block of statements which will provide Request processing logic or business logic. When the container creates one Thread and it will be live until response back to the client. That is in the beginning of service(-,-) execution Thead creation will be taken place and after the completion of service(-,-).
  9. The Thread will be destroyed. When the Server control comes to service(-,-) it automatically creates the object of ServletRequest and ServletResponse.

ServletRequest: It is one of the predefined interface present in javax.servlet.* package. An object of ServletRequest is always used for holding or capturing or gathering ClientRequest data.

      An object of ServletRequest is nothing but an object of its sub class which is developed by server vendors.


ServletResponse: It is one of the predefined interface present in javax.servlet.* package this interface object is used for placing the request of Request processing and gives that ServletResponse object data to the client. In other words the output of the servlet which will not give as response to the client. It will be placed into an Object of ServletResponse. The objects of ServletRequest and ServletResponse scope is only with in the service(-,-) and we can’t refer these objects in other life cycle methods like init(-) and destroy() hence it is highly recommended to the server side programmer override the service() by writing the Request processing logic.


Public abstract void destroy():

  1. It is one of the predefined abstract method present in Servlet interface and defined in GenericServlet and further inherited into HttpServlet.
  2. This method will be called by the container/server provided the servlet/web application related to servlet removed from context of server. We are no longer to execute in the context of server as part of destroy().
  3. We write the operations like JDBC stream objects and FileStream objects termination etc., in general destroy() always contains the block of statements which are performing Resource Relinquishing logic.

Phases of Servlet: when we are executing and servlet based application in the context of server, a servlet will undergo the following phases.

  1. Loading Phase
  2. Instantiation Phase
  • Initialization Phase
  1. Servicing/Request Processing Phase.
  2. Destroying Phase
  3. Un available Phase
  4. Loading Phase: Whenever we make a first request to a servlet, the container loads our servlet class(MyServlet) in the server memory. This phase will be done only once at the time of making first request.
  5. Instantiation Phase: Instantiation phase is nothing but creating an object of our servlet class(MyServlet) which is loaded in the server memory in phase-I by using default constructor(Ex: MyServlet mo=new Servlet)

Note: It is highly recommended to the Servlet programmer not write any parameterized constructors in the servlet program.

Conclusion: Instantiation phase will be performed by container only once when we make first request.

Note: Once intiation phase is completed, an object of our servlet(MyServlet) obtains Servletness.

  • Initialization: Performing initialization phase is nothing but executing init(-) this always only once by the container when we make first request.
  1. Servicing/Request processing phase: Performing this phase is nothing but executing service(-,-) this phase will be performed by the container each and every time as and when client makes a request.
  2. Destruction: This phase will be performed by the container when the servlet is removed from the context of web server or application server. Which is nothing but execution of destroy().
  3. Unavailability: The mechanism of making a request to that servlet which was removed from the context of server is known as un availability phase. When un available phase is performing we get a predefined exception called javax.servlet.unavailbaleException.

Deployment Descriptor or web application configuration file:

  1. Deployment Descriptor is one of the xml document.
  2. The purpose of deployment descriptor is to describe or to express the static web resource programs and dynamic web resource programs which are present in web application.
  3. The need of writing deployment descriptor is to hide the technology used in web application development.
  4. The name of the Deployment descriptor is always saved on a filename with an extension .xml which is one of the fixed name and whose name can’t be change in the context of servlets and JSP.
  5. The aim of deployment descriptor is to provide enough security to the web applications from internet users.

 Structure of DD:

In the above Deployment Descriptor structure

  1. <servlet>——</servlet> this tag always contains logical name of the servlet(Deployer url) and fully qualified name of servlet(Private url)
  2. <servlet-mapping> —————-</servlet-mapping> this tag contains logical name of the servlet and user friendly name of the servlet(Public url) this tag which is stand by server for containing user friendly name of the servlet.
  3. <url-pattern>————-</url-pattern> this tag always contains user friendly name of the servlet for easy accessing purpose for the internet users.
  4. <servlet-name> This tag contains logical name of the servlet/alias name or alternative name to the actual servlet. This is used for mapping user friendly name of the servlet to fully qualified name of the servlet.
  5. <servlet-class> this tag contains fully qualified name of the servlet.

 


Http Servlet: HttpServlet is one of the sub class of GenericServlet so that all the methods of GenericServlet are inherited into HttpServlet.

  1. HttpServlet developed by server with the specification of servlet api and http protocol.
  2. All the methods of http protocol are implemented in HttpServlet class and whose general notation is protected void doXxx(HttpServletRequest, HttpServletResponse) throws ServletException,IOException
  3. Here Xxx represents any http method. If our class extends GenericServlet then such servlet is known as GenericServlet and they are protocol independent and in practical world are not recommended. If our class extends HttpServlet then such servlet is known as HttpServlets and they are protocol dependent and recommended to develop in particular world.

Methods in HttpServlet:

  1. Public void service(ServletRequest, ServletResponse) throws ServletException, IOException
  2. Protected void service(HttpServletRequest, HttpServletResponse) throws ServletException, IOException
  3. Protected void doXxx(HttpServletRequest, HttpServletResponse) throws ServletException, IOException

 

  1. Public void service(ServletRequest, ServletResponse) throws ServletException, IOException: This method is one of the predefined method in HttpServlet class by inheriting GenericServlet. This method is meant for writing request processing logic by making use of protocol independent requests and protocol independent responses.
  2. Protected void service(HttpServletRequest, HttpServletResponse) throws ServletException, IOException: This method is used for writing request processing logic by handling protocol dependent requests and protocol dependent responses.

Method 1 is overridden in such a way that method 2 to be called automatically and casting ServletRequest(Protocol independent) into ServletRequest(Protocol dependent) and also casted ServletResponse into HttpServletResponse. Programatically HttpServletRequest and HttpServletResponse are the sub interfaces of ServletRequest and ServletResponse interfaces respectively. Method 2 is further overridden to call appropriate doXxx(-,-) depends on type of http method used by the client.

  1. Protected void doXxx(HttpServletRequest, HttpServletResponse) throws ServletException, IOException: This method represents in seven forms by taking http methods but as a servlet developer always writing request processing logic.

NOTE: doGet(-,-), doPost(-,-) are recommended methods.

  1. Client makes a first request to the web application.
  2. User request goes to the physical machine depends on type of DNSIP address.
  3. Physical machine locates type of server in which web application is deployed depends on its port number and handover user request.
  4. The server identifies the web application name(Staging directory)
  5. The container looks for xml and scanned container works for <url-pattern> —-</url-pattern> of web.xml
  6. If user requested url pattern is not matching with <url-pattern> values of web.xml then container gives 404 errror as a response to the client(Response not exists). If it is making then further steps will be continued by the container.
  7. <servlet-name> of <servlet-mapping> is matching is converting <url-pattern> into actual servlet.
  8. Container takes fully qualified name of the servlet and go to classes folder and loads the .class file. <servlet> in the server memory only once. After loading process instantation and initialization phases will be performed.
  9. The container will call public service(-,-) it interns calls protected service(-,-) and it interns calls either doGET(-,-) doPOST(-,-) and executes request processing logic.
  10. Container gives result of Request processing logic to the client(browser) all the above steps will be performed when the user maks a first request if the same user makes second and further subsequent requests container will perform step no-11.

Note: In the above steps 7,8 and 9,10 are same


Difference between web servers and application servers.

Web server Application server
1.      Web servers understands only http protocol but not other protocols.

 

2.      Web servers execute or run web applications but not business applications.

3.      Web server executes servlets and JSP related applications but not EJB,JTA(Java transaction API).

4.      Web servers implements the specification of web components like Servlets, JSP but not the specification of business components like EJB, JTA e.t.c.,

5.      Web servers are not able to provide middleware services.

1.      Application servers understand http protocols and other universal protocols of both TCP and UDP.

2.      Application server executes both web and business applications.

 

3.      Applciation server executes servlets, JSP, EJB, JTA, e.t.c.,

 

4.      Application server implements the specification of both web, business components.

 

 

5.      Application servers are containing effective middleware services like connection pooling, security services, transaction services.


MIME Types: Whenever client makes a request to the servlet, the servlet gives its response back to the client most of the internet users are getting response from web applications in the form of Word format, pdf format, XML format, Excel format etc., These varieties of formats given by the servlet as a response to the client is known as MIME type in otherwords HTML type always represents the type of response given by the servlet to the client. The default MIME type in every web application is text/plain(no HTML tag or text/HTML(if HTML tags present)) programmatically one can also set the MIME types.

Application/Msword: This represents the response of the servlet to be given in the word format.

Application/pdf: This represents the response fo the servlet is in pdf format.

Text/XML: This gives XML response.

In order to set MIME type to the response object we use the following method present in http servlet response interface.

Javax.servlet.http.HttpServletResponse

Public void setContentType(String)

Here String parameter represents MIME type res.setContentType(“application/msword”);

Per servlet we must set the MIME type only once but not more than once.

Common MIME Types:

Type Meaning
1.      application/word

2.      application/octect-stream

3.      application/pdf

4.      application/postscript

5.      application/vnd.lotus-notes

6.      application/vnd.ms-excel

7.      application/vnd.ms-powerpoint

8.      application/x-gzip

9.      application/x-java-archieve

10.  application/x-java-searialized-object

11.  application/x-java-vm

12.  application/zip

13.  audio/basic

14.  audio/x-aiff

15.  audio/x-wav

16.  image/gif

17.  image/jpeg

18.  image/png

19.  image/tiff

20.  image/x-xbitmap

21.  text/css

22.  text/html

23.  text/plain

24.  text/xml

25.  video/mpeg

26.  video/quicktime

 

Microsoft word document

Unrecognized or binary data

Acrobat(.pdf) file

PostScript file

Lotus notes file

Excel Spreadsheet

Power Point Presentation

Gzip archive

JAR file

Serialized java object

Java bytecode(.class) file

Zip archieve

Sound file in .au or .snd format

AIFF sound file

Microsoft windows sound file

GIF image

JPEG image

PNG image

TIFF image

X windows bitmap image

HTML cascading style sheet

HTML document

Plain text

XML

MPEG video clip

QuickTime video clip

 


Retrieving the client data in the context of Servlet we know that whenever we send the client data through the HTML program to the servlet, the client data is available in the Request object of HTTPServlet Request in the form of (key, value).

  1. Keys represents HTML form parameter names and values represents HTML form parameter values/request parameter values.
  2. For the purpose of Request processing logic either as a part of doGet or doPost we need to retrieve form parameter these values we have the following approaches.
  3. public String getParameter(String)
  4. public String[] getParameterValues(String)
  • public Enumeration getParameterNames()
  1. public Map getParameterMap()

All the above methods are present in HttpServletRequest.

  1. public String getParameter(String): This method used for retrieving form parameter values when we have distinct form parameter names. The taking parameter String represents form parameter name and return type String represents form parameter value.

 

Stno: 100

Sname:Bharga

Marks:99.99

        EX:          


  1. public String[] getParameterValues(String): In the some of the HTML forms, one form field name may contain multiple values and when we submit such form data to the servlet, in the context of servlet we use the above method for retrieving multiple values by passing single form field name.


 

  • public Enumeration getParameterNames(): When client submits the form data to the servlet, the server side programmer may not be aware of form parameter names and their values. In order to find unknown form parameter names and their values we use the above method.

 

  1. public Map getParameterMap(): The functionality of the method is similar to the above method but this method returns an Object of Map interface. Map is one of interface present in java.util.* and it allows us to retrieve concurrency where as Enumeration interface object allows us to retrieve the data sequentially.

     

     In Otherwords Enumeration interface object belongs to synchronized and Map interface object belongs to non-synchronized.


ServletConfig and ServletContext:

ServletConfig: If we write any servlet in the fixed and technical information and if the servlet is decided to change the fixed details then the servlet developer has to perform the following applications.

  1. Go to the servlet, change the required fixed values and save.
  2. Compile the above servlet and ensure .class file must be generated.
  3. Copy Corresponding .class file into the classes folder and generate war file.
  4. Deploy the war file in the server.

The above cycle of operations are repeated whenever we are changing the source code of the servlet. This type of approach is known as Hard coded approach. Industry is not recommended this type of approach but it is always recommended flexible approach.

Note:

  1. In hard coded approach the values of the application participates in compilation time. Where as flexible approach is one the values participates in execution time. In order to develop flexible servlets, we use a predefined interface called ServletConfig which is present in javax.servlet.* package.
  2. Developing flexible servlet is nothing but getting the technical details /fixed details form one of the external file called web.xml(In JDBC external file is properties/resource bundle file) ServletConfig interface object is responsible for getting technical details from web.xml file. An object of ServletConfig is automatically created by container during the initialization time.
  3. An object of subclass of ServletConfig is nothing but sub class of SerlvetConfig. ServletConfig  interface object obtaining the data from web.xml file which is written in <init-param> ——</init-param> of <servlet> ———–</servlet> of web.xml file.

    Hence the <init-param> data which we have written in the above file in the DBServ is automatically available in the object of ServletConfig interface at the time of initialization phase. An object of ServletConfig contains the <init-param> data in the form of (key,value) , key represents <init-param> name and value represents <inti-param> value. Hence an object of ServletConfig exists one per servlet. ServletConfig object is available with the servlet as long as the servlet is under execution. Once servlet execution is completed automatically ServletConfig object will be removed by the container.

Retrieving the data from object of ServletConfig will be created automatically phase InitParam data of a servlet of web.xml file in the form of (key.value). It is desirable to retrieve the (key, value) related values from SerlvetConfig interface object for developing flexible servlet to retrieve(key, value) from ServletConfig interface object we use the following two methods.

  1. public String getInitParameter(String)
  2. public Enumeration getIntiParameter()

The above two methods are present in ServletConfig interface.

  1. public String getInitParameter(String): This method is used for obtaining InitParameter value by pasing InitParameter name, This method will be used by us when we know about InitParameter names.

 

2.   public Enumeration getIntiParameter(): this method is used to obtaining InitParameter names when the Java programmer has not having an idea about InitParam names. Pass the InitParam names to method1. We get InitParam values.

 


SerlvletContext: The basic aim of ServletContext is to develop flexible web application. SerlvetContext interface present in javax.servlet.* package

An object of SerlvetContext will be created automatically by the container whenever the web application is develoyed. The scope of SerlvetContext interface object exists entire web application that is object common for all the servlets  in the web application hence it is treated as global object for the servlets. An object of ServletContext contains the <context-param>—-</context-param> data of web.xml file in the form of key, value pair. The place of writing<context-param>————</context-param> in the web.xml file with in <webapp> and before all servlets. The following diagram gives the view about SerlvetContext and  SerlvletConfig.

Number of ways to create concept of ServletContext: we can create an object of ServletContext in two ways they are

  1. By calling method getServletContext.
  2. By using ServletConfig object
  1. By calling method getServletContext: getServletContext is one of the method present in GenericSerlvlet and further inherited into HttpServlet and finally available with our servlet class.

 

 

The prototy of getServlet context method is shown below

GenericServlet

Public servletContext getServletContext()

  1. By using ServletConfig object: ServletConfig interface contains the following method for creating an object of ServletContext. To create an object of ServletContext, first we need to create an object of ServletConfig and later all the following

SerlvetConfig

Public ServletContext getServletContext()

 

Number of ways to retrieve the data from ServletContext: We know that an object of ServletContext will be created during deployment time of web application whenever the ServletContext object is created, it is by default containing <context-param>—–</context-param> data of web.xml file in the form of (key, value). To retrieve context param data we use the following methods.

  1. Public String getInitParameter(String)
  2. Public Enumeration getInitParameterNames()

The above two methods are present in ServletContext

 


Q) Differences between ServletConfig and ServletContext?

ServletConfig ServletContext
1.      ServletConfig is exists one per servlet.

2.      ServletConfig object is treated as global object to particular servlet.

3.      The basic aim of SerlvetConfig is to develop a flexible servlet.

4.      An object of SerlvetConfig created by the container during initialization phase.

5.      The scope of the ServletConfig object is only per a particular servlet that is as long as servlet in under execution.

 

6.      ServletConfig object contains <init-param> data of the servlet of web.xml

7.      Before we make first request to web application ServletConfig object is not available.

8.      An object of ServletConfig can be created directly by calling the following method

public ServletConfig getServletConfig()

1.      ServletContext is exists one per web application.

2.      ServletConfig object is treated as global object to entire web application.

3.      The basic aim of SerlvetContext is to develop a flexible web application.

4.      An object of SerlvetContext created by the container during deployment.

5.      The scope of the ServletContext object is only per a entire web application  that is as long as it present in Server context.

6.      ServletContext object contains <context-param> data of the web.xml

7.      Before we make first request to the web application ServletContext object is available.

8.      An object of ServletContext can be created directly by calling the following method

public ServletContext getServletContext()

 


RequestDispatcher: It is one of a predefined interface present in javax.servlet.* package and whose object is used for establishing the communication between multiple servlets which are present in same or different web applications which are running in same server. Programatically an object RequestDispather interface is nothing but creating an object of sub class of RequestDispather interface.

Number of ways of ways to create an object of RequestDispather interface:  An object of RequestDispatcher interface can be created in three ways they are

  1. Request based RequestDispatcher
  2. Context based RequestDispatcher
  • Context based named RequestDispather

 

  1. Request based RequestDispatcher: Request based RequestDispatcher allows us to establish the communication between multiple servlets of same web application but not the communication between multiple servlets of different web applications. Programmatically to create Request based RequestDispatcher we use the following method present in HttpServletRequest.

 

 

 

Here writing ‘/’ is opetional. Here rd is known as RequestDipatcher.

  1. Context based RequestDispatcher: Context based request dispatcher is used for establishing the communication between multiple servlets of same web application or different web application. Context based request dispatcher can be obtaining by using the following method.

 ServletContext

Public RequestDispatcher.getRequestDispatcher(String)

Here String parameter represents url pattern of the destination servlet which may belongs to either same or different web application.

 

 

  • Context based named RequestDispatcher: This approach is also used for establishing the communication between multiple servlets of same and different web applications but NamedRequestDispatcher communicates with destination servlet on the basis of logical name of the servlet and approach2 communicates with destination servlet on the basis of url pattern of the servlet.

To get context based named dispatcher we use the following method

ServletConfig

Public RequestDispatcher getNamedDispatcher

Here String parameter represents logical name of the servlet.

 

 

Types of models in Request Dispatcher: While we are establishing the communication between multiple servlets of same web application or different web application through the RequestDispatcher we have two types of models they are

  1. Forward model
  2. Include model
  3. Forward model: In forward model the Request of the client taken by the source servlet, performs Request processing logic and for the rest of the Request processing logic, source servlet forward its Request and Response objects to the destination servlet. Destination servlet completes the rest of the Request processing logic and gives its result back to the client directly without giving the result of source servlet. The following diagram gives the work flow of the forward model.

Inserting, modifying and deleting Request object: We know that whenever client submits HTML form data to the servlet, the HTML form data available in the servlet in the form of an object of HTTPServletRequest.

        An object of HTTPServletRequest containing the HTML form data in the form of (key, value). In the (key,value) key represents form parameter name or Request parameter name and value represents form parameter value or Request parameter value.

In some of the circumstances of web application we my be performing the following operations on the Request object.

  1. Inserting(key, value) in the Request object
  2. Modifying value of value based on key value.
  • Removing the complete entry(key, value) from Request object. To perform the above three operations we us the following methods.
  1. Public void setAttribute(String, Object)
  2. Public void removeAttribute(String)
  3. Public Object getAttribute(String)

The above methods are present in ServletRequest interface and further inherited into HTTPServletRequest.

 

  1. Public void setAttribute(String, Object) : This method is used for performing both inserting and modifying the entries of Request object. If new form parameter name is not already in Request object then (key, value) will be taken as inserted entry if the new form parameter name already present in the Request object then the value of value will be modified based on key value. This entry is treated as modified entry.

 

 Public void removeAttribute(String): This is used for removing the entry of request object based on key.

  1. Public Object getAttribute(String): This method is used for obtaining value of value by passing key

 

In the above methods the parameter represents Request Parameter name/key. Object parameter represents value of value/Request parameter value.


what is the difference between forward(-,-) and sendRedirect(String)?

   forward(-,-) sendRedirect(Stirng)
1.      These methods will establish the communication between multiple servlets which are running in the same server and they may present in same web application or different web application.

2.      These models exchanges the data between multiple servlets in the form of Request and Response objects.

3.      In this model same references of Request objects will be maintained between multiple servlets which are running in the same server.

4.      In this model the result of destination servlet is given to the client to the source servlet url.

 

1.      These methods will establish the communication between multiple servlets  which are present in multiple web applications and running in different servers.

2.      In this model the data exchanging between servlets which are running in different servers in the form of QueryString(http://localhost:7001/s2url?a=10@b=20) à Query String

 

 

 

3.      In this model different references of Request and Response objects will be maintained across the multiple servlets running in different servers.

 

 

4.      In this model the results of the destination servlets which is running in different server is directly given to the client which its own url but not through source servlet.


Q) In How many number of ways are there to pass the data to the servlet/the Request to the servlet?

  1. A) We can make a request to the servlet in three ways they are
  2. i) Form based request
  3. ii) Query String based request
  4. Hyperlink based Request

Q) What are the different types of url patterns of a servlet?

 In our web application we can use three types of url patterns they are

  1. Exact Match
  2. Directory Match
  3. Extension Match
  1. Exact Match:

  1. Directory Match:

    Note: Exact Match will fix with the directory match

Extension Match:


Examples :


1]life cycle


2] Internal Details Of Servlet