servlet by dhananjayNaik123

VIEWS: 274 PAGES: 11

What is difference between Servelt and Applet
       servlet is the server side component and the applet is the client side component.
       applet makes the request to the servlet and servlet is the server which responed that
       Servlet doesn't have GUI , while applet have GUI.
       Applet are very heavy to handle as compared to servlet.

Do we have a constructor in servlet ? can we explictly provide a constructor in servlet
program as in java program ?
we can have a constructor in servlet class, but only default constructor. We can not have
parameterized constructor in servlet, because the servlet gets instantiated by the container
dynamically, and java does not allow to call parameterized constructor for dynamically loaded

what is the difference between Generic servlet and HTTPServlet
Generic servlet
        as part of javax.servlet a class Generic servlet is provided.this class implemens the
        servlet interface,in this class service() is declared as abstract and this class contains the
        code that is not specific to any protocol.
        generic servlet does not maintain client session.
        as part of javax.servlet.http a class HttpServlet is provideded, this class is sub class of
        GenericServlet.this class implements the servlet interface and service() is not declared as
        abstract and this class contains the code that is specific to http protocol.
        httpservlet maintains client session.

Differences between GET and POST.
        In doGet() u submit the request by appending the URL while in doPost() request is
        submitted via form.

        Since doGet() appends the link it is not safe for request containing passwords etc. while
        doPost() uses form hence it is safe.

        You can send only limited data in doGet() while unlimited data in doPost() .

        doGet() request could used like a bookmark as it uses URL ,but doPost() can't be used
        as bookmark.

        doPost() is Idempotent i.e if the user requests for some thing & later he changes his
        decision & rerequests to make some changes in previous request ,doPost() gets failed in
        that case ,while doGet() is useful in such cases.

        doPost(..) method is generally used for Insertion /updation / deletion of data , whereas
        doGet(..) is used when the users tries to request for any Read Only data.

        that is by doGet() method we becomes limted for sending parameters,bcoz each specific
        browser has a limtitation,means they can send parameters only in limtation,
        but by doPost() method we can send unlimited parameters through browser.

how to get value from init() method in servlet? Or how to get initializaion time values from
init() in servlet?
          U can use getInitParameter(java.lang.String name) method of HttpServlet class to get the
          value of named parameter or getInitParameterNames() to get the names of the servlet's
          initialization parameters as an Enumeration of string objects.
          u can declare init parameters in web.xml file
          The init() method initializes a config variable of ServletConfig object. All the initialization
          time values can be obtained from this object. It can be accessed like

What is the difference between ServletContext and ServletConfig?
        The servlet engine implements the ServletConfig interface in order to pass configuration
        information to a servlet. The server passes an object that implements the ServletConfig
        interface to the servlet's init() method.
        A ServletConfig object passes configuration information from the server to a servlet.
        ServletConfig also includes ServletContext object.
        initial parameters are stored in servletconfig
        As part of web application there will be only one ServletContext object

        The ServletContext interface provides information to servlets regarding the environment
        in which they are running. It also provides standard way for servlets to write events to a
        log file.
        ServletContext defines methods that allow a servlet to interact with the host server. This
        includes reading server-specific attributes, finding information about particular files
        located on the server, and writing to the server log files. If there are several virtual
        servers running, each one may return a different ServletContext
        servletcontext global data SevletContext
        As part of web application there can be multiple ServletConfig objects

What is the difference betweem getRequestDispatcher() available as part of ServletContext
and ServletRequest
ServletContext - getRequestDispatcher()
The pathname must begin with a "/" and is interpreted as relative to the current context root. Use
getContext to obtain a RequestDispatcher for resources in foreign contexts (applications running
on two different servers). This method returns null if the ServletContext cannot return a
ServletRequest - getRequestDispatcher()
The pathname specified may be relative, although it cannot extend outside the current servlet
context. If the path begins with a "/" it is interpreted as relative to the current context root. This
method returns null if the servlet container cannot return a RequestDispatcher.
Foreign context means another application running in the same server and not in another server.
Currently there is no way that you can retrieve the servlet context object for an application on
another server. But also note that within the same server also, if there are security restrictions,
you may not be able to get the context object for another application

how many objects are created when same or different client send 100 requests to a
if the servlet implements SingleThreadModel interface then many instances of that servlet can be
created by the Container otherwise,
         If the web application is a distributed web application then each JVM will have only one
         servlet instance no matter how many requests are there. But in all you can say that you
         have 1 or more than 1 servlet instances (present on many JVM but one servlet instance
         per JVM).

        If the webapp is not a distributed one then only one servlet instance(object) would be
        there to service all the requests. For each request you'll have a separate thread
        accessing service() method.

What is the difference between JSP and SERVLETS
        It is a web component which will handle the request as well as it will give the response in
        particular display format. i.e it will perform developers tasks and designer's tasks.
        we can't embed the components like the java beans.
        Servlets puts HTML code in java code
        it is purely for display will internally create a sevlet for performing developer’s
        In Jsp we can embedded the components such as the java beans.
        where as in JSP java code put in a HTML code

What is difference between sendRedirect() and forward()..? Which one is faster then other
and which works on server?
       response.sendRedirect takes full round trip ie goes to the browser and comes back to the
       server where as forward is server to server transfer
       response.sendRedirect makes a new request so all previous request parameters are lost
       and in order to persist the data you need to send through query string where as in
       forward the old request is forwarded so all old request data persist

We have two applications in that we have two servlets each.How they(servlets)
communicate with each other ?
      Create a singleton encapusalting the shared info, if two servlets are running in same
      JVM. but you have to be very careful about the synchronization
      Use DB to cache the shared info if there is a db in place

Can we write destroy() method in the init() method of a Servelt.if we can, what will happen?
      Ya definitely you can call destroy() from init , but in that case it will be called as any other
      method it will execute the code in destroy() and will come back to init().
      The destroy() method is called by server when the servlet is about to get unloaded.

Why GenericServlet is an abstract class
      GenericServlet class is abstract because there is a method called service() which is
      public abstract void. and service() must be overridden, service() method defines what
      type of protocol is used for request.
      according to Java specifications those classes which have abstract methods must be
      declared as abstract..

What is the difference between servlet and servlet container?
A Servlet is that portion of your J2EE application which handles ur request and where the
business logic is implemented and depending on the request a response object is generated
which is sent back to the client.
Servlet container
A Servlet container is that portion of a Web server which maps URLs to particular servlet it has
entry of each and every servlet and so whenever a request comes up it directs that to the
particular registered servlet.
A webserver contains 3 components:
         HTTP Engine
         Servlet container

      JSP container.
Webcontainer = ServletContainer + JSP container.

how can a servlet automatically update its data without refreshing?
<%response.setHeader("Refresh","amnt of time ;page to be redirected")%>

Can we override the service method? if we can do that then why do we override only
doGET() and doPost() methods if the servlet is of protocol specific?
Yes, we can override service method. But then we have to give our own implementation to
detect which type of method request is using.(i.e GET or POST). Since we mostly use HTTP as
a protocol its best to extend HTTPServlet and override doGET or doPOST accordingly.
You should NOT override the service() method.Your job is to override the doGet() and/or doPost
methods and let the service () implementation from HTTPServlet worry about calling the right

In MVC1 architecture there is no controller concept then why it is called as MVC
MVC1 was a first generation approach that used JSP pages and the JavaBeans component
architecture to implement the MVC architecture for the Web. HTTP requests are sent to a JSP
page that implements Controller logic and calls out to the “Model” for data to update the “View.”
This approach combines Controller and View functionality within a JSP page and therefore
breaks the MVC paradigm. MVC1 is appropriate for simple development and prototyping. It is not,
however, recommended for serious development.

What is the use of Service() in servlets? How is that method invoked?
The container initializes the servlet instance by calling the init .After completing the initialization it
calls the service () method passing servlet request and response objects as parameters. service
() method is designed in such a way the depending on type of the request method it calls the
either doGet() or doPost() method. There is no need to make a explicit call to doGet () or doPost()

Can I invoke a JSP error page from a servlet?
Yes, you can invoke the JSP error page and pass the exception object to it from within a servlet.
The trick is to create a request dispatcher for the JSP error page, and pass the exception object
as a javax.servlet.jsp.jspException request attribute. However, note that you can do this from only
within controller servlets.
If your servlet opens an OutputStream or PrintWriter, the JSP engine will throw the following
translation error: java.lang.IllegalStateException: Cannot forward as OutputStream or Writer has
already been obtained
The following code snippet demonstrates the invocation of a JSP error page from within a
controller servlet:
protected void sendErrorRedirect(HttpServletRequest request,
HttpServletResponse response, String errorPageURL, Throwable e) throws
ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getRequestDispatcher(errorPageURL).forward(request, response);
public void doPost(HttpServletRequest request, HttpServletResponse response)
try {
// do something
} catch (Exception ex) {
try {
} catch (Exception e) {


Consider a scenario in which 4 users are accessing a servlet instance. Among which one
user called destroy() method. What happens to the rest 3 users?
We know that by default servlet is multithreaded, for every client request a new thread will be
created and assigned to that to perform the service. so if one thread initiates destroy() only itself
will be terminated but other threads not terminates. Other wise, it is against to servlet spec.
regarding multithreading concept. ex: suppose if u open 2 browser instances for a website, if u
move from one site to another in one browser the other remains connect to same site not

can we write business methods in servlets? if yes, then how can u access that from out
side of the servlets?
Yes we can write business methods inside a servlet and these methods can be accessed only
within the same servlet and not from outside of servlet.
if you write business methods inside a servlet, client can not call because GenericServlet or HS
doesn't implements Remote interface So u can't call from remote places.

How you can activate or call one another servlet method?

To call the service method of the another servlet from other servlet
1)if both servlets are part of the same web application
Use ServletContext application=config.getServletContext();
 RequestDispatcher rd=application.getRequestDispatcher("/anotherServlet");
use rd.include(request,response);
if you want to get the output generated by service method of both the servlets
or use rd.forward(request,response);
if you want to get output of only the called servlet

2)if both the servlets are part of different application with the name app1 and app2 i.e SOne
belongs app1 & STwo belongs to app2.and running in the same container.
then to invoke the service method of STwo from the SOne
use ServletContext sone_context=config.getServletContext();
ServletContext stwo_context=sone_context.getContext();
RequestDispatcher rd=stwo_context.getRequestDispatcher("/url/of/stwo");
use rd.include(request,response);
or rd.forward(request,response);
SOne is the calling servlet and STwo is the Called Servlet

3)if both the servlets SOne and STwo are part of different applications app1 and app2 and these
app1 and app2 running in different container
in service method of sone use
response.sendRedirect("url of the server");
to invoke the service method of stwo
for e.g if SOne if running in weblogic and STwo in Tomcat
the in SOne service method use response.sendRedirect("http://localhost:8080/app2/url/of/stwo");

What is the modifier for the HttpServlet class service method?
protected void service(javax.servlet.http.HttpServletRequest httpservletrequest,
javax.servlet.http.HttpServletResponse httpservletresponse)

public abstract void service(javax.servlet.ServletRequest servletrequest,
javax.servlet.ServletResponse servletresponse)

What is the servlet life cycle?
       A server loads and initializes the servlet (init())
       The servlet handles zero or more client requests (service())
       The server removes the servlet (destroy()) (some servers do this step only when they
       shut down)

Difference between single thread and multi thread model servlet
A servlet that implements SingleThreadModel means that for every request, a single servlet
instance is created. This is not a very scalable solution as most web servers handle multitudes of
A single thread model for servlets is generally used to protect sensitive data ( bank account
operations ).
multi-threaded servlet
A multi-threaded servlet means that one servlet is capable of handling many requests which is
the way most servlets should be implemented.

what is the role of synchronization when we making a servlet as singlethreadmodel?
Making a Servlet as SingleThreadModel means u r making sure that no two or more clients can
avail the services of the servlet at the same time and synchronization is mechanism of making
sure that a resource will not be used by one or more thread at the same time. SingleThreadModel
makes sure that only one client is availing the service of the servlet.

What is servlet context and what it takes actually as parameters?
Servlet context is an object which is created as soon as the Servlet gets initialized.Servlet context
object is contained in Servlet Config. With the context object u can get access to specific
resource (like file) in the server and pass it as a URL to be displayed as a next screen with the
help of RequestDispatcher.

ServletContext app = getServletContext();
RequestDispatcher disp;
disp = app.getRequestDispatcher
disp = app.getRequestDispatcher

this code will take user to the screen depending upon the value of b.

How to communicate between two servlets?
Servlet Collaboration or Communication can be achieved either by using Request Dispatcher's
Forward or Include methods (available with request object) or Send Redirect method(available
with response object). Servlet Context is also one of the ways to acheive servlet collaboration
coz it is the one which provides the information of all the servlets.
          Forward or redirect from one Servlet to another.
          Load the Servlet from ServletContext and access methods.

what is difference between servlet container and servlet config?
Servlet container(sub set of web container) is the controller of the servlet.
It creates the servlet,initializes,call the service method and finally destroy it.
Servlet config is an object.

Difference Between Web Container and Web Server
Just Receive the request from the client and forward to Webcontainer, and do the Response vice

Web Container
      Creates HTTP Request and Response for the Servlet, calls the appropriate servlet
      service method (doGet or doPost) to service the client request.
      Communication support(socket creation), Servlet life cycle management (Init(), Service()
      and Destroy()), Multithreading support, Declarative security(thru deployment descriptor)
      and JSP support.

how to find out the servlet is demon thread
You can use the following code to determine whether the thread in which your code is getting
executed is daemon or not.

if(Thread.currentThread().isDaemon()) {
     //logic to execute if daemon.
} else {
    //logic to execute if not daemon.

Explain about Inter-Servlet communication and business reason for using Inter-Servlet
       By storing & retrieving data from shared scopes like session and application(servlet
       By using forwards & redirects.

Method 1
If you have 2 servlets. In one servlet you do some calculation and store the data in session
scope, for example bill for all the items in the user's shopping cart. Then you forward the request
to another servlet which takes care of presenting the data to the user for confirmation before
completing the order. This is just one scenario. There could be many more examples where you
would need to store data in a shared scope in one servlet and retrieve it in another servlet.

Method 2
You would use this method, for example when you have a decision making servlet which
forwards/redirects you to some other servlets depending on various conditions. For example, in
the case of a shopping cart servlet, after the user confirms the order, if the order is successfully
saved in the database, you redirect to a success page, otherwise to a failure page that shows the
appropriate status.

Where session information gets stored in methods like Cookies, URLRewriting etc.
      In cookies, Session information is stored at client side in a folder called cookie, if the
      browser is set to cookie disable mode then this approach will not work.
      In URL rewriting, it is stored within each URL & attached with header.
      Except then cookies all approaches stored session information at server side.

what is servlet tunneling? when it will be used?.
The Servlet tunneling can be thought as a way to use an existing road of communication (HTTP)
and create a sub-protocol within it to perform specific tasks.

how can a web container know whether cookies are accepted or not accepted by the
1) The only way to know for sure is to set a cookie on a response, and see if
it comes back on the following request. You have absolutely no clue from
looking just at the current request. Just as an example, I run Netscape
6, configured to warn me every time about accepting a cookie -- so you
can't even look at the User-Agent header and predict whether *I* am going
to accept your cookie or not.
2) This is exactly what the servlet container does for you for session IDs,
as long as you use URL rewriting (done with the response.encodeURL()
method) to create all of your hyperlinks. The container will send the
initial session id both ways (encoded in the URLs, and as a cookie). If
the session id comes back later as a cookie, the container recognizes this
and stops doing the rewriting -- otherwise it continues. But the only
safe thing for your application to do is *always* call encodeURL() to
generate all of your hyperlink destinations that should be part of the
same session.

How to Access Session Variables in Servlets & JSP
Use can store variables in session, but u can store it in object form only.if it is primitive type u can
use wrapper classes to convert it into object.

String str=(String)session.getAttribute("test");
while retrieving data u need to cast it back to its original type.

I can do every thing using jsp itself, then what is the need of using servlet? in which
situation ,we must use servlet with jsp?
We can’t implements interface in Jsp but it is in the servlet. Yes, it is true, we can every thing in
JSP as in the servlet. But, Jsp is always used for design layout or view whereas the servlet is
used to code the business logic.
Why is it in servlet? Because Servlet is the .java file and we simply write the java code for
controlling the business. The servlet is controlled by web container and it creates it multiple
instances automatically.

Whats the difference between using invalidate() & sessionDestroyed for sessionclosing.
session's invalidate method is used when the session will no longer exist or when for a particular
client is leaving the session
Eg:during the logout.
is a method of HttpSessionListener ,and this is called when the session is being removed.when
the session expires or is invalidated the container first removes all of the session attributes, calls
the HttpSessionListener's sessionDestroyed method and then sets the session to null so that it
can be garbage collected.

In normal javabean, bean object is serailizable,and Connection object is transient object.
Then How we using javabean for communnication between Servlet and JSP for data
bean components are the data transfer objects between Servlets and JSPs which are going to
travel and hence they have to be serialized. Connection object is just to make a physical
connection to the database specified and no need to serialize hence made transient.

what method used to add a jsp to the servlet
The RequestDispatcher.include(req, resp) is used to add a jsp to the servlet.

What is the need for having HTTPServlet class when we already have GenericServlet class
which can handle all type of requests?
Http servlet has few more methods in it and also if helps us in not using or overriding all the
methods that are listed in Generic, and just use the methods that are needed http is stateless
protocol and use for http request.

suppose in web.xml file we are given 30 and in the servlet program we are given
setSessionInActiveInterval(40).when that session will be terminated ? After 30 sec or 40
session will be terminated depending upon the later updation means it depend upon the xml file
and it will take 40 sec because after compiling it will update xml file into 40 sec

what are the necessary conditions to override the init() in servlets?
The Servlet must be already loaded into memory & instantiated.

Difference between getNamedDispatcher() & getRequestDispatcher()
        is used to get a requestDispatcher object for a servlet whose name is passed to this
        method call.
        public RequestDispatcher getNamedDispatcher(java.lang.String name)

       is used to get a requestDispatcher object for the resource indicated by the path passed to
       this method call.
       public RequestDispatcher getRequestDispatcher(java.lang.String path)

What is meant by preintialization?
when we send any request to the servlet, that request tryies to find servlet 1st. second servlet
executing following sequence of method

so the first time request to servlet, response time is high than second request
so to avoid above problem, we preintialize that servlet into web.xml so at time of booting server,
server load servlet.this is we need not execute init() method again.

What is the disadvantage of the ServerSideIncludes?
       when ur going to store http session suppose 100 those 100 objects r stored in server side
       so memory is waste and process takes much time
       They are very processor intensive. If you don't have a high-powered computer running
       your web server and you expect to have a lot of traffic, you might want to limit the number
       of documents that use Server-Side Includes.

Which part of the webserver is responsible for initialization of the servlets?
It is the servlet container that is responsible for initializing and managing the servlet life cycle.

What is the difference between mvc1 and mvc2 architecture?
architecture is the one where the controller & view logic are combined in a single unit and the
model is a separate unit. This was the case with early JSP based applications where JSP would
include the controller logic, pull the data from the model and present it to the user.
architecture is one where all these 3 pieces are separate units. The controller receives the client
requests, pulls the data from the model, stores it in some shared scope for use by the view (JSP),
then redirects to the appropriate view for presentation to the user. In general, all your JSP Pages

do is displaying data stored in shared session and/or application scopes which is populated by
some servlet, then you are following the MVC2 architecture. One of the examples for this is the
Struts framework.

Which code line must be set before any of the lines that use the PrintWriter?
Since PrintWriter creates an object which mostly used to markup the Hyper Text in order to
display output in Browser Window i.e, HTML Page. So, the Printwriter object show know the
ContentType like html or text etc., which is to be displayed,
Hence the method setContentType() Method should be called before using Printwriter Object,
inorder to display the output in the said format.

What is the purpose of hidden fields, cookies and session objects?
       The purpose of hidden fields, cookies and session objects is to transfer data between
       different pages of an application.
       I hope you know that HTTP is a stateless protocol and so are our web applications.They
       can't remember the data of client across multiple requests of an user(which is called as
       All the above three are the techniques that are used to enable session tracking in servlet
       based web app.

What is hot deployment?
       A web server is a simple JVM which has all the servlets, jsp and other server side
       components loaded in it. So in the development process if you make any change in the
       servlet or a jsp or other server side component which is already loaded in the container
       you may need to redeploy the application or restart the web server which is expensive in
       terms of time. So all the web servers are providing the hot deployment feature where in
       we can change the server side component and the container will load the new
       component automatically.
       The container will be polling a particular folder and starts deploying if any new application
       is copied into that folder. It also maintains the time stamp of the application deployed and
       redeploys it whenever it finds any change in the timestamp. This feature is called hot
       deployment. This will be helpful in the development time but has to be avoided in the
       production environment for performance issues.

how many cookies(max) can store a browser?
20 cookies for per website and 300 cookies per unique user, also they can limit each cookie's
size to 4096 bytes.

how can we refresh the servlet for every 2 minutes automatically?
response.setHeader("Refresh","300; URL=url");
the above statement will auto refresh the webpage to a new web page with url given. If you give
the url as the same page where u r calling this from, then the web page will refresh for every 5

Through Client Side : We use Meta http refresh

< META HTTP-EQUIV="Refresh" CONTENT="5; URL=/servlet/MyServlet/">

how do to prevent user by viewing secured page by clicking back button when session
You will need to set the appropriate HTTP header attributes to prevent the dynamic content
output by the JSP page from being cached by the browser. Just execute the following script let at
the beginning of your JSP pages to prevent them from being cached at the browser. You need
both the statements to take care of some of the older browser versions.

response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma\","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server

After converting jsp into servlet which methods are present i.e all 6
methods(jspinit(),_jspService(),jspDestroy(),init(),service(),destroy()) or only 3 methods i.e
either jsp life cycle methods or servlet lifecycle methods
A jsp is basically a servlet so, there would be three methods not 6. jspInit() and jspDestroy()
methods would be visible only if you override them in jsp page

public void jspInit() {
//initialization code
public void jspInit() {
//destroy code

_jspService() mehtod is always visible.

How Servlet Applet communication achieved?
a) Type the following code in your applet.

 //The path of the servlet needs to be passed as input param to URL Class.
    URL urlObj = new URL(http://server/servlet?var1=1&var2=2);
    URLConnection uConn = ulrObj.openConnection();
// set the MIME type if required. i.e setContentType("");
    InputStream isObj = uConn.getInputStream();

b) We can read response of the servlet from 'isObj' by iterating.

What information that the ServletResponse interface gives the servlet methods for
replying to the client?
for setting the content in servlet response
for communicating the servlet
controlling cache It Allows the servlet to set the content length and MIME type of the reply.
Provides an output stream, ServletOutputStream and a Writer through which the servlet can send
the reply data.


To top