Servlet
Interview Questions
Servlets are very important topic of Java EE and all of the web
applications framework such as Spring and Struts are built on top of it. This
makes servlet a hot topic in Java interviews.
Here I am providing
a list of 50 servlet interview questions with answers to help you tackle most
of the interview questions related to servlets and web applications in java.
Q: What is servlet?
A: A servlet is a Java
programming language class that is used to extend the capabilities of servers
that host applications accessed by means of a request- response programming
model. Before the servlet, CGI scripting language was used as server side
programming language.
Q: What is the use of servlet?
A: Uses of servlet includes:
·
Processing and storing data submitted by an HTML form.
·
Providing dynamic content.
·
A Servlet can handle multiple request concurrently and be used to develop high
performance system
·
Managing state information on top of the stateless HTTP.
Q: What is the life cycle of servlet?
A: Life cycle of Servlet:
·
Servlet class loading
·
Servlet instantiation
·
Initialization (call the init method)
·
Request handling (call the service method)
·
Removal from service (call the destroy method)
Q: Why do we need constructor in servlet if we use
the init ()?
A: Even though there is an
init method in a servlet which gets called to initialize it, a constructor is
still required to instantiate the servlet. Even though you as the developer
would never need to explicitly call the servlet's constructor, it is still
being used by the container.
Q: How servlet is loaded?
A: The servlet is loaded by:
·
First request is made.
·
Server starts up (auto-load).
·
There is only a single instance which answers all requests concurrently. This
saves memory and allows a Servlet to easily manage persistent data.
·
Administrator manually loads.
Q: When the servlet is unloaded?
A: Servlet gets unloaded when:
·
Server shuts down.
·
Administrator manually unloads.
Q: What is servlet interface?
A: The central abstraction in
the Servlet API is the Servlet interface. All servlets implement this
interface, either directly or more commonly by extending a class that
implements it.
Q: What is the generic servlet class?
A: GenericServlet is an
abstract class that implements the Servlet interface and the ServletConfig
interface. In addition to the methods declared in these two interfaces, this
class also provides simple versions of the lifecycle methods init () and
destroy (), and implements the log method declared in the ServletContext
interface.
Q: What is the difference between GenericServlet
and HttpServlet?
A: The difference is:
·
The GenericServlet is an abstract class that is extended by HttpServlet to
provide HTTP protocol-specific methods. But HttpServlet extends the
GenericServlet base class and provides a framework for handling the HTTP
protocol.
·
The GenericServlet does not include protocol-specific methods for handling
request parameters, cookies, sessions and setting response headers. The
HttpServlet subclass passes generic service method requests to the relevant
doGet () or doPost () method.
·
GenericServlet is not specific to any protocol. HttpServlet only supports HTTP
and HTTPS protocol.
Q: Why HttpServlet class is declared abstract?
A: The HttpServlet class is
declared abstract because the default implementations of the main service
methods do nothing and must be overridden. This is a convenience implementation
of the Servlet interface, which means that developers do not need to implement
all service methods.
If your servlet is required to handle doGet () requests for example, there is no need to write a doPost () method too.
If your servlet is required to handle doGet () requests for example, there is no need to write a doPost () method too.
Q: Can servlet have a constructor?
A: Yes
Q: What are the type of protocols supported by the
HttpServlet?
A: It extends the
GenericServlet base class and provides a framework for handling the HTTP
protocol. So, HttpServlet only supports HTTP and HTTPS protocol.
Q: What is the difference between the doGet () and
doPost ()?
A: The difference is:
·
In doGet() the parameters are appended to the URL and sent along with header
information. In doPost (),send the information through a socket back to the
webserver and it won't show up in the URL bar.
·
The amount of information you can send back using a GET is restricted as URLs
can only be 1024 characters. You can send much more information to the server
by using post and it's not restricted to textual data either. It is possible to
send files and even binary data such as serialized Java objects!
·
DoGet() is a request for information.It does not change anything on the server.
(doGet () should be idempotent). doPost () provides information (such as
placing an order for merchandise) that the server is expected to remember.
Q: When to use doGet() and when doPost()?
A:Always prefer to use GET (As
because GET is faster than POST), except mentioned in the following reason:
·
If data is sensitive.
·
Data is greater than 1024 characters.
·
If your application don't need bookmarks.
Q: How do I support both doGet () and doPost ()
from same servlet?
A:The easy way is, just support
POST, then have your doGet method call your doPost method.
Q: Should I override the service () method?
A: We never override the
service method, since the HTTP Servlets have already taken care of it. The
default service function invokes the doXXX() method corresponding to the method
of the HTTP request. For example, if the HTTP request method is GET, doGet ()
method is called by default.
A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.
A servlet should override the doXXX() method for the HTTP methods that servlet supports. Because HTTP service method checks the request method and calls the appropriate handler method, it is not necessary to override the service method itself. Only override the appropriate doXXX() method.
Q: What is the ServletContext?
A: A servlet context object
contains the information about the Web application of which the servlet is a
part. It also provides access to the resources common to all the servlets in
the application. Each Web application in a container has a single servlet
context associated with it.
Q: What is the difference between the ServletConfig
and ServletContext interface?
A: The ServletConfig interface
is implemented by the servlet container 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 ServletContext
defines a set of methods that a servlet uses to communicate with its servlet
container.
Q: What is the difference between forward () and
sendRedirect ()?
A: The difference is:
·
A forward is performed internally by the servlet. A redirect is a two step
process, where the web application instructs the browser to fetch a second URL,
which differs from the original.
·
The browser is completely unaware that it has taken place, so its original URL
remains intact. But in sendRedirect, the browser, in this case, is doing the
work and knows that it's making a new request.
Q: What is the difference between forward() and
include()?
A: The RequestDispatcher
include() method inserts the contents of the specified resource directly in the
flow of the servlet response, as if it were part of the calling servlet. The
RequestDispatcher forward() method is used to show a different resource in
place of the servlet that was originally called.
Q: What is the use of servlet wrapper classes?
A: The
HttpServletRequestWrapper and HttpServletResponseWrapper classes are designed
to make it easy for developers to create custom implementations of the servlet
request and response types.
The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.
The classes are constructed with the standard HttpServletRequest and HttpServletResponse instances respectively and their default behaviour is to pass all method calls directly to the underlying objects.
Q: What is a deployment descriptor?
A: A deployment descriptor is
an XML document with an .xml extension. It defines a component's deployment
settings. It declares transaction attributes and security authorization for an
enterprise bean.
The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
The information provided by a deployment descriptor is declarative and therefore it can be modified without changing the source code of a bean.
Q: What is the preinitialization of servlet?
A: A container does not
initialize the servlets as soon as it starts up; it initializes a servlet when
it receives a request for that servlet first time. This is called lazy
loading.
The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
The servlet specification defines the element, which can be specified in the deployment descriptor to make the servlet container load and initialize the servlet as soon as it starts up. The process of loading a servlet before any request comes in is called preloading or preinitializing a servlet.
Q: What is the <load-on-startup> element?
A: The <load-on-startup>
element of a deployment descriptor is used to load a servlet file when the
server starts instead of waiting for the first request. It is also used to
specify the order in which the files are to be loaded.
Q: What is session?
A: A session refers to all the
requests that a single client might make to a server in the course of viewing
any pages associated with a given application. Sessions are specific to both
the individual user and the application.
Q: What is the session tracking?
A: Session tracking is a
mechanism that servlets use to maintain state about a series of requests from
the same user (requests originating from the same browser) across some period
of time.
Q: What is the need of session tracking in web
application?
A: HTTP is a stateless
protocol. Every request is treated as new request. For web applications to be
more realistic they have to retain information across multiple requests. Such
information which is part of the application is referred as "state".
To keep track of this state we need session tracking.
Q: What are the different types of session
tracking?
A: Different types are:
·
URL rewriting
·
Hidden Form Fields
·
Cookies
·
Secure Socket Layer (SSL) Sessions
Q: How do I use cookies to store session state on
client?
A: In a servlet, the
HttpServletResponse and HttpServletRequest objects passed to method
HttpServlet. Service () can be used to create cookies on the client and use
cookie information transmitted during client requests. JSPs can also use
cookies, in scriptlet code or, preferably, from within custom tag code.
·
To set a cookie on the client, use the addCookie() method in class
HttpServletResponse. Multiple cookies may be set for the same request, and a
single cookie name may have multiple values.
·
To get all of the cookies associated with a single HTTP request, use the
getCookies() method of class HttpServletRequest
Q: What are the advantages of storing session state
in cookies?
A: Cookies are usually
persistent, so for low-security sites, user data that needs to be stored
long-term (such as a user ID, historical information, etc.) can be maintained
easily with no server interaction. For small- and medium-sized session data,
the entire session data (instead of just the session ID) can be kept in the
cookie.
Q: What is URL rewriting?
A: URL rewriting is a method
of session tracking in which some extra data is appended at the end of each
URL. This extra data identifies the session. The server can associate this
session identifier with the data it has stored about that session.
Q: How can destroyed session in servlet?
A: Using session.invalidate()
method.
Q: What is servlet lazy loading?
A: A container does not
initialize the servlets as soon as it starts up; it initializes a servlet when
it receives a request for that servlet first time. This is called lazy loading.
Q: What is servlet chaining?
A: Servlet Chaining is a
method where the output of one servlet is piped into a second servlet. The
output of the second servlet could be piped into a third servlet, and so on.
The last servlet in the chain returns the output to the Web browser
Q: What is filter?
A: Filters are Java components
that are used to intercept an incoming request to a Web resource and a response
sent back from the resource. It is used to abstract any useful information
contained in the request or response.
Q: What are the advantages of jsp over servlet?
A: The advantage of JSP is
that they are document-centric. Servlets, on the other hand, look and act like
programs. A Java Server Page can contain Java program fragments that
instantiate and execute Java classes, but these occur inside an HTML template
file and are primarily used to generate dynamic content.
Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.
Some of the JSP functionality can be achieved on the client, using JavaScript. The power of JSP is that it is server-based and provides a framework for Web application development.
Q: What is the life cycle of jsp?
A: Life cyle of jsp:
·
Translation
·
Compilation
·
Loading the class
·
Instantiating the class
·
jspInit()
·
_jspService()
·
jspDestroy()
Q: What is the jspInit() method?
A: The jspInit() method of the
javax.servlet.jsp.JspPage interface is similar to the init() method of
servlets. This method is invoked by the container only once when a JSP page is
initialized. It can be overridden by a page author to initialize resources such
as database and network connections, and to allow a JSP page to read persistent
configuration data.
Q: What is the _jspService ()?
A: The _jspService() method of
the javax.servlet.jsp.HttpJspPage interface is invoked every time a new request
comes to a JSP page. This method takes the HttpServletRequest and
HttpServletResponse objects as its arguments. A page author cannot override
this method, as its implementation is provided by the container.
Q: What is the jspDestroy ()?
A: The jspDestroy() method of
the javax.servlet.jsp.JspPage interface is invoked by the container when a JSP
page is about to be destroyed. This method is similar to destroy() method of
servlets. It can be overridden by a page author to perform any cleanup
operation such as closing a database connection.
Q: What jsp life cycle method can I override?
A: You cannot override the
_jspService() method within a JSP page. You can however, override the jspInit()
and jspDestroy() methods within a JSP page. JspInit() can be useful for
allocating resources like database connections, network connections, and so
forth for the JSP page. It is good programming practice to free any allocated
resources within jspDestroy().
Q: What are implicit objects in jsp?
A: Implicit objects in JSP are
the Java objects that the JSP Container makes available to developers in each
page. These objects need not be declared or instantiated by the JSP author.
They are automatically instantiated by the container and are accessed using
standard variables; hence, they are called implicit objects.
Q: How many implicit objects are available in jsp?
A: These implicit objects are
available in jsp:
·
Request
·
Response
·
PageContext
·
session
·
application
·
Out
·
config
·
page
·
exception
Q: What are jsp directives?
A: JSP directives are messages
for the JSP engine. i.e., JSP directives serve as a message from a JSP page to
the JSP container and control the processing of the entire page.
They are used to set global values such as a class declaration, method implementation, output content type, etc. They do not produce any output to the client.
They are used to set global values such as a class declaration, method implementation, output content type, etc. They do not produce any output to the client.
Q: What is page directive?
A: Page Directive is:
·
A page directive is to inform the JSP engine about the headers or facilities
that page should get from the environment.
·
The page directive is found at the top of almost all of our JSP pages.
·
There can be any number of page directives within a JSP page (although the
attribute – value pair must be unique).
·
The syntax of the include directive is: <%@ page
attribute="value">
Q: What are the attributes of page directive?
A: There are thirteen
attributes defined for a page directive of which the important attributes are
as follows:
·
Import: It specifies the packages that are to be imported.
·
Session: It specifies whether a session data is available to the
JSP page.
·
ContentType: It allows a user to set the content-type for a page.
·
IsELIgnored: It specifies whether the EL expressions are ignored
when a JSP is translated to a servlet.
Q: What is the include directive?
A: Include directive is used
to statically insert the contents of a resource into the current JSP. This
enables a user to reuse the code without duplicating it, and includes the
contents of the specified file at the translation time.
Q: What are the jsp standard actions?
A: The JSP standard actions
affect the overall runtime behaviour of a JSP page and also the response sent
back to the client. They can be used to include a file at the request time, to
find or instantiate a Java Bean, to forward a request to a new page, to
generate a browser-specific code, etc.
Q: What are the standards actions available in jsp?
A: The standards actions
include:
·
<jsp:include>
·
<jsp:forward>
·
<jsp:useBean>
·
<jsp:setProperty>
·
<jsp:getProperty>
·
<jsp:param>
·
<jsp:plugin>
Q: What is the <jsp: useBean> standard
action?
A: The <jsp: useBean>
standard action is used to locate an existing Java Bean or to create a Java
Bean if it does not exist. It has attributes to identify the object instance,
to specify the lifetime of the bean, and to specify the fully qualified class
path and type.
Q: What is the scope available in <jsp: useBean>?
A: Scope includes:
·
Page scope
·
Request scope
·
application scope
·
session scope
Q: What is the <jsp:forward> standard action?
A: The <jsp:forward>
standard action forwards a response from a servlet or a JSP page to another
page. The execution of the current page is stopped and control is transferred
to the forwarded page.
Q: What is the <jsp: include> standard
action?
A: The <jsp: include>
standard action enables the current JSP page to include a static or a dynamic
resource at runtime. In contrast to the include directive, include action is
used for resources that change frequently. The resource to be included must be
in the same context.
Q: What is the difference between include directive
and include action?
A: The difference is:
·
Include directive, includes the content of the specified file during the
translation phase–when the page is converted to a servlet. Include action,
includes the response generated by executing the specified page (a JSP page or
a servlet) during the request processing phase–when the page is requested by a
user.
·
Include directive is used to statically insert the contents of a resource into
the current JSP. Include standard action enables the current JSP page to include
a static or a dynamic resource at runtime.
Q: What is the difference between
pageContext.include () and <jsp: include>?
A: The <jsp: include>
standard action and the pageContext.include() method are both used to include
resources at runtime. However, the pageContext.include () method always flushes
the output of the current page before including the other components, whereas
<jsp: include> flushes the output of the current page only if the value
of flush is explicitly set to true.
Q: What is the <jsp: setProperty> action?
A: You use jsp: setProperty to
give values to properties of beans that have been referenced earlier.
Q: What is the <jsp: getProperty> action?
A: The <jsp:
getProperty> action is used to access the properties of a bean that was set
using theaction. The container converts the property to a String as follows:
If it is an object, it uses the
toString() method to convert it to a String. If it is a primitive, it converts
it directly to a String using the valueOf() method of the corresponding Wrapper
class.
The syntax of the <jsp:
getProperty> method is: <jsp: getProperty name="Name"
property="Property" />
Q: What is the <jsp: param> standard action?
A: The <jsp: param>
standard action is used with <jsp: include> or <jsp: forward> to
pass parameter names and values to the target resource.
Q: What is the <jsp: plugin> action?
A: This action lets you insert
the browser-specific OBJECT or EMBED element needed to specify that the browser
run an applet using the Java plugin.
Q: What is the scripting element?
A: JSP scripting elements let
you insert Java code into the servlet that will be generated from the current
JSP page.
·
Expressions
·
Scriptlet
·
Declarations
·
comment
Q: What is the scriptlet?
A: A scriptlet contains Java
code that is executed every time a JSP is invoked. When a JSP is translated to
a servlet, the scriptlet code goes into the service() method.
Hence, methods and variables written in scriptlet are local to the service() method. A scriptlet is written between the <% and %>tags and is executed by the container at request processing time.
Hence, methods and variables written in scriptlet are local to the service() method. A scriptlet is written between the <% and %>tags and is executed by the container at request processing time.
Q: What is the jsp declaration?
A: JSP declarations are used
to declare class variables and methods in a JSP page. They are initialized when
the class is initialized. Anything defined in a declaration is available for
the whole JSP page. A declaration block is enclosed between the <%! and
%>tags. A declaration is not included in the service() method when a JSP is
translated to a servlet.
Q: What is the jsp expression?
A: A JSP expression is used to
write an output without using the out.print statement. It can be said as a
shorthand representation for scriptlet. An expression is written between the
<%= and %> tags. It is not required to end the expression with a semicolon,
as it implicitly adds a semicolon to all the expressions within the expression
tags.
Q: How is scripting disabled?
A: Scripting is disabled by
setting the scripting-invalid element of the deployment descriptor to true. It
is a subelement of jsp-property-group. Its valid values are true and false.
Q: Why is _jspService () start with ‘_’?
A: _jspService() method will
be written by the container hence any methods which are not to be overridden by
the end user are typically written starting with a '_'. This is the reason why
we don't override _jspService() method in any JSP page.
Q: How to pre-compile jsp?
A: Add jsp_precompile as a
request parameter and send a request to the JSP file. This will make the jsp
pre-compile. http://localhost:8080/jsp1/test.jsp?jsp_precompile=true
It causes execution of JSP life cycle until jspInit() method without executing _jspService() method.
It causes execution of JSP life cycle until jspInit() method without executing _jspService() method.
Q: What is the benefit of pre-compile jsp page?
A: It removes the start-up lag
that occurs when a container must translate a JSP page upon receipt of the
first request.
Q: What is the difference between variable declared
inside the declaration tag and variable declared in scriptlet?
A: Variable declared inside
declaration part is treated as a instance variable and will be placed directly
at class level in the generated servlet. Variable declared in a scriptlet will
be placed inside _jspService () method of generated servlet. It acts as local
variable.
Q: What are the three kind of comment in jsp?
A: These are the three types
of commenst in jsp:
·
JSP Comment: <%-- this is jsp comment -- %>
·
HTML Comment: <!-- this is HTMl comment -- >
·
Java Comments: <% // single line java comment /* this is multiline comment
*/ %>
Q: What is the output comment?
A: The comment which is
visible in the source of the response is called output comment. <!-- this is
HTMl comment -- >
Q: What is a hidden comment?
A: This is also known as JSP
comment and it is visible only in the JSP and in rest of phases of JSP life
cycle it is not visible. <%-- this is jsp comment -- %>
Q: How does jsp handle the run time exception?
A: You can use the errorPage
attribute of the page directive to have uncaught run-time exceptions
automatically forwarded to an error processing page.
Q: How can I implement the thread safe jsp page?
A: You can make your JSPs
thread-safe by having them implement the SingleThreadModel interface. This is
done by adding the directive in the JSP. <%@ page
isThreadSafe="false" %>
Q: Is there a way to reference the “this” variable
within the jsp?
A: Yes, there is. The page
implicit object is equivalent to "this", and returns a reference to
the generated servlet.
Q: Can you make the use of servletOutputStream
object within jsp?
A: Yes. By using
getOutputStream () method on response implicit object we can get it.
Q: What is autoflush?
A: This command is used to
autoflush the contents. If a value of true is used it indicates to flush the
buffer whenever it is full. In case of false it indicates that an exception
should be thrown whenever the buffer is full. If you are trying to access the
page at the time of conversion of a JSP into servlet will result in error.
Q: What is the different scope available in jsp?
A:The different scopes are:
·
Page: Within the same page.
·
Request: After forward or include also you will get the request
scope data.
·
Session: After sendRedirect also you will get the session scope
data. All data stored in session is available to end user till session closed
or browser closed.
·
Application: Data will be available throughout the application. One
user can store data in application scope and other can get the data from
application scope.
Q: When to use application scope?
A: If we want to make our data
available to the entire application then we have to use application scope.
Q: Can a jsp page instantiate a serialized bean?
A: No problem! The use Bean
action specifies the bean Name attribute, which can be used for indicating a
serialized bean.
Q: In which situation we can use the static include
and dynamic include?
A: If the target resource
won’t change frequently, then it is recommended to use include directives. If
the target resource will change frequently, then it is recommended to use
include action.
Q: What is the JDBC?
A: Java Database Connectivity
(JDBC) is a standard Java API to interact with relational databases form Java.
JDBC has set of classes and interfaces which can use from Java application and
talk to database without learning RDBMS details and using Database Specific
JDBC Drivers
Q: What are the basic steps of using jdbc in java?
A: The basic steps are:
·
Load the RDBMS specific JDBC driver because this driver actually communicates
with the database.
·
Open the connection to database which is then used to send SQL statements and
get results back.
·
Create JDBC Statement object. This object contains SQL query.
·
Execute statement which returns resultset(s). Resultset contains the tuples of
database table as a result of SQL query.
·
Process the result set.
·
Close the connection.
Q: What are the main component of jdbc?
A: The main components are:
·
DriverManager
·
Driver
·
Connection
·
Statement
·
Resultset
Q: What is DriverManager?
A: DriverManager is a static
class. It manages a list of database drivers. Matches connection requests from
the java application with the proper database driver using communication sub
protocol. The first driver that recognizes a certain sub protocol under JDBC
will be used to establish a database Connection.
Q: What is Driver?
A: The JDBC API defines the
Java interfaces and classes that programmers use to connect to databases and
send queries. A JDBC driver implements these interfaces and classes for a
particular DBMS vendor.database communications link, handling all communication
with the database.
Normally, once the driver is loaded, the developer need not call it explicitly.
Normally, once the driver is loaded, the developer need not call it explicitly.
Q: What is the connection?
A: Interface with all methods
for contacting a database. The connection object represents communication
context, i.e., all communication with database is through connection object
only
Q: What is the statement?
A: Encapsulates an SQL
statement which is passed to the database.
Q: What is the resultset?
A: The Resultset represents
set of rows retrieved due to query execution.
Q: How we load a database driver with JDBC?
A: Provided the JAR file
containing the driver is properly configured, just place the JAR file in the
classpath. Java developers NO longer need to explicitly load JDBC drivers using
code like Class.forName() to register a JDBC driver.
The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.
The DriverManager class takes care of this by automatically locating a suitable driver when the DriverManager.getConnection() method is called. This feature is backward-compatible, so no changes are needed to the existing JDBC code.
Q: What is the JDBC Driver interface?
A: The JDBC Driver interface
provides vendor-specific implementations of the abstract classes provided by
the JDBC API. Each vendor driver must provide implementations of the
java.sql.Connection,Statement,PreparedStatement, CallableStatement, ResultSet
and Driver
Q: What does the connection objects represents?
A: The connection object
represents communication context, i.e., all communication with database is
through connection object only.
Q: What is the statement?
A: Statement acts like a
vehicle through which SQL commands can be sent. Through the connection object
we create statement kind of objects.
Q: What is the prepared statement?
A: A prepared statement is an
SQL statement that is precompiled by the database. Through precompilation,
prepared statements improve the performance of SQL commands that are executed
multiple times. Once compiled, prepared statements can be customized prior to
each execution by altering predefined SQL parameters.
Q: What is the difference between statement and
PreparedStatement?
A: The difference is:
·
A standard Statement is used to create a Java representation of a literal SQL
statement and execute it on the database. A PreparedStatement is a precompiled
statement. This means that when the PreparedStatement is executed, the RDBMS
can just run the PreparedStatement SQL statement without having to compile it
first.
·
Statement has to verify its metadata against the database every time. While a
prepared statement has to verify its metadata against the database only once.
·
If you want to execute the SQL statement once go for STATEMENT. If you want to
execute a single SQL statement multiple number of times, then go for
PREPAREDSTATEMENT. PreparedStatement objects can be reused with passing
different values to the queries
Q: What is the callable statement?
A: Callable statements are
used from JDBC application to invoke stored procedures and functions.
Q: How to call a stored procedure from jdbc?
A: PL/SQL stored procedures
are called from within JDBC programs by means of the prepareCall() method of
the Connection object created. A call to this method takes variable bind parameters
as input parameters as well as output variables and creates an object instance
of the CallableStatement class.
Q: What are the types of JDBC Driver?
A: The types are:
·
Type 1: JDBC/ODBC
·
Type2: Native API (partly-Java driver)
·
Type 3: Open Protocol-Net
·
Type 4: Proprietary Protocol-Net(pure Java driver)
Q: Which type of jdbc driver is the faster one?
A: JDBC Net pure Java
driver(Type IV) is the fastest driver because it converts the JDBC calls into
vendor specific protocol calls and it directly interacts with the database.
Q: Does the JDBC-ODBC Bridge support multiple
concurrent open statements per connection?
A: No, You can open only one
Statement object per connection when you are using the JDBC-ODBC Bridge.
Q: What are the standard isolation levels defined
by the jdbc?
A: The standard isolation
levels are:
·
TRANSACTION_NONE
·
TRANSACTION_READ_COMMITTED
·
TRANSACTION_READ_UNCOMMITTED
·
TRANSACTION_REPEATABLE_READ
·
TRANSACTION_SERIALIZABLE
Q: What is the resultset?
A: The ResultSet represents set of
rows retrieved due to query execution. Example: ResultSetrs =
stmt.executeQuery(sqlQuery);
Q: What are the types of resultset?
A: The types are:
·
TYPE_FORWARD_ONLY specifies that a resultset is not scrollable, that is, rows
within it can be advanced only in the forward direction.
·
TYPE_SCROLL_INSENSITIVE specifies that a resultset is scrollable in either
direction but is insensitive to changes committed by other transactions or
other statements in the same transaction.
·
TYPE_SCROLL_SENSITIVE specifies that a resultset is scrollable in either
direction and is affected by changes committed by other transactions or
statements within the same transaction.
Q: What is the difference between
TYPE_SCROLL_INSENSITIVE and TYPE_SCOLL_SENSITIVE?
A: An insensitive resultset is
like the snapshot of the data in the database when query was executed. A
sensitive resultset does NOT represent a snapshot of data; rather it contains
points to those rows which satisfy the query condition.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive. After we obtain the resultset if the data is modified then such modifications are visible through resultset.
After we get the resultset the changes made to data are not visible through the resultset, and hence they are known as insensitive. After we obtain the resultset if the data is modified then such modifications are visible through resultset.
Q: What is the RowSet?
A: A RowSet is an object that
encapsulates a set of rows from either Java Database Connectivity (JDBC) result
sets or tabular data sources like a file or spreadsheet. RowSets support
component-based development models like JavaBeans, with a standard set of
properties and an event notification mechanism.
Q: What are the different types of RowSet?
A:The different types are:
·
Connected - A connected RowSet object connects to the database once and remains
connected until the application terminates.
·
Disconnected - A disconnected RowSet object connects to the database, executes
a query to retrieve the data from the database and then closes the connection.
A program may change the data in a disconnected RowSet while it is
disconnected. Modified data can be updated in the database after a disconnected
RowSet re-establishes the connection with the database.
Q: What is the need of BatchUpdates?
A: The BatchUpdates feature
allows us to group SQL statements together and send to database server in one
single trip.
Q: What is the data source?
A: A DataSource object is the
representation of a data source in the Java programming language. In basic
terms,
·
A DataSource is a facility for storing data.
·
DataSource can be referenced by JNDI.
·
Data Source may point to RDBMS; file System, any DBMS etc.
Q: What are the advantages of data source?
A: The advantages are:
·
An application does not need to hardcode driver information, as it does with
the DriverManager.
·
The DataSource implementations can easily change the properties of data
sources.
·
The DataSource facility allows developers to implement a DataSource class to
take advantage of features like connection pooling and distributed
transactions.
Q: What is the main advantage of connection
pooling?
A: A connection pool is a
mechanism to reuse connections created. Connection pooling can increase
performance dramatically by reusing connections rather than creating a new
physical connection each time a connection is requested.
Q: What is the multi programming?
A: Multiprogramming is a rapid
switching of the CPU back and forth between processes.
Q: What is the difference between TCP and UDP?
A: TCP is designed to provide
reliable communication across a variety of reliable and unreliable networks and
internets.UDP provides a connectionless so it isbasically an unreliable
service. Delivery and duplicate protection are not guaranteed.
Q: What is socket?
A: The combination of an IP
address and a port number is called a socket.
Q: What is the advantage of java socket?
A: The advantages are:
·
Sockets are flexible and sufficient.
·
Efficient socket based programming can be easily implemented for general
communications.
·
Sockets cause low network traffic.
Q: What is the disadvantage of java socket?
A: The disadvantages are:
·
Security restrictions are sometimes overbearing because a Java applet running
in a Web browser is only able to establish connections to the machine where it
came from, and to nowhere else on the network.
·
Despite all of the useful and helpful Java features, Socket based
communications allows only to send packets of raw data between applications.
Both the client-side and server-side have to provide mechanisms to make the
data useful in any way.
·
Since the data formats and protocols remain application specific, the re-use of
socket based implementations is limited.
Q: What is RMI?
A: It stands for Remote Method
Invocation. RMI is a set of APIs that allows to build distributed applications.
RMI uses interfaces to define remote objects to turn local method invocations
into remote method invocations.
Q: What is socket()?
A: The socket () is very
similar to socketPair() except that only one socket is created instead of two.
This is most commonly used when if the process you wish to communicate with is
not the child process.
Q: What is ServerSocket?
A: The ServerSocket class is
used to create serverSocket. This object is used to communicate with client.
Q: What is bind()?
A: It binds the socket to the
specified server and port in the SocketAddress object. Use this method if you
instantiated the ServerSocket using the no-argument constructor.
Q: What is the Datagram?
A: A datagram is an
independent, self-contained message sent over the network whose arrival,
arrival time, and content are not guaranteed.
Q: What is getLocalPort()?
A: It returns the port that
the server socket is listening on. This method is useful if you passed in 0 as
the port number in a constructor and let the server find a port for you.
Q: What is accept()?
A: It waits for an incoming
client. This method blocks until either a client connects to the server on the
specified port or the socket times out, assuming that the time-out value has
been set using the setSoTimeout() method. Otherwise, this method blocks
indefinitely.
Q: What is the network interface?
A: A network interface is the
point of interconnection between a computer and a private or public network. A
network interface is generally a network interface card (NIC), but does not
have to have a physical form.
Q: What is the encapsulation technique?
A: Hiding data within the
class and making it available only through the methods. This technique is used
to protect your class against accidental changes to fields, which might leave
the class in an inconsistent state.
Q: How does the race condition occur?
A: It occurs when two or more
processes are reading or writing some shared data and the final result depends
on who runs precisely when.
Q: What information is needed to create a TCP
Socket?
A: Socket is created from this
information:
·
Local System's: IP Address and Port Number
·
Remote System’s: IPAddress and Port Number
Q: What
is different between web server and application server?
A: A web server responsibility
is to handler HTTP requests from client browsers and respond with HTML
response. A web server understands HTTP language and runs on HTTP protocol.
Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications.
Apache Web Server is kind of a web server and then we have specific containers that can execute servlets and JSPs known as servlet container, for example Tomcat.
Application Servers provide additional features such as Enterprise JavaBeans support, JMS Messaging support, Transaction Management etc. So we can say that Application server is a web server with additional functionalities to help developers with enterprise applications.
Q: Which
HTTP method is non-idempotent?
A: A HTTP method is said to be
idempotent if it returns the same result every time. HTTP methods GET, PUT,
DELETE, HEAD, and OPTIONS are idempotent method and we should implement our
application to make sure these methods always return same result. HTTP method
POST is non-idempotent method and we should use post method when implementing
something that changes with every request.
For example, to access an HTML
page or image, we should use GET because it will always return the same object
but if we have to save customer information to database, we should use POST
method. Idempotent methods are also known as safe methods and we don’t care
about the repetitive request from the client for safe methods.
A: ·
GET is a safe method (idempotent) where POST is non-idempotent method.
·
We can send limited data with GET method and it’s sent in the header request
URL whereas we can send large amount of data with POST because it’s part of the
body.
·
GET method is not secure because data is exposed in the URL and we can easily
bookmark it and send similar request again, POST is secure because data is sent
in request body and we can’t bookmark it.
·
GET is the default HTTP method whereas we need to specify method as POST to
send request with POST method.
·
Hyperlinks in a page uses GET method.
A: The “Content-Type” response
header is known as MIME Type. Server sends MIME type to client to let them know
the kind of data it’s sending. It helps client in rendering the data for user.
Some of the mostly used mime types are text/html, text/xml, application/xml
etc.
We can use ServletContext
getMimeType() method to get the correct MIME type of the file and use it to set
the response content type. It’s very useful in downloading file through servlet
from server.
A: Web Applications are
modules that run on server to provide both static and dynamic content to the
client browser. Apache web server supports PHP and we can create web
application using PHP. Java provides web application support through Servlets
and JSPs that can run in a servlet container and provide dynamic content to
client browser.
Java Web Applications are packaged
as Web Archive (WAR) and it has a defined structure like below image.
A: Java Servlet is server side
technologies to extend the capability of web servers by providing support for
dynamic response and data persistence.
The javax.servlet and
javax.servlet.http packages provide interfaces and classes for writing our own
servlets.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
All servlets must implement the javax.servlet.Servlet interface, which defines servlet lifecycle methods. When implementing a generic service, we can extend the GenericServlet class provided with the Java Servlet API. The HttpServlet class provides methods, such as doGet() and doPost(), for handling HTTP-specific services.
Most of the times, web applications
are accessed using HTTP protocol and thats why we mostly extend HttpServlet
class. Servlet API hierarchy is shown in below image.
A: Servlet technology was
introduced to overcome the shortcomings of CGI technology.
·
Servlets provide better performance that CGI in terms of processing time,
memory utilization because servlets uses benefits of multithreading and for
each request a new thread is created, that is faster than loading creating new
Object for each request with CGI.
·
Servlets and platform and system independent, the web application developed
with Servlet can be run on any standard web container such as Tomcat, JBoss,
Glassfish servers and on operating systems such as Windows, Linux, Unix,
Solaris, Mac etc.
·
Servlets are robust because container takes care of life cycle of servlet and
we don’t need to worry about memory leaks, security, garbage collection etc.
·
Servlets are maintainable and learning curve is small because all we need to
take care is business logic for our application.
A: Servlet containers are also
known as web container, for example Tomcat. Some of the important tasks of
servlet container are:
·
Communication Support: Servlet Container provides easy way of
communication between web client (Browsers) and the servlets and JSPs. Because
of container, we don’t need to build a server socket to listen for any request
from web client, parse the request and generate response. All these important
and complex tasks are done by container and all we need to focus is on business
logic for the applications.
·
Lifecycle and Resource Management: Servlet Container takes care of
managing the life cycle of servlet. From the loading of servlets into memory,
initializing servlets, invoking servlet methods and to destroy them. Container
also provides utility like JNDI for resource pooling and management.
·
Multithreading Support: Container creates new thread for every request
to the servlet and provide them request and response objects to process. So
servlets are not initialized for each request and saves time and memory.
·
JSP Support: JSPs doesn’t look like normal java classes but every JSP in
the application is compiled by container and converted to Servlet and then
container manages them like other servlets.
·
Miscellaneous Task: Servlet container manages the resource pool, perform
memory optimizations, execute garbage collector, provides security
configurations, support for multiple applications, hot deployment and several
other tasks behind the scene that makes a developer life easier.
A: javax.servlet.ServletConfig is
used to pass configuration information to Servlet. Every servlet has it’s
own ServletConfig object and servlet container is responsible
for instantiating this object. We can provide servlet init parameters in
web.xml file or through use of WebInitParam annotation. We can use
getServletConfig() method to get the ServletConfig object of the servlet.
A: javax.servlet.ServletContext interface
provides access to web application parameters to the servlet. The
ServletContext is unique object and available to all the servlets in the web
application. When we want some init parameters to be available to multiple or
all of the servlets in the web application, we can use ServletContext object
and define parameters in web.xml using <context-param> element. We can
get the ServletContext object via the getServletContext() method
of ServletConfig. Servlet containers may also provide context objects that are
unique to a group of servlets and which is tied to a specific portion of the
URL path namespace of the host.
ServletContext is enhanced in
Servlet Specs 3 to introduce methods through which we can programmatically add
Listeners and Filters and Servlet to the application. It also provides some
utility methods such as getMimeType(), getResourceAsStream() etc.
A: Some of the differences
between ServletConfig and ServletContext are:
·
ServletConfig is a unique object per servlet whereas ServletContext is a unique
object for complete application.
·
ServletConfig is used to provide init parameters to the servlet whereas
ServletContext is used to provide application level init parameters that all
other servlets can use.
·
We can’t set attributes in ServletConfig object whereas we can set attributes
in ServletContext that other servlets can use in their implementation.
A: RequestDispatcher interface
is used to forward the request to another resource that can be HTML, JSP or
another servlet in same application. We can also use this to include the
content of another resource to the response. This interface is used for
inter-servlet communication in the same context.
There are two methods defined in
this interface:
A.
void forward(ServletRequest request, ServletResponse response) – forwards the
request from a servlet to another resource (servlet, JSP file, or HTML file) on
the server.
B.
void include(ServletRequest request, ServletResponse response) – includes the
content of a resource (servlet, JSP page, HTML file) in the response.
We can get RequestDispatcher in a
servlet using ServletContext getRequestDispatcher(String path) method. The path
must begin with a / and is interpreted as relative to the current context root.
A: PrintWriter is a
character-stream class whereas ServletOutputStream is a byte-stream class. We
can use PrintWriter to write character based information such as character array
and String to the response whereas we can use ServletOutputStream to write byte
array data to the response.
We can use ServletResponse
getWriter() to get the PrintWriter instance whereas we can use ServletResponse
getOutputStream() method to get the ServletOutputStream object reference.
A: We can’t get instances of
both PrintWriter and ServletOutputStream in a single servlet method, if we
invoke both the methods; getWriter() and getOutputStream() on response; we will
getjava.lang.IllegalStateException at runtime with message as other method
has already been called for this response.
A: We can create deadlock in
servlet by making a loop of method invocation, just call doPost() method from
doGet() method and doGet() method to doPost() method to create deadlock
situation in servlet.
A: Servlet HTTP API provides
two wrapper classes – HttpServletRequestWrapper andHttpServletResponseWrapper.
These wrapper classes are provided to help developers with custom
implementation of servlet request and response types. We can extend these
classes and override only specific methods we need to implement for custom request
and response objects. These classes are not used in normal servlet programming.
A: SingleThreadModel interface
was provided for thread safety and it guarantees that no two threads will
execute concurrently in the servlet’s service method. However SingleThreadModel
does not solve all thread safety issues. For example, session attributes and
static variables can still be accessed by multiple requests on multiple threads
at the same time, even when SingleThreadModel servlets are used. Also it takes
out all the benefits of multithreading support of servlets, thats why this
interface is Deprecated in Servlet 2.4.
A: When servlet container
receives client request, it invokes the service() method which in turn invokes
the doGet(), doPost() methods based on the HTTP method of request. I don’t see
any use case where we would like to override service() method. The whole
purpose of service() method is to forward to request to corresponding HTTP
method implementations. If we have to do some pre-processing of request, we can
always use servlet filters and listeners.
A: We can define a constructor
for servlet but I don’t think its of any use because we won’t be having access
to the ServletConfig object until unless servlet is initialized by container.
Ideally if we have to initialize any resource for servlet, we should override
init() method where we can access servlet init parameters using ServletConfig
object.
A: GenericServlet is protocol
independent implementation of Servlet interface whereas HttpServlet is HTTP
protocol specific implementation. Most of the times we use servlet for creating
web application and that’s why we extend HttpServlet class. HttpServlet class
extends GenericServlet and also provide some other methods specific to HTTP
protocol.
Q: What is the inter-servlet communication?
A: When we want to invoke
another servlet from a servlet service methods, we use inter-servlet
communication mechanisms. We can invoke another servlet using RequestDispatcher
forward() and include() methods and provide additional attributes in request
for other servlet use.
A: HttpServlet init() method
and destroy() method are called only once in servlet life cycle, so we don’t
need to worry about their synchronization. But service methods such as doGet()
or doPost() are getting called in every client request and since servlet uses
multithreading, we should provide thread safety in these methods.
If there are any local variables
in service methods, we don’t need to worry about their thread safety because
they are specific to each thread but if we have a shared resource then we can
use synchronization to achieve thread safety in servlets when working with
shared resources.
The thread safety mechanisms are
similar to thread safety in standalone java application, read more about them
at Thread Safety in Java.
A: Servlet attributes are used
for inter-servlet communication, we can set, get and remove attributes in web
application. There are three scopes for servlet attributes – request scope,
session scope and application scope.
ServletRequest, HttpSession and
ServletContext interfaces provide methods to get/set/remove attributes from
request, session and application scope respectively.
Servlet attributes are different
from init parameters defined in web.xml for ServletConfig or ServletContext.
Q: How do
we call one servlet from another servlet?
A: We can use
RequestDispatcher forward() method to forward the processing of a request to
another servlet. If we want to include the another servlet output to the
response, we can use RequestDispatcher include() method.
A: We can’t use
RequestDispatcher to invoke servlet from another application because it’s
specific for the application. If we have to forward the request to a resource
in another application, we can use ServletResponse sendRedirect() method and
provide complete URL of another servlet. This sends the response to client with
response code as 302 to forward the request to another URL. If we have to send
some data also, we can use cookies that will be part of the servlet response
and sent in the request to another servlet.
Q: What is difference between
ServletResponse sendRedirect() and RequestDispatcher forward() method?
A: .
RequestDispatcher forward() is used to forward the same request to another
resource whereas ServletResponse sendRedirect() is a two step process. In
sendRedirect(), web application returns the response to client with status code
302 (redirect) with URL to send the request. The request sent is a completely
new request.
A.
forward() is handled internally by the container whereas sednRedirect() is
handled by browser.
B.
We should use forward() when accessing resources in the same application
because it’s faster than sendRedirect() method that required an extra network
call.
C.
In forward() browser is unaware of the actual processing resource and the URL
in address bar remains same whereas in sendRedirect() URL in address bar change
to the forwarded resource.
D.
forward() can’t be used to invoke a servlet in another context, we can only use
sendRedirect() in this case.
A: HttpServlet class provide
HTTP protocol implementation of servlet but it’s left abstract because there is
no implementation logic in service methods such as doGet() and doPost() and we
should override at least one of the service methods. That’s why there is no
point in having an instance of HttpServlet and is declared abstract class.
A: We know that Servlet
Container manages the life cycle of Servlet, there are four phases of servlet
life cycle.
.
Servlet Class Loading – When container receives request for a servlet, it first
loads the class into memory and calls it’s default no-args constructor.
A.
Servlet Class Initialization – Once the servlet class is loaded, container
initializes the ServletContext object for the servlet and then invoke it’s init
method by passing servlet config object. This is the place where a servlet
class transforms from normal class to servlet.
B.
Request Handling – Once servlet is initialized, its ready to handle the client
requests. For every client request, servlet container spawns a new thread and
invokes the service() method by passing the request and response object
reference.
C.
Removal from Service – When container stops or we stop the application, servlet
container destroys the servlet class by invoking it’s destroy() method.
A: Servlet Life Cycle consists
of three methods:
.
public void init(ServletConfig config) – This method is used by container to
initialize the servlet, this method is invoked only once in the lifecycle of
servlet.
A.
public void service(ServletRequest request, ServletResponse response) – This
method is called once for every request, container can’t invoke service()
method until unless init() method is executed.
B.
public void destroy() – This method is invoked once when servlet is unloaded
from memory.
A: If we have to initialize
some resource before we want our servlet to process client requests, we should
override init() method. If we override init(ServletConfig config) method, then
the first statement should be super(config) to make sure superclass
init(ServletConfig config) method is invoked first. That’s why GenericServlet
provides another helper init() method without argument that get’s called at the
end of init(ServletConfig config) method. We should always utilize this method
for overriding init() method to avoid any issues as we may forget to add
super() call in overriding init method with ServletConfig argument.
A: URL Encoding is the process
of converting data into CGI form so that it can travel across the network
without any issues. URL Encoding strip the white spaces and replace special
characters with escape characters. We can use java.net.URLEncoder.encode(String
str, String unicode) to encode a String. URL Decoding is the reverse process of
encoding and we can use java.net.URLDecoder.decode(String str, String unicode)
to decode the encoded string. For example “Pankaj’s Data” is encoded to
“Pankaj%27s+Data”.
A: Session is a conversional
state between client and server and it can consists of multiple request and
response between client and server. Since HTTP and Web Server both are
stateless, the only way to maintain a session is when some unique information
about the session (session id) is passed between server and client in every
request and response.
Some of the common ways of
session management in servlets are:
.
User Authentication
A.
HTML Hidden Field
B.
Cookies
C.
URL Rewriting
D.
Session Management API
A: We can use HttpSession for
session management in servlets but it works with Cookies and we can disable the
cookie in client browser. Servlet API provides support for URL rewriting that
we can use to manage session in this case.
The best part is that from coding
point of view, it’s very easy to use and involves one step – encoding the URL.
Another good thing with Servlet URL Encoding is that it’s a fallback approach
and it kicks in only if browser cookies are disabled.
We can encode URL with
HttpServletResponse encodeURL() method and if we have to redirect the request
to another resource and we want to provide session information, we can use
encodeRedirectURL() method.
A: Cookies are used a lot in
web client-server communication, it’s not something specific to java. Cookies
are text data sent by server to the client and it gets saved at the client
local machine.
Servlet API provides cookies support
through javax.servlet.http.Cookie class that implements Serializable and
Cloneable interfaces.
HttpServletRequest getCookies()
method is provided to get the array of Cookies from request, since there is no
point of adding Cookie to request, there are no methods to set or add cookie to
request.
Similarly HttpServletResponse
addCookie(Cookie c) method is provided to attach cookie in response header,
there are no getter methods for cookie.
A: If we have to make sure an
object gets notified when session is destroyed, the object should
implement javax.servlet.http.HttpSessionBindingListener interface.
This interface defines two callback methods – valueBound() and valueUnbound() that
we can define to implement processing logic when the object is added as
attribute to the session and when session is destroyed.
A: HttpServletResponse provide
method to encode URL in HTML hyperlinks so that the special characters and
white spaces are escaped and append session id to the URL. It behaves similar
to URLEncoder encode method with additional process to append jsessionid
parameter at the end of the URL.
However HttpServletResponse
encodeRedirectUrl() method is used specially for encode the redirect URL in
response.
So when we are providing URL
rewriting support, for hyperlinks in HTML response, we should use encodeURL()
method whereas for redirect URL we should use encodeRedirectUrl() method.
A: Servlet Filters are
pluggable java components that we can use to intercept and process requests
before they are sent to servlets and response after servlet code is finished
and before container sends the response back to the client.
Some common tasks that we can do
with filters are:
·
Logging request parameters to log files.
·
Authentication and autherization of request for resources.
·
Formatting of request body or header before sending it to servlet.
·
Compressing the response data sent to the client.
·
Alter response by adding some cookies, header information etc.
Q: What is the effective way to make sure all the
servlets are accessible only when user has a valid session?
A: We know that servlet
filters can be used to intercept request between servlet container and servlet,
we can utilize it to create authentication filter and check if request contains
a valid session or not.
.
A: We know that using
ServletContext, we can create an attribute with application scope that all
other servlets can access but we can initialize ServletContext init parameters
as String only in deployment descriptor (web.xml). What if our application is
database oriented and we want to set an attribute in ServletContext for
Database Connection.
If you application has a single
entry point (user login), then you can do it in the first servlet request but
if we have multiple entry points then doing it everywhere will result in a lot
of code redundancy. Also if database is down or not configured properly, we
won’t know until first client request comes to server. To handle these
scenario, servlet API provides Listener interfaces that we can implement and
configure to listen to an event and do certain operations.
A: If you notice, doGet() and
doPost() methods throw ServletException and IOException. Since browser
understand only HTML, when our application throw exception, servlet container
processes the exception and generate a HTML response. Same goes with other
error codes like 404, 403 etc.
Servlet API provides support for
custom Exception and Error Handler servlets that we can configure in deployment
descriptor, the whole purpose of these servlets are to handle the Exception or
Error raised by application and send HTML response that is useful for the user.
We can provide link to application home page or some details to let user know
what went wrong.
We can configure them in web.xml
like below:
<error-page>
<error-code>404</error-code>
<location>/AppExceptionHandler</location>
</error-page>
<error-page>
<exception-type>javax.servlet.ServletException</exception-type>
<location>/AppExceptionHandler</location>
</error-page>
A: Deployment descriptor is a
configuration file for the web application and it’s name is web.xml and it
resides in WEB-INF directory. Servlet container use this file to configure web
application servlets, servlet config params, context init params, filters,
listeners, welcome pages and error handlers.
With servlet 3.0 annotations, we
can remove a lot of clutter from web.xml by configuring servlets, filters and
listeners using annotations.
A: Usually servlet container
loads a servlet on the first client request but sometimes when the servlet is
heavy and takes time to loads, we might want to load it on application startup.
We can use load-on-startup element with servlet configuration in web.xml file
or use WebServlet annotation loadOnStartup variable to tell container to load
the servlet on system startup.
<servlet>
<servlet-name>foo</servlet-name>
<servlet-class>com.foo.servlets.Foo</servlet-class>
<load-on-startup>5</load-on-startup>
</servlet>
The load-on-startup value should
be int, if it’s negative integer then servlet container will load the servlet
based on client requests and requirement but if it’s 0 or positive, then
container will load it on application startup.
If there are multiple servlets
with load-on-startup value such as 0,1,2,3 then lower integer value servlet
will be loaded first.
A: We can use following code
snippet to get the actual path of the servlet in file system.
getServletContext().getRealPath(request.getServletPath())
A: We can use below code
snippet to get the servlet information in a servlet through servlet context
object.
getServletContext().getServerInfo()
A: File Upload and Download
and common tasks in a java web application. Unfortunately Servlet API doesn’t
provide easy methods to upload file on server, so we can use Apache FileUpload
jar to make our life easier.
Please read File Upload
Servlet post that provide all the necessary details with example program
to upload and download file using servlets.
A: If you work with database
connection a lot in your web application, its best to initialize it in a
servlet context listener and set it as a context attribute for other servlets
to use.
Integrating Log4j is also very
easy in web applications, all we need is a log4j configuration XML or property
file and then configure it in a servlet context listener.
A: We can
use request.getRemoteAddr() to get the client IP address in servlet.
A: Servlet Specs 3.0 was a
major release and some of the important features are:
.
Servlet Annotations: Prior to Servlet 3, all the servlet mapping and
it’s init parameters were used to defined in web.xml, this was not convenient
and more error prone when number of servlets are huge in an application.
Servlet 3 introduced use of java
annotations to define a servlet, filter and listener servlets and init
parameters. Some of the important Servlet API annotations are WebServlet,
WebInitParam, WebFilter and WebListener.
A.
Web Fragments: Prior to servlet specs 3.0, all the web application
configurations are required to be present in the web.xml that makes it
cluttered with lot of elements and chances of error increases. So servlet 3
specs introduced web fragments where we can have multiple modules in a single
web application, all these modules should have web-fragment.xml file in
META-INF directory. We can include all the elements of web.xml inside the
web-fragment.xml too. This helps us in dividing our web application into
separate modules that are included as JAR file in the web application lib
directory.
B.
Adding Web Components dynamically: We can use ServletContext object to
add servlets, filters and listeners programmatically. This helps us in building
dynamic system where we are loading a component only if we need it. These
methods are addServlet(), addFilter() and addListener() defined in the servlet
context object.
C.
Asynchronous Processing: Asynchronous support was added to delegate the
request processing to another thread rather than keeping the servlet thread
busy. It can increase the throughput performance of the application. This is an
advance topic and I recommend to read Async Servlet tutorial.
A: Servlet Container provides
different ways of login based servlet authentication:
.
HTTP Basic Authentication
A.
HTTP Digest Authentication
B.
HTTPS Authentication
C.
Form Based Login: A standard HTML form for authentication, advantage is
that we can change the login page layout as our application requirements rather
than using HTTP built-in login mechanisms.
A: We can configure our
servlet container to use SSL for message communication over the network. To
configure SSL on Tomcat, we need a digital certificate that can be created
using Java keytool for development environment. For production environment, you
should get the digital certificate from SSL certificate providers, for example,
Verisign or Entrust.
Java Servlet Interview Questions and Answers
ReplyDeletehttp://allinterviewquestionsandanswerspdf.blogspot.in/2016/06/top-25-java-servlet-interview-questions.html