0% found this document useful (0 votes)
10 views49 pages

JSP Servlets Hibernate

JSP (Java Server Pages) is a presentation layer technology that allows embedding Java code in HTML pages, compiled into servlets for dynamic web content generation. It supports implicit objects, custom tags, and tag libraries for extensibility and ease of use. JSP provides advantages over servlets by simplifying content generation and allowing for cleaner separation of presentation and business logic.

Uploaded by

shresth000ai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
10 views49 pages

JSP Servlets Hibernate

JSP (Java Server Pages) is a presentation layer technology that allows embedding Java code in HTML pages, compiled into servlets for dynamic web content generation. It supports implicit objects, custom tags, and tag libraries for extensibility and ease of use. JSP provides advantages over servlets by simplifying content generation and allowing for cleaner separation of presentation and business logic.

Uploaded by

shresth000ai
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 49

What is JSP and tell its uses?

JSP stands for Java Server Pages. It is a presentation layer technology independent
of platform. It comes with SUN's J2EE platforms. They are like HTML pages but with
Java code pieces embedded in them. They are saved with a .jsp extension. They are
compiled using JSP compiler in the background and generate a Servlet from the
page.

Explain Implicit objects in JSP.

Objects created by web container and contain information regarding a particular


request, application or page are called Implicit Objects. They are :

1. response

2. exception

3. application

4. request

5. session

6. page

7. out

8. config

9. pageContext

Is JSP technology extensible?


Yes, JSP is easily extensible by use and modification of tags, or custom actions,
encapsulated in tag libraries.

How is JSP better than Servlet technology?

JSP is a technology on the server's side to make content generation simple. They are
document centric, whereas servlets are programs. A Java server page can contain
fragments of Java program, which execute and instantiate Java classes. However,
they occur inside HTML template file. It provides the framework for development of a
Web Application.

How can you avoid scriptlet code in JSP?

JavaBeans or Custom Tags can be used instead of scriptlet code.

Explain the jspDestroy() method.

Whenever a JSP page is about to be destroyed, the container invokes the


jspDestroy() method from the javax.servlet.jsp.JspPage interface. Servlets destroy
methods are similar to it. It can be easily overridden to perform cleanup, like when
closing a database connection.

What is the need of tag library?


Tag library is a collection of custom tags. Custom actions helps recurring tasks will be
handled more easily they can be reused across more than one application and
increase productivity.

JSP tag libraries are used by Web application designers who can focus on
presentation issues rather than being concerned with how to access databases and
other enterprise services. Some of the popular tag libraries are Apache display tag
library and String tag library.

Why is _jspService() method starting with an '_' while other life cycle
methods do not?

JSP life cycle method are :-

jspInit(), jspDestroy() and _jspService(), bydefault whatever content we write in our


jsp page will go inside the _jspService() method by the container if again will try to
override this method. JSP compiler will give error but we can override other two life
cycle method as we have implementing this two in jsp so making this difference
container use _ in jspService() method and shows that we cant override this method.

Explain client and server side validation.

JavaScript is used for the client-side validation. It takes place within the browser.
JavaScript is used to submit the form data if validation is successful. Validation errors
require no extra network trip because form cannot be submitted.

Validation is also carried out in the server after submission. If validation fails, extra
network trip is required to resend the form to the client.
Can constructor be used instead of init(), to initialize servlet?

Yes, it is possible. But it is not preferred because init() was developed because earlier
Java versions could not invoke constructors with arguments dynamically. So they
could not assign a servletConfig. Today, however, servlet containers still call only no-
arg constructor. So there is no access to servletContext or servletConfig.

Which implicit object is not available in normal JSP pages?

JSP exception implicit object is not available in normal JSP pages and it's used in
JSP error pages only to catch the exception thrown by the JSP pages and provide
useful message to the client.

What are the benefits of PageContext implicit object?

JSP pageContext implicit object is instance


of javax.servlet.jsp.PageContext abstract class implementation. We can use
pageContext to get and set attributes with different scopes and to forward request to
other resources. pageContext object also hold reference to other implicit object.

This is the only object that is common in both JSP implicit objects and in JSP EL
implicit objects.

What are the types of JSTL tags?

There are five categorized into JSTL functions :-


1. Core Tags :- Core tags provide support for iteration, conditional logic, catch
exception, url, forward or redirect response etc.

2. Formatting and Localization Tags :- These tags are provided for formatting of
Numbers, Dates and i18n support through locales and resource bundles.

3. SQL Tags :- JSTL SQL Tags provide support for interaction with relational
databases such as Oracle, MySql etc.

4. XML Tags :- XML tags are used to work with XML documents such as parsing
XML, transforming XML data and XPath expressions evaluation.

5. JSTL Functions Tags :- JSTL tags provide a number of functions that we can use
to perform common operation, most of them are for String manipulation such as
String Concatenation, Split String etc.

What is JSP Custom Tag and what are it's components?

Sometimes JSP EL, Action Tags and JSTL tags are not enough and we might get
tempted to write java code to perform some operations in JSP page. Fortunately JSP
is extendable and we can create our own custom tags to perform certain operations.

We can create JSP Custom Tags with following components :-

(a). JSP Custom Tag Handler.

(b). Creating Tag Library Descriptor (TLD) File.

(c). Deployment Descriptor Configuration for TLD.

We can add custom tag library in JSP page using taglib directive and then use it.

What is difference between JspWriter and Servlet PrintWriter?


Difference between JspWriter and Servlet PrintWriter :-

PrintWriter :-

1. Does not support buffering.

2. Does not use BufferWriter internally.

3. Can create class of java.io.* package.

4. Its print (-) method does not throw IOException.

5. It is useful for servlet programming.

JspWriter :-

1. Supports buffering.

2. Uses BufferWriter, PrintWriter internally.

3. Abstract class of javax.servlet.jsp package.

4. Its print (-) method throw IOException.

5. It is the type of implicit object out in JSP

How can a thread safe JSP page be implemented?

It can be done by having them implemented by the SingleThreadModel Interface.


Add <%@page isThreadSafe="false" %> directive in the JSP page.

What is the Expression in JSP?

Expression tag is used to insert Java values directly in the output. Its syntax is <
%=expression%>.
It contains a scripting language expression that is evaluated, then converted to a
string, and then inserted where the expression comes in JSP file.

What are custom tags and why it is needed?

JSP tags are extended by creating a custom set of tags which is called as tag library
(taglib). The page which uses custom tags declares taglib and uniquely names,
defines and associates a tag prefix to differentiate the usage of those tags.

Explain the difference between RequestDispatcher and sendRedirect?


How JSP handles runtime exceptions?

1. RequestDispatcher redirects the server-side by requesting and responding the


objects. But sendRedirect redirects the Client-side with new request and responding
the objects.

2. JSP handles runtime exceptions by using the errorPage attribute of the page
directive.

3. By specifying ErrorPage = true the current page intended URL is redirected to the
JSP.

Explain the difference between ServletContext and PageContext. How


to create request.getRequestDispatcher () and
context.getRequestDispatcher()?

1. The ServletContext :- Provides the information about the container.

2. PageContext :- Provides the information about the Request.


3. To create request.getRequestDispatcher(path) we have to provide the relative path
of the resource. But to create context.getRequestDispatcher (path) we have to
provide the absolute path of the resource.

Explain the differences between <jsp:forward page = ... > and


response.sendRedirect(url).

1. The <jsp:forward page = ... > element propagates the request object containing
the client request information from one JSP file to another file.

2. The target file might be an HTML file, another JSP file, or any servlet, but it must be
in the same application context.response.sendRedirect(url).

3. The sendRedirect helps to send HTTP temporary redirect response to the


browser, and the browser helps to create a new request for going to the redirected
page

4. The response.sendRedirect helps to kill the session variables.

Why is it not a good practice to create HttpSessions in JSPs by


default?

By default, JSP files create HttpSessions. This is in compliance with J2EETM to


facilitate the use of JSP implicit objects, which can be referenced in JSP source and
tags without explicit declaration. HttpSession is one of those objects.

If you do not use HttpSession in your JSP files then you can save some performance
overhead with the following JSP page directive :-

<%@ page session="false"%>


Servlet Interview Questions:-

What is different between web server and application server?

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.

Which HTTP method is non-idempotent?

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.

What is the difference between GET and POST method?

1. GET is a safe method (idempotent) where POST is non-idempotent method.

2. 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.

3. 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.
4. GET is the default HTTP method whereas we need to specify method as POST
to send request with POST method.

5. Hyperlinks in a page uses GET method.

What is MIME Type?

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.

What is a web application ?

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.

What is a servlet?

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.

Most of the times, web applications are accessed using HTTP protocol and thats
why we mostly extend HttpServlet class.

What are the advantages of Servlet over CGI?

Servlet technology was introduced to overcome the shortcomings of CGI


technology.

1. 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,

2. 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.

3. 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.

4. Servlets are maintainable and learning curve is small because all we need to
take care is business logic for our application.
What are common tasks performed by Servlet Container?

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.

What is ServletConfig object?


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.

What is ServletContext object?

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-paramelement. 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.
What is difference between ServletConfig and ServletContext?

Some of the differences between ServletConfig and ServletContext are:

1. ServletConfig is a unique object per servlet whereas ServletContext is a unique


object for complete application.

2. 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.

3. We can't set attributes in ServletConfig object whereas we can set attributes in


ServletContext that other servlets can use in their implementation.

What is Request Dispatcher?

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:

1. void forward(ServletRequest request, ServletResponse response)


- forwards the request from a servlet to another resource (servlet, JSP file, or
HTML file) on the server.

2. 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.
What is difference between PrintWriter and ServletOutputStream?

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.

Can we get PrintWriter and ServletOutputStream both in a servlet?

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 get java.lang.IllegalStateException at runtime with
message as other method has already been called for this response.

How can we create deadlock situation in servlet?

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.

What is the use of servlet wrapper classes?


Servlet HTTP API provides two wrapper classes
- HttpServletRequestWrapper and HttpServletResponseWrapper.

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.

Do we need to override service() method?

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.

Is it good idea to create servlet constructor?

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.
What is difference between GenericServlet and HttpServlet?

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.

What is the inter-servlet communication?

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.

Are Servlets Thread Safe? How to achieve thread safety in servlets?

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.
What is servlet attributes and their scope?

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.

How do we call one servlet from another servlet?

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.

How can we invoke another servlet in a different application?

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.
What is difference between ServletResponse sendRedirect() and
RequestDispatcher forward() method?

1. 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.

2. forward() is handled internally by the container whereas sednRedirect() is


handled by browser.

3. We should use forward() when accessing resources in the same application


because it's faster than sendRedirect() method that required an extra network
call.

4. 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.

5. forward() can't be used to invoke a servlet in another context, we can only


use sendRedirect()in this case.

Why HttpServlet class is declared abstract?

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.
What are the phases of servlet life cycle?

We know that Servlet Container manages the life cycle of Servlet, there are four
phases of servlet life cycle.

1. 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.

2. 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.

3. 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.

4. Removal from Service - When container stops or we stop the application,


servlet container destroys the servlet class by invoking it's destroy() method.

What are life cycle methods of a servlet?

Servlet Life Cycle consists of three methods:

1. 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.

2. 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.
3. public void destroy() - This method is invoked once when servlet is unloaded
from memory.

Why we should override only no-agrs init() method.

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.

What is URL Encoding?

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.

What are different methods of session management in servlets?


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:

1. User Authentication

2. HTML Hidden Field

3. Cookies

4. URL Rewriting

5. Session Management API

What is URL Rewriting?

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.
How does Cookies work in Servlets?

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.

To notify an object in session when session is invalidated or timed-


out?

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.

What is the difference between encodeRedirectUrl and encodeURL?


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.

Why do we have servlet filters?

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:

1. Logging request parameters to log files.

2. Authentication and autherization of request for resources.

3. Formatting of request body or header before sending it to servlet.

4. Compressing the response data sent to the client.

5. Compressing the response data sent to the client.

What is the effective way to make sure all the servlets are accessible
only when user has a valid session?
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.

Why do we have servlet listeners?

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.

What is a deployment descriptor?

Deployment descriptor is a configuration file for the web application and it's name
is web.xmland 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.
How to make sure a servlet is loaded at the application startup?

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.

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.

How to get the actual path of servlet in server?

We can use following code snippet to get the actual path of the servlet in file
system.

getServletContext().getRealPath(request.getServletPath())

44. How to get the server information in a servlet?

We can use below code snippet to get the servlet information in a servlet through
servlet context object.
Hibernate Interview Questions:-

What is Hibernate?

Hibernate is an ORM (Object-relational Mapping) framework, which allows the


developer to concentrate on business logic by taking care of persistence of data
by itself. Java developer can write code using object and Hibernate can take care
of creating those object from data loaded from the database and saving update
back to the database.

Hibernate is one of the most widely used ORM tool for Java applications. It's used
a lot in enterprise applications for database operations. So I decided to write a
post about hibernate interview questions to brush up your knowledge before the
interview.

What is Java Persistence API (JPA)?


Java Persistence API (JPA) provides specification for managing the relational
data in applications. Current JPA version 2.1 was started in July 2011 as JSR
338. JPA 2.1 was approved as final on 22 May 2013.

JPA specifications is defined with annotations in javax.persistence package.


Using JPA annotation helps us in writing implementation independent code.

What are the important benefits of using Hibernate Framework?

Some of the important benefits of using hibernate framework are:

1. Hibernate eliminates all the boiler-plate code that comes with JDBC and takes
care of managing resources, so we can focus on business logic.

2. Hibernate framework provides support for XML as well as JPA annotations,


that makes our code implementation independent.

3. Hibernate provides a powerful query language (HQL) that is similar to SQL.


However, HQL is fully object-oriented and understands concepts like inheritance,
polymorphism and association.

4. Hibernate is an open source project from Red Hat Community and used
worldwide. This makes it a better choice than others because learning curve is
small and there are tons of online documentations and help is easily available in
forums.

5. Hibernate is easy to integrate with other Java EE frameworks, it's so popular


that Spring Framework provides built-in support for integrating hibernate with
Spring applications.

6. Hibernate supports lazy initialization using proxy objects and perform actual
database queries only when it's required.

7. Hibernate cache helps us in getting better performance.


8. For database vendor specific feature, hibernate is suitable because we can
also execute native sql queries.

What are the advantages of Hibernate over JDBC?

Some of the important advantages of Hibernate framework over JDBC are:

1. Hibernate removes a lot of boiler-plate code that comes with JDBC API, the
code looks more cleaner and readable.

2. Hibernate supports inheritance, associations and collections. These features


are not present with JDBC API.

3. Hibernate implicitly provides transaction management, in fact most of the


queries can't be executed outside transaction. In JDBC API, we need to write
code for transaction management using commit and rollback.

4. JDBC API throws SQLException that is a checked exception, so we need to


write a lot of try-catch block code. Most of the times it's redundant in every JDBC
call and used for transaction management. Hibernate wraps JDBC exceptions
and throw JDBCException orHibernateException un-checked exception, so we
don't need to write code to handle it. Hibernate built-in transaction management
removes the usage of try-catch blocks.

5. Hibernate Query Language (HQL) is more object oriented and close to java
programming language. For JDBC, we need to write native sql queries.

6. Hibernate supports caching that is better for performance, JDBC queries are
not cached hence performance is low.

7. Hibernate provide option through which we can create database tables too, for
JDBC tables must exist in the database.
8. Hibernate configuration helps us in using JDBC like connection as well as JNDI
DataSource for connection pool. This is very important feature in enterprise
application and completely missing in JDBC API.

9.Hibernate supports JPA annotations, so code is independent of implementation


and easily replaceable with other ORM tools. JDBC code is very tightly coupled
with the application. Name some important interfaces of Hibernate framework?

Name some important interfaces of Hibernate framework?

Some of the important interfaces of Hibernate framework are:

1. SessionFactory (org.hibernate.SessionFactory): SessionFactory is an


immutable thread-safe cache of compiled mappings for a single database. We
need to initialize SessionFactory once and then we can cache and reuse it.
SessionFactory instance is used to get the Session objects for database
operations.

2. Session (org.hibernate.Session): Session is a single-threaded, short-lived


object representing a conversation between the application and the persistent
store. It wraps JDBC java.sql.Connection and works as a factory for
org.hibernate.Transaction. We should open session only when it's required and
close it as soon as we are done using it. Session object is the interface between
java application code and hibernate framework and provide methods for CRUD
operations.

3. Transaction (org.hibernate.Transaction): Transaction is a single-threaded,


short-lived object used by the application to specify atomic units of work. It
abstracts the application from the underlying JDBC or JTA transaction.
A org.hibernate.Session might span multiple org.hibernate.Transaction in
some cases.
What is hibernate configuration file?

Hibernate configuration file contains database specific configurations and used to


initialize SessionFactory. We provide database credentials or JNDI resource
information in the hibernate configuration xml file.

Some other important parts of hibernate configuration file is Dialect information,


so that hibernate knows the database type and mapping file or class details.

What is hibernate mapping file?

Hibernate mapping file is used to define the entity bean fields and database table
column mappings. We know that JPA annotations can be used for mapping but
sometimes XML mapping file comes handy when we are using third party classes
and we can't use annotations.

Name some important annotations used for Hibernate mapping?

Hibernate supports JPA annotations and it has some other annotations


in org.hibernate.annotations package. Some of the important JPA and
hibernate annotations used are:

1. javax.persistence.Entity: Used with model classes to specify that they are


entity beans.

2. javax.persistence.Table: Used with entity beans to define the corresponding


table name in database.
3. javax.persistence.Access: Used to define the access type, either field or
property. Default value is field and if you want hibernate to use getter/setter
methods then you need to set it to property.

4. javax.persistence.Id: Used to define the primary key in the entity bean.

5. javax.persistence.EmbeddedId: Used to define composite primary key in the


entity bean.

6.javax.persistence.Column: Used to define the column name in database


table.

7. javax.persistence.GeneratedValue: Used to define the strategy to be used


for generation of primary key. Used in conjunction
with javax.persistence.GenerationType enum.

8. javax.persistence.OneToOne: Used to define the one-to-one mapping


between two entity beans. We have other similar annotations as OneToMany,
ManyToOne and ManyToMany

9. org.hibernate.annotations.Cascade: Used to define the cascading between


two entity beans, used with mappings. It works in conjunction
with org.hibernate.annotations.CascadeType

10. javax.persistence.PrimaryKeyJoinColumn: Used to define the property for


foreign key. Used
with org.hibernate.annotations.GenericGenerator and org.hibernate.annotati
ons.Parameter

What is Hibernate SessionFactory and how to configure it?

SessionFactory is the factory class used to get the Session objects.


SessionFactory is responsible to read the hibernate configuration parameters and
connect to the database and provide Session objects. Usually an application has
a single SessionFactory instance and threads servicing client requests obtain
Session instances from this factory.

The internal state of a SessionFactory is immutable. Once it is created this


internal state is set. This internal state includes all of the metadata about
Object/Relational Mapping.

SessionFactory also provide methods to get the Class metadata and Statistics
instance to get the stats of query executions, second level cache details etc.

What is Hibernate Session and how to get it?

Hibernate Session is the interface between java application layer and hibernate.
This is the core interface used to perform database operations. Lifecycle of a
session is bound by the beginning and end of a transaction.

Session provide methods to perform create, read, update and delete operations
for a persistent object. We can execute HQL queries, SQL native queries and
create criteria using Session object.

Hibernate Session is thread safe?

Hibernate Session object is not thread safe, every thread should get it's own
session instance and close it after it's work is finished.

What is difference between openSession and getCurrentSession?


Hibernate SessionFactory getCurrentSession() method returns the session bound
to the context. But for this to work, we need to configure it in hibernate
configuration file. Since this session object belongs to the hibernate context, we
don't need to close it. Once the session factory is closed, this session object gets
closed.
<property
name="hibernate.current_session_context_class">thread</property>

Hibernate SessionFactory openSession() method always opens a new session.


We should close this session object once we are done with all the database
operations. We should open a new session for each request in multi-threaded
environment.

What is difference between Hibernate Session get() and load()


method?

Hibernate session comes with different methods to load data from database. get
and load are most used methods, at first look they seems similar but there are
some differences between them.

1. get() loads the data as soon as it's called whereas load() returns a proxy
object and loads data only when it's actually required, so load() is better because
it support lazy loading.

2. Since load() throws exception when data is not found, we should use it only
when we know data exists.

3. We should use get() when we want to make sure data exists in the database.

What is hibernate caching? Explain Hibernate first level cache?


As the name suggests, hibernate caches query data to make our application
faster. Hibernate Cache can be very useful in gaining fast application
performance if used correctly. The idea behind cache is to reduce the number of
database queries, hence reducing the throughput time of the application.

Hibernate first level cache is associated with the Session object. Hibernate first
level cache is enabled by default and there is no way to disable it. However
hibernate provides methods through which we can delete selected objects from
the cache or clear the cache completely.

Any object cached in a session will not be visible to other sessions and when the
session is closed, all the cached objects will also be lost.

What are different states of an entity bean?

An entity bean instance can exist is one of the three states.

1. Transient: When an object is never persisted or associated with any session,


it's in transient state. Transient instances may be made persistent by calling
save(), persist() or saveOrUpdate().Persistent instances may be made transient
by calling delete().

2. Persistent: When an object is associated with a unique session, it's in


persistent state. Any instance returned by a get() or load() method is persistent.

3. Detached: When an object is previously persistent but not associated with any
session, it's in detached state. Detached instances may be made persistent by
calling update(), saveOrUpdate(), lock() or replicate(). The state of a transient
or detached instance may also be made persistent as a new persistent instance
by calling merge().
What is use of Hibernate Session merge() call?

Hibernate merge can be used to update existing values, however this method
create a copy from the passed entity object and return it. The returned object is
part of persistent context and tracked for any changes, passed object is not
tracked.

What is difference between Hibernate save(), saveOrUpdate() and


persist() methods?

Hibernate save can be used to save entity to database. Problem with save() is
that it can be invoked without a transaction and if we have mapping entities, then
only the primary object gets saved causing data inconsistencies. Also save
returns the generated id immediately.

Hibernate persist is similar to save with transaction. I feel it's better than save
because we can't use it outside the boundary of transaction, so all the object
mappings are preserved. Also persist doesn't return the generated id
immediately, so data persistence happens when needed.

Hibernate saveOrUpdate results into insert or update queries based on the


provided data. If the data is present in the database, update query is executed.
We can use saveOrUpdate() without transaction also, but again you will face the
issues with mapped objects not getting saved if session is not flushed.

What will happen if we don't have no-args constructor in Entity bean?

Hibernate uses Reflection API to create instance of Entity beans, usually when
you call get() or load() methods. The method Class.newInstance() is used for
this and it requires no-args constructor.
So if you won't have no-args constructor in entity beans, hibernate will fail to
instantiate it and you will get HibernateException.

What is difference between sorted collection and ordered collection,


which one is better?

When we use Collection API sorting algorithms to sort a collection, it's called
sorted list. For small collections, it's not much of an overhead but for larger
collections it can lead to slow performance and OutOfMemory errors. Also the
entity beans should implement Comparable or Comparator interface for it to work,

If we are using Hibernate framework to load collection data from database, we


can use it's Criteria API to use "order by" clause to get ordered list. Below code
snippet shows you how to get it.

List<Employee> empList = session.createCriteria(Employee.class)


.addOrder(Order.desc("id")).list();

Ordered list is better than sorted list because the actual sorting is done at
database level, that is fast and doesn't cause memory issues.

What are the collection types in Hibernate?

There are five collection types in hibernate used for one-to-many relationship
mappings.

1. Bag

2. Set

3. List
4. Array

5. Map

How to implement Joins in Hibernate?

There are various ways to implement joins in hibernate.

1. Using associations such as one-to-one, one-to-many etc.

2. Using JOIN in the HQL query. There is another form "join fetch" to load
associated data simultaneously, no lazy loading.

3. We can fire native sql query and use join keyword.

Why we should not make Entity Class final?

Hibernate use proxy classes for lazy loading of data, only when it's needed. This
is done by extending the entity bean, if the entity bean will be final then lazy
loading will not be possible, hence low performance.

What is HQL and what are it's benefits?

Hibernate Framework comes with a powerful object-oriented query language -


Hibernate Query Language (HQL). It's very similar to SQL except that we use
Objects instead of table names, that makes it more close to object oriented
programming.

Hibernate query language is case-insensitive except for java class and variable
names. So SeLeCT is the same as sELEct is the same as SELECT,
but com.journaldev.model.Employee is not same
as com.journaldev.model.EMPLOYEE.

The HQL queries are cached but we should avoid it as much as possible,
otherwise we will have to take care of associations. However it's a better choice
than native sql query because of Object-Oriented approach.

What is Query Cache in Hibernate?

Hibernate implements a cache region for queries resultset that integrates closely
with the hibernate second-level cache.

This is an optional feature and requires additional steps in code. This is only
useful for queries that are run frequently with the same parameters. First of all we
need to configure below property in hibernate configuration file.

<property name="hibernate.cache.use_query_cache">true</property>

And in code, we need to use setCacheable(true) method of Query, quick example


looks like below.

Query query = session.createQuery("from Employee");


query.setCacheable(true);
query.setCacheRegion("ALL_EMP");

Can we execute native sql query in hibernate?

Hibernate provide option to execute native SQL queries through the use of
SQLQuery object.

For normal scenarios, it is however not the recommended approach because we


loose benefits related to hibernate association and hibernate first level caching.
What is the benefit of native sql query support in hibernate?

Native SQL Query comes handy when we want to execute database specific
queries that are not supported by Hibernate API such as query hints or the
CONNECT keyword in Oracle Database.

What is Named SQL Query?

Hibernate provides Named Query that we can define at a central location and use
them anywhere in the code. We can created named queries for both HQL and
Native SQL.

Hibernate Named Queries can be defined in Hibernate mapping files or through


the use of JPA annotations @NamedQuery and @NamedNativeQuery.

What are the benefits of Named SQL Query?

Hibernate Named Query helps us in grouping queries at a central location rather


than letting them scattered all over the code.

Hibernate Named Query syntax is checked when the hibernate session factory is
created, thus making the application fail fast in case of any error in the named
queries.

Hibernate Named Query is global, means once defined it can be used throughout
the application.

However one of the major disadvantage of Named query is that it's hard to debug,
because we need to find out the location where it's defined.
What is the benefit of Hibernate Criteria API?

Hibernate provides Criteria API that is more object oriented for querying the
database and getting results. We can't use Criteria to run update or delete
queries or any DDL statements. It's only used to fetch the results from the
database using more object oriented approach.

Some of the common usage of Criteria API are:

1. Criteria API provides Projection that we can use for aggregate functions such
as sum(), min(), max() etc.

2. Criteria API can be used with ProjectionList to fetch selected columns only.

3. Criteria API can be used for join queries by joining multiple tables, useful
methods arecreateAlias(), setFetchMode() and setProjection()

4. Criteria API can be used for fetching results with conditions, useful methods
are add() where we can add Restrictions.

5. Criteria API provides addOrder() method that we can use for ordering the
results.

How to log hibernate generated sql queries in log files?

We can set below property for hibernate configuration to log SQL queries.

<property name="hibernate.show_sql">true</property>

However we should use it only in Development or Testing environment and turn it


off in production environment.
What is Hibernate Proxy and how it helps in lazy loading?

Hibernate uses proxy object to support lazy loading. Basically when you load data
from tables, hibernate doesn't load all the mapped objects.

As soon as you reference a child or lookup object via getter methods, if the linked
entity is not in the session cache, then the proxy code will go to the database and
load the linked object.

It uses javassist to effectively and dynamically generate sub-classed


implementations of your entity objects.

How to implement relationships in hibernate?

We can easily implement one-to-one, one-to-many and many-to-many


relationships in hibernate. It can be done using JPA annotations as well as XML
based configurations. For better understanding, you should go through following
tutorials.

1. Hibernate One to One Mapping

2. Hibernate One to Many Mapping

3. Hibernate Many to Many Mapping

How transaction management works in Hibernate?

Transaction management is very easy in hibernate because most of the


operations are not permitted outside of a transaction. So after getting the session
from SessionFactory, we can call session beginTransaction() to start the
transaction.
This method returns the Transaction reference that we can use later on to either
commit or rollback the transaction.

Overall hibernate transaction management is better than JDBC transaction


management because we don't need to rely on exceptions for rollback. Any
exception thrown by session methods automatically rollback the transaction.

What is cascading and what are different types of cascading?

When we have relationship between entities, then we need to define how the
different operations will affect the other entity. This is done by cascading and
there are different types of it.

1. None: No Cascading, it's not a type but when we don't define any cascading
then no operations in parent affects the child.

2. ALL: Cascades save, delete, update, evict, lock, replicate, merge, persist.
Basically everything

3. SAVE_UPDATE: Cascades save and update, available only in hibernate.

4. DELETE: Corresponds to the Hibernate native DELETE action, only in


hibernate.

5. DETATCH, MERGE, PERSIST, REFRESH and REMOVE- for similar


operations

6. LOCK: Corresponds to the Hibernate native LOCK action.

7. REPLICATE: Corresponds to the Hibernate native REPLICATE action.


How to use application server JNDI DataSource with Hibernate
framework?

For web applications, it's always best to allow servlet container to manage the
connection pool. That's why we define JNDI resource for DataSource and we can
use it in the web application.

It's very easy to use in Hibernate, all we need is to remove all the database
specific properties and use below property to provide the JNDI DataSource name.

<property
name="hibernate.connection.datasource">java:comp/env/jdbc/MyLocalDB<
/property>

Which design patterns are used in Hibernate framework?

Some of the design patterns used in Hibernate Framework are:

1. Domain Model Pattern - An object model of the domain that incorporates both
behavior and data.

2. Data Mapper - A layer of Mappers that moves data between objects and a
database while keeping them independent of each other and the mapper itself.

3. Proxy Pattern for lazy loading

4. Factory pattern in SessionFactory

What is Hibernate Validator Framework?


Data validation is integral part of any application. You will find data validation at
presentation layer with the use of Javascript, then at the server side code before
processing it. Also data validation occurs before persisting it, to make sure it
follows the correct format.

Validation is a cross cutting task, so we should try to keep it apart from our
business logic. That's why JSR303 and JSR349 provides specification for
validating a bean by using annotations. Hibernate Validator provides the
reference implementation of both these bean validation specs.

What are the advantages of Hibernate over JDBC?

Apart from Persistence i.e. saving and loading data from Database, Hibernate
also provides following benefits

1. Caching

2. Lazy Loading

3. Relationship management and provides code for mapping an object to the data

4. The developer is free from writing code to load/store data into the database.

What is N+1 SELECT problem in Hibernate?

The N+1 SELECT problem is a result of lazy loading and load on demand
fetching strategy. In this case, Hibernate ends up executing N+1 SQL queries to
populate a collection of N elements.

For example, if you have a List of N Items where each Item has a dependency on
a collection of Bid object. Now if you want to find the highest bid for each item
then Hibernate will fire 1 query to load all items and N subsequent queries to load
Bid for each item.

So in order to find the highest bid for each item your application end up firing N+1
queries.

What are some strategies to solve the N+1 SELECT problem in


Hibernate?

This is the follow-up question of previous Hibernate interview question. If you


answer the last query correctly then you would be most likely asked this one.
Here are some strategies to solve the N+1 problem:

1. pre-fetching in batches, this will reduce N+1 problem to N/K + 1 problem


where K is size of batch

2. subselect fetching strategy

3. disabling lazy loading

What is different between Session and Sessionfactory in Hibernate?

This is another popular Hibernate interview question, mostly at a telephonic round


of interviews.

The main difference between Session and SessionFactory is that former is a


single-threaded, short-lived object while later is Immutable and shared by all
Session.

It also lives until the Hibernate is running. Another difference between Session
and SessionFactory is that former provides first level cache while SessionFactory
provides the Second level cache.
When do you use merge() and update() in Hibernate?

You should use update() if you are sure that the Hibernate session does not
contain an already persistent instance with the same id and use merge() if you
want to merge your modifications at any time without considering the state of the
session.

The difference between transient, persistent and detached in


Hibernate?

The main difference between sorted and ordered collection is that sorted
collection sort the data in JVM's heap memory using Java's collection framework
sorting methods while ordered collection is sorted using order by clause in the
database itself.

A sorted collection is more suited for small dataset but for a large dataset, it's
better to use ordered collection to avoid OutOfMemoryError in Java application.

Which cache is used by Session Object in Hibernate? First level or


second level cache?

A Session object uses the first-level cache. As I told before the second level
cache is used at SessionFactory level.

This is a good question to check if Candidate has been working in hibernate or


not. If he has not worked in Hibernate from a long time then he would get
confused in this question.
What is lazy fetching in Hibernate?

In Hibernate Lazy fetching is associated with child objects loading for its parents.
Through Hibernate mapping file (.hbm.xml) you can specified the selection of
loading child objects. By default Hibernate does not load child objects.

Lazy=true means not to load the child objects.

What is the process of communication between Hibernate with


RDBMS?

To create the communication between the Hibernate and RDBMS there are some
steps that are involved in the process. These are as follows :

1. To create the communication first loading of the Hibernate configuration file


takes place. When this file is loaded then a configuration object gets created. This
object loads the .hbm files used to map the objects automatically.

2. A session gets created by taking the interface from the SessionFactory from
the configuration object.

3. A HQL query is being creation after taking the session from the session factory
and starting the session for the user.

4. In the end an execution of the query gets listed that contain the Java Objects of
the file. This allows the communication being done between different objects of
Hibernate and RDBMS.

You might also like