Interview question of Servlets


1) What is servlet?

Ans: Servlets are modules that extend request/response-oriented  servers, such as java-enabled web servers. For example, a servlet might be responsible for taking data in an HTML order-entry form and applying the business logic used to update a company’s order database.

2) What are the classes and  interfaces for servlets?

Ans: There are two packages in servlets and they are javax.servlet and javax.servlet.http.

Javax.servlet contains:

Interfaces                       Classes

Servlet                           Generic Servlet

ServletRequest               ServletInputStream

ServletResponse            ServletOutputStream

ServletConfig                 ServletException

ServletContext               UnavailableException

SingleThreadModel

Javax.servlet.http contains:

Interfaces                                          Classes

HttpServletRequest                            Cookie

HttpServletResponse                         HttpServlet

HttpSession                                       HttpSessionBindingEvent

HttpSessionContext                           HttpUtils

HttpSeesionBindingListener

3) What is the difference between an applet and a servlet?

Ans:     a) Servlets are to servers what applets are to browsers.

b) Applets must have graphical user interfaces whereas servlets have no graphical user interfaces.

4)what is the lifecycle of a servlet.

Ans: Each Servlet has the same life cycle:

a)A server loads and initializes the servlet by init () method.

b)The servlet handles zero / more client’s requests through service()              method.

c)The server removes the servlet through destroy() method.

5) What is the ServletConfig() and why are using ServletConfig ?

Ans: This interface is implemented by services in order to pass

configuration information to a  servlet when it is first loaded.Aservice writer implementing this  interface must write methods

for the servlet to use to get its initialization parameters and the context in which it is running.public interface ServletConfig

6) What is meant by the ServletContext() and use of the method ?

Ans:  The ServletContext interface gives servlets access to information about their environment ,and allows them to log significant events. Servlet writers decide  what data to log. The interface is implemented by services, and used by servlets. Different virtual hosts should have different servlet contexts.

public interface ServletContext

7) What is use of parseQueryString ?

Ans: Parses a query string and builds a hashtable of key-value pairs, where the values are arrays of strings. The query string should have the form of a string packaged by the GET or POST method. (For example, it should have its key-value pairs delimited by ampersands (&) and its  keys separated from its values by equal signs (=).)

Note:

public static Hashtable parseQueryString(String s)

8)what are the types of servlets.

Ans: Genereic Servlets,HttpServlets.

9)what are the different methods in HttpServlet.

Ans: doGet(),doPost(),doHead,doDelete(),deTrace()

10)What is the difference between GET and POST.

Ans: a) doGet() method is used to get information, while doPost( ) method  is used for posting information.

b) doGet() requests can’t send large amount of information and is limited to 240-255 characters. However,doPost( )requests passes all of its data, of unlimited length.

c) A doGet( ) request is appended to the request URL in a query string and this allows the exchange is visible to the client, whereas a doPost() request passes directly over the socket connection as part  of its  HTTP request body and the exchange are invisible to the  client.

11) Why do you need both GET and POST method implementations in Servlet?

Ans: A single servlet can be called from differenr HTML pages,so Different method calls can be possible.

12)When init() and Distroy() will be called.

Ans: init() is called whenever the servlet is loaded for the first time into the webserver.destroy() will be called whenever the servlet is removed from the webserver.

13) Who is loading the init() method of servlet?

Ans: Web server

14)If you want to modify the servlet,will the Webserver need to be ShutDown.

Ans:No

15)What is the advantage of Servlets over other serverside technologies.

Ans: PlatForm independent, so once compiled can be used in any webserver.For different processes different threads will execute in-built mutithreaded.

16) What is Server-Side Includes (SSI)?

Ans: Server-Side Includes allows embedding servlets within HTML pages using   a special servlet tag. In many servlets that support servlets, a page  can be processed by the server to include output from servlets at  certain points inside the HTML page. This is accomplished using a  special internal SSINCLUDE, which processes the servlet tags.SSINCLUDE

servlet will be invoked whenever a file with an. shtml extension is  requested.So HTML files that include  server-side includes must be   stored with an .shtml extension.

17)What is Single Threaded Model in Servlets and how is it useful give one practical example.

Ans: For every single user a differnt copy of this servlet is executed.        For  Ex: To do Credit card transactions.

18) What is the uses Sessions ?

Ans: Its a part of the SessionTracking and it is for mainting the client  state at server side.

****19)What are the advantage  of using Sessions over Cookies and URLReWriting?

Ans: Sessions are more secure and fast becasue they are stored at serverside. But Sessions has to be used combindly with Cookies or URLReWriting for mainting the client id that is sessionid at client side.Cookies are stored  at client side so some clients may disable cookies   so we may not sure that the cookies which  we are mainting  may work  or not but in sessions cookies are disable we can maintain our   sessionid using URLReWriting .In URLReWriting we can’t maintain large data because it leads to    network traffic and access may be become slow.Where as in seesions   will not maintain the data which we have to maintain instead we will maintain only the session id.

20) What is session tracking and how do you track a user session in servlets?

Ans: Session tracking is a mechanism that servlets use to maintain state  about a series of  requests from the same user across some period of time.The methods used for session tracking are:

a) User Authentication – occurs when a web server restricts access to      some of its resources to only those clients that log in using a recognized username and password

b) Hidden form fields – fields are added to an HTML form that are not displayed in the client’s browser. When the form containing the  fields is submitted,

the fields are sent back to the server

c) URL rewriting – every URL that the user clicks on is dynamically  modified or rewritten to include extra information. The extra information can be in the form of extra path information, added  parameters or some custom, server-specific URL change.

d) Cookies – a bit of information that is sent by a web server to a browser and which can later be read back from that browser.

e) HttpSession – places a limit on the number of sessions that can        exist in memory. This limit is set in the     session.maxresidents       property

21)What is Cookies and what is the use of Cookies ?

Ans: Cookies are used to get user agents (web browsers etc) to hold small amounts of state associated with a user’s web browsing.Later that  infromation read by server

22) What are cookies and how will you use them?

Ans: Cookies are a mechanism that a servlet uses to have a client hold a   small amount of state-information associated with the user.a) Create a cookie with the Cookie constructor:

public Cookie(String name, String value)

b) A servlet can send a cookie to the client by passing a Cookie object to the addCookie() method of

HttpServletResponse:public void HttpServletResponse.addCookie(Cookie cookie)

c) A servlet retrieves cookies by calling the getCookies() method of HttpServletRequest:public Cookie[ ] HttpServletRequest.getCookie( ).

23) How many Cookies is supported to the host ?

Ans: User agents excepted to support twenty per host.And its take fourKilobytes each.

24) What is the use of setComment and getComment methods in Cookies ?

Ans:

setComment: If a user agent (web browser) presents this cookie to a user, the cookie’s purpose will be described using this comment. This  is not supported by version zero cookies.

public void setComment(String use)

{

}

getComment:  Returns the comment describing the purpose of this cookie, or null if no such comment has been defined.

25)Why we are used setMaxAge() and getMaxAge() in Cookies ?

Ans:  setMaxAge

public void setMaxAge(int expiry)

Sets the maximum age of the cookie.The cookie will expire after that many seconds have passed.Negative values indicate the default behaviour:the cookie is not stored persistently, and will be deleted when the user agent exits.A zero value causes the cookie to be deleted

getMaxAge():

public int getMaxAge()

Returns the maximum specified age of the cookie. If none was specified, a negative value is returned, indicating the default behaviour described with setMaxAge.

26)What is the use of setSecure() and getSecure() in Cookies ?

Ans: setSecure

Indicates to the user agent that the cookie should only be sent using a secure protocol (https). This should only be set when the cookie’s originating server used a secure protocol to set the cookie’s value.

public void setSecure(boolean flag)

getSecure:

Returns the value of the ‘secure’ flag.

public boolean getSecure()

27)What is meant by Httpsession and what is the use of sessions ?

Ans: The HttpSession interface is implemented by services to provide an

association between an HTTP client and HTTP server. This session,

persists over multiple connections and/or requests during a given time

period. Sessions are used to maintain state and user identity across

multiple page requests.

HttpSession session = req.getSession(true);

28) What are the methods in HttpSession and use of those methods?

Ans:

a)         getCreationTime()

Returns the time at which this session representation was created.

b)         getId()

Returns the identifier assigned to this session.

c)         getLastAccessedTime()

Returns the last time the client sent a request carrying the    identifier assigned to the session.

d)         getSessionContext()

Returns the context in which this session is bound.

e)   getValue(String)

Returns the object bound to the given name in the session’s

application layer data.

f)                       getValueNames()

Returns an array of the names of all the application layer data

objects bound into the session.

g)         invalidate()

Causes this representation of the session to be invalidated and   removed from its context.

h)         isNew()

A session is considered to be “new” if it has been created by the server, but the client has not yet acknowledged joining the session.

j)          putValue(String, Object)

Binds the specified object into the session’s application layer data   with the given name.

k)         removeValue(String)

Removes the object bound to the given name in the session’s application layer data.

29) How do you communicate between the servlets.

Ans: a)servlet chaning

b)Servlet context(RequestDespatcher interface)

30)Can you send the mail from a servlet ,if yes tell how?

Ans:yes.using mail API

31)How do you access variables across the sessions.

Ans:Through ServletContext.

32)where the session data will store?

ans: session objects

33)What is Servlet Context?

Ans:This object represents resources shared by a group of servlets like

servlet’s environment,Application attributes shared in the context

level.

34)How do you trap the debug the errors in servlets.

Ans:error log file

35)How do you debug the Servlet?

Ans:through servlet log();

36)How do u implement threads in servlet?

Ans:Intenally implemented

37)How do you handle DataBase access and in which method of the servlet do you like to create connection.

Ans:init()

38)If you want to improve the performance how do you create connections for multiple users?

A.Connection Pooling.

39)what is connection pooling?

Ans:Class which manages no of user requests for connections to improve the

performance.

40) What are the different servers available for developing and deploying Servlets?

Ans:                    a)    JRun2.0–Allaire

b)    Apache—jserv

c)    jwsdk2.0 –sun

d)    servletexec

e)    Tomcat webserver—tomcat

f)     Weblogic AS—BEA Systems

g)    NetDynamics5.0–sun

h)    Iplanet—sun&netscape

i)     Netscape—netscape

g)    IBM websphere—IBM

h)    oracle—oracle

i)     Proton-Pramati technologies

41) Is it possible to communicate from an applet to servlet and how many ways and how?

Ans: Yes, there are three ways to communicate from an applet to servlet and

they are:

a)                 HTTP Communication(Text-based and object-based)

b)                 Socket Communication

c)                 RMI Communication

(You can say, by using URL object open the connection to server

and get the InputStream from URLConnection  object).

Steps involved for applet-servlet communication:

step: 1               Get the server URL.

URL url = new URL();

step: 2               Connect to the host

URLConnection Con = url.openConnection();

step: 3               Initialize the connection

Con.setUseCatches(false):

Con.setDoOutput(true);

Con.setDoInput(true);

step: 4               Data will be written to a byte array buffer so that we can tell the server the length of the data.

ByteArrayOutputStream byteout  = new ByteArrayOutputStream();

step: 5               Create the OutputStream to be used to write the data to the                 buffer.

DataOutputStream out = new DataOutputStream(byteout);

42) Why should we go for interservlet communication?

Ans: Servlets running together in the same server communicate with each

other in several ways.The three major reasons to use interservlet communication are:

a)Direct servlet manipulation – allows to gain access to the other currently loaded servlets and perform certain tasks (through the ServletContext object)

b)Servlet reuse – allows the servlet to reuse the public methods of another servlet.

c)Servlet collaboration – requires to communicate with each other by sharing specific information (through method invocation)

43) Is it possible to call servlet with parameters in the URL?

Ans: Yes. You can call a servlet with parameters in the syntax as

(?Param1 = xxx || m2 = yyy).

44) What is Servlet chaining?

Ans: Servlet chaining is a technique in which two or more servlets can  cooperate in servicing a single request.In servlet chaining, one  servlet’s output is piped to the next servlet’s input. This process continues until the last servlet is reached. Its output is then sent back to the client.

45) How do servlets handle multiple simultaneous requests?

Ans: The server has multiple threads that are available to handle requests.  When a request comes in, it is assigned to a thread, which calls a  service method (for example: doGet(), doPost( ) and service( ) ) of the servlet. For this reason, a single servlet object can have its service methods called by many threads at once.

46) How are Servlets and JSP Pages related?

Ans: JSP pages are focused around HTML (or XML) with Java codes and JSP tags inside them. When a web server that has JSP support is asked for a JSP page, it checks to see if it has already compiled the page into a servlet. Thus, JSP pages become servlets and are transformed into pure Java and then compiled, loaded into the server and executed.Servlets:

47).How do servlets handle multiple simultaneous requests?

Ans: Using Threads

48).How do I automatically reload servlets?

Ans:depends upon the server’s servlet reload properites.

48).My servlet, which ran correctly under the Servlet 2.0 APIs (Java Web Server 1.1.3) is  not running under the Servlet 2.1 APIs (Java Web Server 2.0). What’s wrong?

Ans:You might have used servlet to servlet communication by usingservletcontext methods like getServlet(),getServlets() which are  depricated and returns null from new release that is from servlet2.1 API.

49) What are the types of ServletEngines?

Standalone ServletEngine: A standalone engine is a server that includes built-in support for servlets.

Add-on ServletEngine: Its a plug-in to an existing server.It adds servlet support to a server that was not originally designed with servlets in mind.Embedded ServletEngine: it is a lightweight servlet deployment platform that can be embedded in another application.that application become true server.

****50)what is httptunneling?

ans: it is mechanism of performing both write and read operations using http protocol.it is extending the functionality of htp protocol.

51).How do I use native code in a servlet?

Ans:

49)What’s with the javax.servlet package naming?

Ans:

50. List out Differences between CGI Perl and Servlet?

Servlet                                                                                      CGI

Platform independent                                        Platform dependent.

Language dependent                                         Language independent.

Pin it

Oracle ADF interview Question Part – 1

I have created a collection of ADF interview Question .So just want to share with everyone Please give feedback.

What is Oracle Adf?

Ans :

The Oracle Application Development Framework (Oracle ADF) is an end-to-end

application framework that builds on J2EE standards and open-source technologies to

simplify and accelerate implementing service-oriented applications. If you develop

enterprise solutions that search, display, create, modify, and validate data using web,

wireless, desktop, or web services interfaces, Oracle ADF can simplify your job. Used

in tandem, Oracle JDeveloper 10g and Oracle ADF give you an environment that

covers the full development lifecycle from design to deployment, with drag-and-drop

data binding, visual UI design, and team development features built-in.

Q: Lifecycle of a Web Page Request Using Oracle ADF and JSF
Ans : Below figure  shows a sequence diagram of the lifecycle of a web page request using JSF and Oracle ADF in tandem.

Lifecycle of a Web Page Request Using JSF and Oracle ADF

Life Cycle of ADF

As shown in the figure, the basic flow of processing happens as follows:

A web request for http://yourserver/yourapp/faces/some.jsp arrives from the client to the application server

The ADFBindingFilter finds the ADF binding context in the HTTP session, and if not yet present, initializes it for the first time.

During binding context initialization, the ADFBindingFilter:

Consults the servlet context initialization parameter named CpxFileName and appends the *.cpx file extension to its value to determine the name of the binding context metadata file. By default the parameter value will be “DataBindings“, so it will look for a file named DataBindings.cpx.

Reads the binding context metadata file to discover the data control definitions, the page definition file names used to instantiate binding containers at runtime, and the page map that relates a JSP page to its page definition file.

Constructs an instance of each Data Control, and a reference to each BindingContainer. The contents of each binding container are loaded lazily the first time they are used by a page.

The ADFBindingFilter invokes the beginRequest() method on each data control participating in the request. This gives every data control a notification at the start of every request where they can perform any necessary setup.

An application module data control uses the beginRequest notification to acquire an instance of the application module from the application module pool.

The JSF Lifecycle class, which is responsible for orchestrating the standard processing phases of each request, notifies the ADFPhaseListener class during each phase of the lifecycle so that it can perform custom processing to coordinate the JSF lifecycle with the Oracle ADF Model data binding layer.

Note:The FacesServlet (in javax.faces.webapp) is configured in the web.xml file of a JSF application and is responsible for initially creating the JSF Lifecycle class (in javax.faces.lifecycle) to handle each request. However, since it is the Lifecycle class that does all the interesting work, the FacesServlet is not shown in the diagram.

The ADFPhaseListener creates an ADF PageLifecycle object to handle each request and delegates appropriate before/after phase methods to corresponding methods in the ADF PageLifecycle class as shown in  If the appropriate binding container for the page has never been used before during the user’s session, it is created.

How JSF Page Lifecycle and ADF Page Lifecycle Phases Relate

The JSF Lifecycle forwards control to the page to be rendered.

The UI components on the page access value bindings and iterator bindings in the page’s binding container and render the formatted output to appear in the browser.

The ADFBindingFilter invokes the end Request() method on each data control participating in the request. This gives every data control a notification at the end of every request where they can perform any necessary resource cleanup.

An application module data control uses the endRequest notification to release the instance of the application module back to the application module pool.

The user sees the resulting page in the browser.

Q : What is Action Listener ?

Ans : An action listener is a class that wants to be notified when a command component

fires an action event. An action listener contains an action listener method that

processes the action event object passed to it by the command component

Q:What are business Component In ADF.Describe them?

Ans: All of these features can be summarized by saying that using ADF Business

Components for your J2EE business service layer makes your life a lot easier. The key

ADF Business Components components that cooperate to provide the business service

implementation are:

■Entity Object

An entity object represents a row in a database table and simplifies modifying its

data by handling all DML operations for you. It can encapsulate business logic for

the row to ensure your business rules are consistently enforced. You associate an

entity object with others to reflect relationships in the underlying database schema

to create a layer of business domain objects to reuse in multiple applications.

■Application Module

An application module is the transactional component that UI clients use to work

with application data. It defines an up datable data model and top-level

procedures and functions (called service methods) related to a logical unit of work

related to an end-user task.

■View Object

A view object represents a SQL query and simplifies working with its results. You

use the full power of the familiar SQL language to join, project, filter, sort, and

aggregate data into exactly the “shape” required by the end-user task at hand. This

includes the ability to link a view object with others to create master/detail

hierarchies of any complexity. When end users modify data in the user interface,

your view objects collaborate with entity objects to consistently validate and save

the changes

Q: What is Top Link?

Ans:

Top Link is an Object-Relational Mapping layer that provides a map between the Java objects that

the model uses and the database that is the source of their data.

By default, a session is created named default. In the following steps, you create a new session

Q:What is Managed Bean?

Ans:JavaBean objects managed by a JSF implementation are called managed beans. A managed bean describes how a bean is created and managed. It has nothing to do with the bean’s functionality.

Managed bean is about how the bean is created and initialized. As you know, jsf uses the lazy initialization model. It means that the bean in the particular scope is created and initialized not at the moment when the scope is started, but on-demand, i.e. when the bean is first time required.

Q :What is Backing Bean?

Ans:Backing beans are JavaBeans components associated with UI components used in a page. Backing-bean management separates the definition of UI component objects from objects that perform application-specific processing and hold data.


Backing bean is about the role a particular managed bean plays. This is a role to be a server-side representation of the components located on the page. Usually, the backing beans have a request scope, but it is not a restriction.

The backing bean defines properties and handling-logics associated with the UI components used on the page. Each backing-bean property is bound to either a component instance or its value. A backing bean also defines a set of methods that perform functions for the component, such as validating the component’s data, handling events that the component fires and performing processing associated with navigation when the component activates.

What is view object?

Ans :A view object is a model object used specifically in the presentation tier. It contains the data that must display in the view layer and the logic to validate user input, handle events, and interact with the business-logic tier. The backing bean is the view object in a JSF-based application. Backing bean and view object are interchangeable terms

Q: Difference between Backing Bean and Managed Bean?

Backing Beans Managed Beans
A backing bean is any bean that is referenced by a form. A managed bean is a backing bean that has been registered with JSF (in faces-config.xml) and it automatically created (and optionally initialized) by JSF when it is needed.
The advantage of managed beans is that the JSF framework will automatically create these beans, optionally initialize them with parameters you specify in faces-config.xml,
Backing Beans should be defined only in the request scope The managed beans that are created by JSF can be stored within the request, session, or application scopes

Q? What do you mean by Bean Scope?

Bean Scope typically holds beans and other objects that need to be available in the different components of a web application.

Q.  What are the different kinds of Bean Scopes in JSF?

JSF supports three Bean Scopes. viz.,

Request Scope: The request scope is short-lived. It starts when an HTTP request is submitted and ends when the response is sent back to the client.

Session Scope: The session scope persists from the time that a session is established until session termination.

Application Scope: The application scope persists for the entire duration of the web application. This scope is shared among all the requests and sessions.

What is the difference between JSP-EL and JSF-EL?

JSP-EL JSF-EL
In JSP-EL the value expressions are delimited by ${…}. In JSf-EL the value expressions are delimited by #{…}.
The ${…} delimiter denotes the immediate evaluation of the expressions, at the time that the application server processes the page. The #{…} delimiter denotes deferred evaluation. With deferred evaluation ,the application server retains the expression and evaluates it whenever a value is needed.


Q:How to declare the page navigation (navigation rules) in faces-config.xml file in ADF 10g
?

Ans: Navigation rules tells JSF implementation which page to send back to the browser after a form has been submitted. We can declare the page navigation as follows:

<naviagation-rule>

<from-view-id>/index.jsp</from-view-id>

<navigation-case>

<from-outcome>login</from-outcome>

<to-view-id>/welcome.jsp</to-view-id>

</navigation-case>

</naviagation-rule>

This declaration states that the login action navigates to /welcome.jsp, if it occurred inside /index.jsp.

Q: Setting the range of table

Ans : <af:table rows=”#{bindings.LoggedInUserServiceRequests.rangeSize}”…/>

Q : Which component in ADF BC manages transaction ?
A : Application Module, manages transaction.

Q : Can an entity object be based on two Database Objects(tables/views) or two Webservices ?
A : No entity objects will always have one to one relationship with a database object or web service.

Q : Where is that we write business rules/validations in ADF and why?
A : We should ideally be writing validations at Entity Object level, because they provide highest degree of reuse.

Q:What are the JSF life-cycle phases?

Ans:The six phases of the JSF application lifecycle are as follows (note the event processing at each phase):

1. Restore view
2. Apply request values; process events
3. Process validations; process events
4. Update model values; process events
5. Invoke application; process events
6. Render response

Q. Explain briefly the life-cycle phases of JSF?

1. Restore View : A request comes through the FacesServlet controller. The controller examines the request and extracts the view ID, which is determined by the name of the JSP page.
2. Apply request values: The purpose of the apply request values phase is for each component to retrieve its current state. The components must first be retrieved or created from the FacesContext object, followed by their values.
3. Process validations: In this phase, each component will have its values validated against the application’s validation rules.
4. Update model values: In this phase JSF updates the actual values of the server-side model ,by updating the properties of your backing beans.
5. Invoke application: In this phase the JSF controller invokes the application to handle Form submissions.
6. Render response: In this phase JSF displays the view with all of its components in their current state.

Read more here

Q. Explain briefly the life-cycle phases of JSF?

Q: What is setActionListener?

Ans:SetActionListener – The setActionListener tag is a declarative way to allow an action source ( , , etc.) to set a value before navigation. It is perhaps most useful in conjunction with the “processScope” EL scope provided b ADF Faces, as it makes it possible to pass details from one page to another without writing any Java code. This tag can be used both with ADF Faces commands and JSF standard tags.
Exmaple of this can be as follows. Suppose we have a table “employee”.We want to fetch the salary of an employee of some particular row and want to send this salary in
Next page in process scope or request scope etc.So using this we can do this.
It have two attributes :
From – the source of the value; can be an EL expression or a constant value
To – the target for the value; must be an EL expression

1 <af:setActionListener from="#{row.salary}"
2 to="#{processScope.salary1}"/>

This setActionListener will pick value of salary of that row and store this value into salary1 variable.So anyone can use this salary
As processScope.salary1 . It is very simple to use. And very useful.

see more – part 2-

Oracle ADF interview Question part-2

Calling Servlet from Servlets in Java

I gathered information from environment and sharing you this information with all.
When Ever you want to call any servlet from another servlet We can use two ways:-

  • A servlet can make an HTTP request of another servlet. Opening a connection to a URL
  • A servlet can call another servlet’s public methods directly, if the two servlets run within the same server.

I will let you know the second way to calling the servlet. To call another servlet’s public methods directly, you must:

  • You Should know the name of servlet that you want to call.
  • Acquire access to that servlet’s Servlet object
  • Calling the servlet’s public method

To get the object of servlet, use the ServletContext object’s getServlet method. Get the ServletContext object from the ServletConfig object stored in the Servlet object. An example should make this clear. When the EmployeeDetail servlet calls the BookDB servlet, the EmployeeDetail servlet obtains the EmployeeDB servlet’s Servlet object like this:

Once you have the servlet object, you can call any of that servlet’s public methods. For example, the EmployeeDetail servlet calls the EmployeeDB servlet’s get getEmployeeDetail method:

You Should take care of the few things.If your servlet is following the singlethreadedModel interface then your call violate that single threaded model. Then you should implement the first way..

public class EmployeeDetail extends HttpServlet {

public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
...
EmployeeDBdatabase = (EmployeeDB)
getServletConfig().getServletContext().getServlet(employeedB);
EmployeeDetail bd = database.getEmployeeDetails(empId);
...
}
}