0% found this document useful (0 votes)
463 views24 pages

JSP-Servlet Interview Questions You'll Most Likely Be Asked

JSP Servlet Interview Questions You’ll Most Likely Be Asked is a perfect companion to stand ahead above the rest in today's competitive job market. Rather than going through comprehensive, textbook-sized reference guides, this book includes only the information required immediately for job search to build an IT career. This book puts the interviewee in the driver's seat and helps them steer their way to impress the interviewer.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
463 views24 pages

JSP-Servlet Interview Questions You'll Most Likely Be Asked

JSP Servlet Interview Questions You’ll Most Likely Be Asked is a perfect companion to stand ahead above the rest in today's competitive job market. Rather than going through comprehensive, textbook-sized reference guides, this book includes only the information required immediately for job search to build an IT career. This book puts the interviewee in the driver's seat and helps them steer their way to impress the interviewer.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 24

JSP-Servlet Interview

Questions
Review these typical interview questions and think about how you
would answer them. Read the answers listed; you will find best
possible answers along with strategies and suggestions.
This page is intentionally left blank.
Chapter 1

Servlet

1: What is the difference between JSP and Java Servlet?


Answer:

code for a page and is based on Java. Servlets are java programs
that are written and compiled in a proper Java environment. You
can write dynamic HTML content in Servlets. JSP is a view
whereas Servlets are controllers. JSP ultimately compiles into a
servlet before it runs and hence, is a little slower compared to the
Servlets. -side data

involving complex business functions, the Servlets are preferred.


JSP is easier to write as the scripting within the HTML code is
easier to manage. With Javascript, JSP can easily manage client-
side matters whereas the Servlets are purely server-side.
2: Explain the tasks of a Servlet.
Answer:

by the client, process the requests at the server-side to generate


results, and send this result as implicit or explicit to the client.
Explicit input data would be form data as input or selected by the
client. This is explicitly input or selected by the client to retrieve
some information or to provide some information which has to be
saved in the database. Implicit input data would be the request
headers or other hidden elements such as status codes etc. which

o
the information requested. Implicit output would be the request
headers and status codes sent by the server.

3: Explain Servlet Mapping.


Answer:
Servlet mapping is the method used to map the servlet classes and
packages to a particular web application. It is done using the
<servlet-mapping/> xml tag. The set of servlets and the classes
defined in them are mentioned within the <servlet-mapping/> tags
in the web.xml file. When the jsp page accesses a particular
package or servlet class, the web.xml fetches this mapping and
accesses the corresponding class file which has the servlet class
definition. For example,
<servlet-mapping>
<servlet-name>healthdrinks</servlet-name>
<url-pattern>/health_drink/*</url-pattern>
</servlet-mapping>
Here, the <servlet-name/> contains the name of the servlet to be
executed for the url patterns mentioned within the <url-pattern/>
tags. The string mentioned within the url-pattern tag is case
sensitive.

4: Explain what happens when a client requests a jsp page from


the browser.
Answer:
When the client browser tries to access a particular jsp page, the
corresponding jsp server is identified from the URL first. The jsp
server checks for an existing compiled servlet corresponding to
the requested page. If the page is not found or if the class is older
than the latest jsp page, it has to be compiled first. The requested

forwarded to the servlet engine which is a part of the web server.


The Servlet engine loads the compiled servlet class and executes
the same. The result is written as static HTML content and passed
on to the web server as an HTTP response. It finally reaches the
browser which displays the HTML content to the user.

5: Why do we need JSP when Servlets are there?


Answer:
Even when you are writing JSP code, you know that ultimately it
is going to get converted into java code and a servlet. The jsp
-side scripts are compiled into java servlet class and

main advantage of jsp pages is that they are much simpler to code
and implement. The HTML tags will be a real pain to write using
the java println statement. Instead, the required minimal scripts
are included between the HTML tags, making the jsp pages easier
to maintain. When using JSP, you can get the user interface coded
separately and just include the required java elements within the
scripting tags.

6: What is SSI (Server Side Includes)?


Answer:
Server side includes (SSI) are the directives and servlet code
embedded within HTML pages to add some dynamically
generated data retrieved from the server into the HTML pages.
<html>
<head> SSI </head>
<body>
<p> Username is
<servlet code=loginServlet> // It will call loginServlet and return
the output to html page
<param name=id value=123>
</servlet>
</body>
</html>
It will take the id from the HTML page and retrieve the username
from the servlet file.

7: How do servlets handle multiple requests simultaneously?


Answer:
The Servlet container will create a single instance and multiple
threads for a servlet. When multiple requests arrive
simultaneously, the container synchronizes these requests by
creating a new thread for each request and calls the service()
method. The Service() method will be called for each request so as
to handle these multiple requests.

8: What is the difference between GenericServlet and


HttpServlet?
Answer:
The differences between GenericServlet and HttpServlet are:
a) HttpServlet is for the HTTP protocol requests and is
protocol dependent. It is extended from GenericServlet
and inherits all the properties of a GenericServlet.
b) GenericServlet is for all protocols such as FTP and is a
protocol independent. It is sufficient to implement
service() method to implement genericservlet. It
implements the LOG method of ServletContext interface.

9: If we need to perform a login validation before hitting our


application servlet, what could be done?
Answer:
To perform a login validation, we can use ServletFilter. This is
mainly to provide authorization for all the pages given in the
application. Only a single filter is needed to enable the
authorization.

10: Who is responsible to create a servlet instance?


Answer:
Web container is responsible to create a servlet instance.

11: What is Servlet Collaboration?


Answer:
Servlet Collaboration refers to the communication between
servlets. Information can be shared among the servlets through
some method invocations, such as:
a) RequestDispatcher (forward() or include())
b) response.sendRedirect()
c) System.getProperties().put("name", "ABC") and
String s1 = System.getProperty("name");
d) ServletContext

12: What is the architecture of a Servlet Interface?


Answer:
The architecture of a Servlet Interface is as given below:
Servlets >> GenericServlet >> HttpServlet >> CustomServlet
javax.servlet is the package which contains interfaces and classes.

13: What are the objects a servlet would receive during client
interaction?
Answer:
A servlet would receive two objects during client interaction. They
are:
a) ServletRequest interface
b) ServletRespose interface

14: Why do we not have constructors in servlets?


Answer:
The init() method is used for instantiating the servlets instead of
constructors. The servlet container will take care of instantiating
the servlet hence an explicit constructor is not required.
Initialization code can be placed within init() method as we would
have placed within the constructor. It will be called by the
container once it has loaded the servlet at the first request.

15: How would you get the real path of the current servlet?
Answer:
We can retrieve the current real path using getRealPath()
method:
System.out.println(request.getRealPath(request.getServletPath());

16: How would you call one servlet from another?


Answer:
A servlet can be called from another:
a) Using RequestDispatcher
b) Using URLConnection or HttpClient
c) Using response.sendRedirect

17: What are the different types of Servlets available?


Answer:
The different types of Servlets available are:
a) Generic Servlet
b) HttpServlet

18: Explain about HttpServlet and its methods.


Answer:
Httpservlet extends the GenericServlet class. A servlet class which
implements HttpServlet class should override one of the below
methods.
The methods of httpservlet are:
a) doGet()
b) doPost()
c) doPut()
d) doDelete()
e) getServletInfo()
f) service()
The service() method is not normally overridden since it
dispatches the HTTP requests automatically to these appropriate
methods. If service() method are to be overridden, doGet() or
doPost() methods should also be invoked explicitly from the
overridden service() method else super.service() method should
be invoked from the overridden service() method to preserve the
original service() functionality.

19: What are the advantages of Servlets?


Answer:
The advantages of Servlets are:
a) Platform independent: Once it is compiled, it can be run
in any web server
b) Threadsafe: Different threads are created for different
requests in a multithreaded environment

20: Name the servers available for deploying Servlets.


Answer:
The various servers available for deploying Servlets are:
a) Netscape
b) IBM Websphere
c) Oracle
d) Tomcat webserver
e) Apache
f) Weblogic

21: What would happen if I want to use the Servlet 2.1 API
instead of Servlet2.0 API?
Answer:
If we use Servlet 2.1 API instead of Servlet2.0 API, servlet to
servlet communication will not work as the communication using
servletcontext methods like getServlet() and getServlets() have
been deprecated. It will return null.

22: How would you avoid IllegalStateException in Servlet?


Answer:
IllegalStateException in Servlet happens when the servlet attempts
to write into the response object (output stream) after it has been
redirected or committed. It can be avoided using a return
statement immediately after response.sendRedirect() or forward()
methods. For example,
public void doGet(HttpServletRequestreq,
HttpServletResponseresp) throws ServletException, IOException {
if(s1.equals(s2)) {
response.sendRedirect("login.jsp");
return;
}
}

23: How would you make servlet stop timing-out when


processing a long database query?
Answer:
If the database query takes several minutes to execute, the
browser will time out before it retrieves the result for that request.
To avoid this, we can use Client-pull/client-refresh/server polling,
which makes the client to automatically refresh after a
predetermined period of time. In this case, the client will poll the
servlet in a regular period of time to fetch the page, which will
make the servlet check the response object value and refetch the
details. It would be able to send wait while processing the
request ... message to the client browser until the request gets
processed.
<META http- />

24: Why is HttpServlet declared as abstract even though it has


concrete methods?
Answer:
HttpServlet contains methods such as doGet(), doPost(), doPut().
Since it is declared as abstract, it does not require all of its
methods to be implemented. We can implement the methods
based on the HTTP request or requirement. Otherwise we must
implement all the methods including those which are not
required.
25: How would you refresh a servlet automatically if any data
gets updated into database?
Answer:
Servlet can be refreshed using client side refresh or server push if
any data gets updated into database.

26: Describe the difference between URL encoding and URL


rewriting.
Answer:
The difference between URL encoding and URL rewriting are:
a) URL encoding: Transforms user input into CGI form
which will trim spaces and punctuation, replacing them
with special characters. URL decoding is a reverse process
of encoding which will transform CGI format back to
normal format. We use encode() and decode() methods of
java.net.URLEncoder and java.net.URLDecoder classes.
E.g. Input >> and Transform Into >>

b) URL rewriting: Additional information such as session id


or parameters are appended at the end of the URL.
E.g. http://localhost:8080/Demo/servlets?param1=abc

27: What is the use of Servlet Wrapper classes?


Answer:
Servlet wrapper classes are ServletRequestWrapper and
ServletResponseWrapper. The subclasses are
HttpServletRequestWrapper and HttpServletResponseWrapper
classes. It uses wrapper or decorator design pattern. It provides
custom implementation of subclasses which extends
servletrequest and servletresponse types. The methods are
invoked through the wrapped request or response objects.

28: What is servlet chaining?


Answer:
Servlet chaining is a mechanism where the output of one servlet
will be sent to a second servlet and the output of second servlet
will be sent to a third servlet. The output of the last servlet will be
sent to web browser/container.

29: What are the functions of Servlet Container?


Answer:
The functions of Servlet Container are:
a) JSP support: Converts JSP page into servlet class, for
example, Login.jsp will be converted to Login_jsp.java
b) Multithreading support: Creates separate threads for each
request and calls service()
c) Communication support: Handles communication
between web server and servlets
d) Declarative security: Maintains security in web.xml using
authentication techniques
e) Lifecycle management: Manages servlet lifecycle such as
loading, instantiating, service, and destroys servlets which
are eligible for garbage collection

30: What is Server Side push and what is it used for?


Answer:
If the client requests data from the server, it is called Client pull.
i.e. the client pulls the data from the server. Sometimes the server
needs to continuously send data to the client to maintain sync
between server database and client page. This is called Server side
push. For instance, monitors which display online status such as
airport and share market status.
Server keeps sending the data; client receives it and waits for the
next information. The server does not create a new TCP
connection for each request. It leaves the connection open after
sending the initial data to the client. This is an expensive
implementation, as the sockets remain open.

31: What is Client refresh/Client pull mechanism and how do we


achieve it?
Answer:
Since server side push is an expensive approach, we can use the
client refresh mechanism. It will automatically refresh the client
browser page every 3 or 5 seconds (given below).Every 3 seconds
the client will send a request to the server for the information and
servlet will retrieve and send it to the browser. HTTP-EQUIV
attribute information will be added to the http response header.
<META HTTP-EQUIV="Refresh" CONTENT="3;
URL=/servlets/testServlet/">

32: How would you achieve/make Client Auto Refresh using


servlets?
Answer:
Client browser page will be refreshed every 5 (given) seconds. i.e
server will send request to client every 5 seconds using
addHeader() method of response object till the servlet gets
destroyed.
public void doGet(HttpServletRequest req,
HttpServletResponseresponse) throws ServletException,
java.io.IOException {
HttpSession session = req.getSession();
response.addHeader("Refresh", "5");
response.setContentType("text/html"); //If response is text
message
}

33: What types of protocols are supported by HttpServlet?


Answer:
Httpservlet extends GenericServlet class and supports Http and
Https protocols whereas GenericServlet supports various
protocols.

34: How would you send data from servlet to Javascript?


Answer:
Data from servlet can be sent to Javascript as below:
publicvoiddoGet(HttpServletRequest request,
HttpServletResponseresponse)
throwsIOException,ServletException{
PrintWriter out=response.getWriter();
out.println("<script>");
out.println("varuname='"+uName+"';");
out.println("alert(uname)");
out.println("</script>");
}
}

35: How would you retrieve the name and version number of
servlet or JSP engine?
Answer:
The name and version number of JSP engine or servlet is retrieved
as below:
a) In servlet:
String info=
getServletConfig().getServletContext().getServerInfo();
b) In JSP:
//About application server
<%= application.getServerInfo() %>
// About JSP engine
<%=JspFactory.getDefaultFactory().getEngineInfo()getSpec
ificationVersion()%>

36: What is meant by parsequerystring?


Answer:
Parsequerystring parses the string in the form of a key and value
pair similar to It appends the string with the URL. The
query string will be generated if doGet() method is used and it
will not be appended if doPost() method is used.

37: Which one is better to write binary data: JSP or servlet?


Answer:
Servlet is the best solution for writing binary data using
ServletOutputStream. JSP is not suitable. The JspWriter class does
not support writing bytes, it is designed to send text data and the
JSP container includes whitespaces, which are unnecessary when
writing binary data.

You might also like