AJAVAQAKEYS
AJAVAQAKEYS
Question Bank: Part - A ( 5x1=5 ) Part – B (5x7=35) Part – C (1x10=10) Total Marks:50
Unit-I: JDBC: Introduction to JDBC, JDBC Driver types, JDBC database connections, JDBC Statements,
PreparedStatement, CallableStatement, ResultSet, JDBC data types, transactions, Batch Processing,
Stored Procedure
Part - A
Part - B
Part - C
1
Unit-2: Servlet: Servlet structure, Life Cycle of a Servlet, Using Tomcat for Servlet Development, The
Servlet API, Handling Client Request: Form data, Handling client HTTP request and server HTTP
Response, HTTP status codes, Handling Cookies, Session tracking, Database Access
Part - A
1. What is servlet?
2. List out the two package used for servlet creation
3. Why use the session tracking in web application?
4. What is HTTP?
5. What is RMI?
6. What is CORBA?
7. What is XML?
8. What is CGI?
9. What is Web server?
10. What is Browser?
11. What is Cookies?
Part - B
2
Unit-3: JSP: Overview of JSP Technology, Need of JSP, Advantages of JSP, Life Cycle of JSP Page, JSP
Processing, JSP Application Design with MVC, Setting Up the JSP Environment, JSP Directives, JSP
Action, JSP Implicit Objects, JSP Form Processing, JSP Session and Cookies Handling, JSP Session
Tracking JSP Database Access, JSP Standard Tag Libraries, JSP Custom Tag, JSP Expression Language,
JSP Exception Handling
Part - A
1. What is JSP?
2. What is MVC?
3. What is ASP?
4. What is Model Layer?
5. What is View Layer?
6. What is Controller Layer?
7. What is Implicit Objects?
Part - B
Part - C
3
Unit -4: Hibernate Introduction, Hibernate Configuration, Hibernate Concepts, Hibernate
O-R Mapping, Manipulating and Querying, Hibernate Query Language, Criteria Queries,
Native SQL, Transaction and Concurrency
Part - A
1. What is Hibernate?
2. What is ORM?
3. What is HQL?
4. Define advantage of HQL
5. What is Criteria queries?
6. Define Native SQL.
7. What is Java Persistence?
Part - B
Part - C
UNIT- 5 Spring Framework: Spring Basics, Spring Container, Spring AOP, Spring Data Access,
Spring O-R/mapping, Spring Transaction Management, Spring Remoting and Enterprise
Services, Spring Web MVC Framework, Securing Spring Application.
Part - A
1. What is spring?
2. What is POJO?
3. What is IoC?
4. What is AOP?
5. What is Spring Security?
6. What is java beans?
7. What is Dependency Injection?
Part - B
4
5. Describe the Spring Remoting technologies
6. Explain the Spring Enterprise Services.
7. Explain the Spring Web MVC Framework design
8. What are the benefits of using Spring Security Application?
Part - C
5
Question and Answer keys:
Unit-I: JDBC: Introduction to JDBC, JDBC Driver types, JDBC database connections, JDBC Statements,
PreparedStatement, CallableStatement, ResultSet, JDBC data types, transactions, Batch Processing,
Stored Procedure
Part - A
6
Part - B
7
3. Define JDBC Concept with example.
Components of JDBC : There are generally four main components of JDBC through
which it can interact with a database. They are as mentioned below:
1. JDBC API: It provides various methods and interfaces for easy communication with the
database. It provides two packages as follows, which contain the java SE and Java EE
platforms to exhibit WORA(write once run anywhere) capabilities.
java.sql.*;
It also provides a standard to connect a database to a client application.
8
2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver converts JDBC method
calls into native calls of the database API. It is not written entirely in java.
4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database protocol. That is why it
is known as thin driver. It is fully written in Java language.
9
5. Explain the JDBC data types.
The JDBC driver converts the Java data type to the appropriate JDBC type, before sending it to the
database. It uses a default mapping for most data types. For example, a Java int is converted to an
SQL INTEGER. Default mappings were created to provide consistency between drivers.
The following table summarizes the default JDBC data type that the Java data type is converted to,
when you call the setXXX() method of the PreparedStatement or CallableStatement object or the
ResultSet.updateXXX() method. Example
10
6. Explain the properties of transaction managements
Every transaction follows some transaction properties these are called ACID
properties
ACID
Atomicity: Atomicity of a transaction is nothing but in a transaction either all operations
can be done or all operation can be undone, but some operations are done and some
operation are undone should not occure.
Consistency: Consistency means, after a transaction completed with successful, the data in
the data store should be a reliable data this reliable data is also called as consistent data.
Isolation: Isolation means, if two transaction are going on same data then one transaction
will not disturb another transaction.
Durability: Durability means, after a transaction is completed the data in the data store will
be permanent until another transaction is going to be performed on that data.
11
If transfer money from first account to second account belongs to different
banks then the transaction is a global transaction.
• Note: Jdbc technology perform only local transactions. For global
transaction in java we need either EJB or spring framework.
Useful Connection Methods (for Transactions
• getAutoCommit/setAutoCommit
– By default, a connection is set to auto-commit
– Retrieves or sets the auto-commit mode
• commit
– Force all changes since the last call to commit to become permanent
– Any database locks currently held by this Connection object are
released
• rollback
– Drops all changes since the previous call to commit
– Releases any database locks held by this Connection object
Main Advantage of Transaction Mangaement: Fast performance It makes the performance fast
because database is hit at the time of commit.
The following table provides a summary of each interface's purpose to decide on the
interface to use.
12
9. Explain the Batch Processing in JDBC with example.
Batch Processing allows you to group related SQL statements into a batch and submit them with
one call to the database. When you send several SQL statements to the database at once, you reduce
the amount of communication overhead, thereby improving performance.Batch processing in
JDBC. It follows following steps:
13
Batch is a group of SQL statements that are executed at one time by SQL Server. These
statements are sent to SQL Server by a program, such as the Query Analyzer. The opposite
of a batch query is a single query, containing only one SQL statement.
5 and 6 Execute Batch and Close Connection
int[] executeBatch() The executeBatch() method begins the execution of all the statements
grouped together . The method returns an integer array, and each element of the array
represents the updated count for the respective update statement.
Part - C
Description:
Application: It is a java applet or a servlet that communicates with a data source.
The JDBC API: The JDBC API allows Java programs to execute SQL statements and retrieve results.
Some of the important classes and interfaces defined in JDBC API are as follows:
DriverManager: It plays an important role in the JDBC architecture. It uses some database-specific
drivers to effectively connect enterprise applications to databases.
JDBC drivers: To communicate with a data source through JDBC, you need a JDBC driver that
intelligently communicates with the respective data source.
14
2. Write a java program to access the MySql database
Create a Java JDBC program to access the Mysql database:
Mysql database:
mysql> use college
Database changed
mysql> desc mca;
Mysql>create table mca(S_id int(5)primary key,Sname varchar(20),DOB date,Address
varchar(20),Email_id varchar(20));
Mysql>insert into mca values(1001,”Raja”,’2023-07-09’,”Chennai”,”[email protected]”);
Mysql>insert into mca values(1001,”John”,’2023-07-10’,”Mangalore”,”[email protected]”);
System.out.print(rs.getString(i));
System.out.println("|");
-
System.out.println();
-
-
catch (SQLException ex) ,
System.out.println(ex.getMessage());
-
15
-
-
Output:
run:
1001|
Raja|
2023-07-09|
Chennai|
[email protected]|
1002|
John|
2023-07-10|
Mangalore|
[email protected]|
BUILD SUCCESSFUL (total time: 0 seconds)
Result: Thus program has been successfully executed.
The forName() method of Class class is used to register the driver class. This method is
used to dynamically load the driver class.
Syntax of forName() method
public static void forName(String className)throws ClassNotFoundException
Note: Since JDBC 4.0, explicitly registering the driver is optional. We just need to put vender's
Jar in the classpath, and then JDBC driver manager can detect and load the driver automatically.
Example to register the OracleDriver class
Here, Java program is loading oracle driver to esteblish database connection.
Class.forName("oracle.jdbc.driver.OracleDriver");
2) Create the connection object
The getConnection() method of DriverManager class is used to establish connection with the
database.
Syntax of getConnection() method
1) public static Connection getConnection(String url)throws SQLException
16
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle database
Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system","password");
3) Create the Statement object
The createStatement() method of Connection interface is used to create statement. The object of
statement is responsible to execute queries with the database.
Statement stmt=con.createStatement();
The executeQuery() method of Statement interface is used to execute queries to the database.
This method returns the object of ResultSet that can be used to get all the records of a table.
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
By closing connection object statement and ResultSet will be closed automatically. The close()
method of Connection interface is used to close the connection.
con.close();
Note: Since Java 7, JDBC has ability to use try-with-resources statement to automatically close
resources of type Connection, ResultSet, and Statement.
17
Unit-2: Servlet: Servlet structure, Life Cycle of a Servlet, Using Tomcat for Servlet Development, The
Servlet API, Handling Client Request: Form data, Handling client HTTP request and server HTTP
Response, HTTP status codes, Handling Cookies, Session tracking, Database Access
Part - A
1. What is servlet?
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. Although
servlets can respond to any type of request, they are commonly used to extend the applications
hosted by web servers.
2. List out the two package used for servlet creation
There are two main packages which this chapter makes use of: javax. servlet and javax. servlet.
http. The javax.servlet package provides all of the base classes and interfaces defining both what a
Servlet is, and how it interacts with the Web server that is running it.The javax.servlet.http package
provides classes specific to handling HTTP requests. It provides the HttpServlet class used in this
chapter, which implements the appropriate interfaces from javax.servlet.
3. Why use the session tracking in web application?
To recognize the user It is used to recognize the particular user. Session Tracking is a way to
maintain state (data) of an user. It is also known as session management in servlet.
4. What is HTTP?
Hypertext Transfer Protocol (HTTP) is a method for encoding and transporting information
between a client (such as a web browser) and a web server. HTTP is the primary protocol for
transmission of information across the Internet
5. What is RMI?
Remote Method Invocation (RMI) is a Java technology in which an object running in Java Virtual
Machine (JVM) could be invoked from another object running in a different JVM. The technology
provides a remote access of objects in Java programming language. The RMI technology consists of a
server and a client.
6. What is CORBA?
CORBA stands for Common Object Request Broker Architecture. The original idea was to create a
single universal standard for how objects across different platforms, programming languages, and
network protocols can communicate with each other in a seamless manner.
7. What is XML?
Extensible Markup Language (XML) lets you define and store data in a shareable manner. XML
supports information exchange between computer systems such as websites, databases, and third-
party applications.
8. What is CGI?
The Common Gateway Interface (CGI) standard is a data-passing specification used when a Web
server must send or receive data from an application such as a database. A CGI script passes the
request from the Web server to a database, gets the output and returns it to the Web client.
A web server is software and hardware that uses HTTP (Hypertext Transfer Protocol) and other
protocols to respond to client requests made over the World Wide Web. The main job of a web
server is to display website content through storing, processing and delivering webpages to users.
18
10. What is Browser?
A software application used to access information on the World Wide Web is called a Web
Browser. When a user requests some information, the web browser fetches the data from a web
server and then displays the webpage on the user’s screen.
Part - B
19
show the servlet tasks
A servlet life cycle can be defined as the entire process from its creation till the destruction. The
following are the paths followed by a servlet The servlet is initialized by calling the init () method.
The servlet calls service() method to process a client's request. The servlet is terminated by calling
the destroy() method. Finally, servlet is garbage collected by the garbage collector of the JVM.
Now let us discuss the life cycle methods in details.
The init() method :
The init method is designed to be called only once. It is called when the servlet is first created, and
not called again for each user request. So, it is used for one-time initializations, just as with the init
method of applets. The servlet is normally created when a user first invokes a URL corresponding to
the servlet, but you can also specify that the servlet be loaded when the server is first started. When
a user invokes a servlet, a single instance of each servlet gets created, with each user request
resulting in a new thread that is handed off to doGet or doPost as appropriate. The init() method
simply creates or loads some data that will be used throughout the life of the servlet.
The init method definition
looks like this:
public void init() throws ServletException ,
// Initialization code...
-
The service() method:
The service() method is the main method to perform the actual task. The servlet container(i.e. web
server) calls the service() method to handle requests coming from the client(browsers) and to write
the formatted response back to the client. Each time the server receives a request for a servlet, the
server spawns a new thread and calls service. The service() method checks the HTTP request type
(GET, POST, PUT, DELETE, etc.) and calls doGet, doPost, doPut, doDelete, etc. methods as appropriate.
Here is the signature of this method:
public void service(ServletRequest request,
20
ServletResponse response)
throws ServletException, IOException,
The service () method is called by the container and service method invokes doGet, doPost, doPut,
doDelete, etc. methods as appropriate. So you have nothing to do with service() method but you
override either doGet() or doPost() depending on what type of request you receive from the client.
The doGet() and doPost() are most frequently used methods within each service request. Here
is the signature of these two methods
Sun Microsystem defines a unique directory structure that must be followed to create a servlet
application. Create the above directory structure inside Apache-Tomcat\webapps directory. All
HTML, static files(images, css etc) are kept directly under Web application folder. While all the Servlet
classes are kept inside classesfolder.
21
Servlet directory structure
The Root Directory: The root directory of you web application can have any name. In the above
example the root directory name is mywebapp .Under the root directory, you can put all files that
should be accessible in your web application.
The WEB-INF Directory :The WEB-INF directory is located just below the web app root directory. This
directory is a meta information directory. Files stored here are not supposed to be accessible from a
browser (although your web app can access them internally, in your code).
web.xml :The web.xml file contains information about the web application, which is used by the Java
web server / servlet container in order to properly deploy and execute the web application.
classes Directory : The classes directory contains all compiled Java classes that are part of your web
application. The classes should be located in a directory structure matching their package structure.
lib folder :The lib directory contains all JAR files used by your web application. This directory most
often contains any third party libraries that your application is using.
5. Explain types of session techniques.
Basically there are four techniques which can be used to identify a user session.
1. Cookies, 2. Hidden Fields,3. URL Rewriting,4. Session Tracking API
Cookies , Hidden Fields and URL rewriting involves sending a unique identifier with each request and
servlets determines the user session based on the identifier. Session API uses the other three
techniques internally and provides a session tracking in much convenient and stable way.
1.Cookies Cookie is a key value pair of information, sent by the server to the browser and then
browser sends back this identifier to the server with every request there on.
There are two types of cookies:
Session cookies - are temporary cookies and are deleted as soon as user closes the browser.
The next time user visits the same website, server will treat it as a new client as cookies are
already deleted.
Persistent cookies - remains on hard drive until we delete them or they expire.
If cookie is associated with the client request, server will associate it with corresponding user
session otherwise will create a new unique cookie and send back with response.
Simple code snippet to create a cookie with name sessionId with a unique value for each
client:
Cookie cookie = new Cookie(“sessionID”, “some unique value”);
response.addCookie(cookie);
22
User can disable cookie support in a browser and in that case server will not be able to
identify the user so this is the major disadvantage of this approach.
2.Hidden Field: Hidden fields are the input fields which are not displayed on the page but its
value is sent to the servlet as other input fields. For example
<input type=”hidden” name=”sessionId” value=”unique value”/>
is a hidden form field which will not displayed to the user but its value will be send to the server and
can be retrieved using request.getParameter(“sessionId”) in servlet.
As we cannot hardcode the value of hidden field created for session tracking purpose, which
means we cannot use this approach for static pages like HTML. In short with this approach, HTML
pages cannot participate in session tracking with this approach.Another example will be any get
requests like clicking of any link so above two are the major disadvantages of this approach.
3.URL Rewriting: URL Rewriting is the approach in which a session (unique) identifier gets appended
with each request URL so server can identify the user session. For example if we apply URL rewriting
on http://localhost:8080/HelloWorld/SourceServlet , it will become something like
http://localhost:8080/HelloWorld/SourceServlet?jSessionId=XYZ where jSessionId=XYZ is the
attached session identifier and value XYZ will be used by server to identify the user session.
There are several advantages of URL rewriting over above discussed approaches like it is browser
independent and even if user’s browser does not support cookie or in case user has disabled
cookies, this approach will work. Another advantage is , we need not to submit extra hidden
parameter.As other approaches, this approach also has some disadvantages like we need to
regenerate every url to append session identifier and this need to keep track of this identifier until
the conversation completes.
4.Session Tracking API:Servlets provide a convenient and stable session-tracking solution using the
HttpSession API. This interface is built on the top of above discussed approaches.Session tracking in
servlet is very simple and it involves following steps.
Get the associated session object (HttpSession) using request.getSession().
To get the specific value out of session object, call getAttribute(String) on the HttpSession object.
To store any information in a session call setAttribute(key,object) on a session object.
To remove the session data , call removeAttribute(key) to discard a object with a given key.
To invalidate the session, call invalidate() on session object. This is used to logout the logged in
user.
23
mysql> INSERT INTO Employees VALUES (102, 30, 'Zaid', 'Khan');
Query OK, 1 row affected (0.00 sec)
mysql> INSERT INTO Employees VALUES (103, 28, 'Sumit', 'Mittal');
Query OK, 1 row affected (0.00 sec)
mysql>
24
String last = rs.getString("last");
//Display values
out.println("ID: " + id + "<br>");
out.println(", Age: " + age + "<br>");
out.println(", First: " + first + "<br>");
out.println(", Last: " + last + "<br>");
-
out.println("</body></html>");
// Clean-up environment
rs.close();
stmt.close();
conn.close();
- catch(SQLException se) ,
//Handle errors for JDBC
se.printStackTrace();
- catch(Exception e) ,
//Handle errors for Class.forName
e.printStackTrace();
- finally ,
//finally block used to close resources
try ,
if(stmt!=null)
stmt.close();
- catch(SQLException se2) ,
- // nothing we can do
try ,
if(conn!=null)
conn.close();
- catch(SQLException se) ,
se.printStackTrace();
- //end finally try
- //end try
-
-
Now let us compile above servlet and create following entries in web.xml
<servlet>
<servlet-name>DatabaseAccess</servlet-name>
<servlet-class>DatabaseAccess</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>DatabaseAccess</servlet-name>
<url-pattern>/DatabaseAccess</url-pattern>
</servlet-mapping>
Now call this servlet using URL http://localhost:8080/DatabaseAccess which would display following
response −
Database Result
ID: 100, Age: 18, First: Zara, Last: Ali
ID: 101, Age: 25, First: Mahnaz, Last: Fatma
ID: 102, Age: 30, First: Zaid, Last: Khan
ID: 103, Age: 28, First: Sumit, Last: Mittal
25
Part - C
1. javax.servlet package
2. javax.servlet.http package
Type 1: javax.servlet package: This package of Servlet contains many servlet interfaces and classes
which are capacity of handling any types of protocol sAnd This javax.servlet package containing large
interfaces and classes that are invoked by the servlet or web server container as they are not
specified with any protocol.
Type 2: javax.servlet.http package: This package of servlet contains more interfaces and classes
which are capable of handling any specified http types of protocols on the servlet. This
javax.servlet.http package containing many interfaces and classes that are used for http requests
only for servlet
Type 1: javax.servlet package:
Servlet: This interface describes and connects all the methods that a Servlet must implement. It
includes many methods to initialize the destroy of the Servlet, and a general (service()) method
which is handling all the requests are made to it. This Servlet interface is used to creating this servlet
class as this class having featuring to implementing these interfaces either directly or indirectly to
within it on to fetching servlets
ServletRequest: This ServletRequest interface in which examining the methods for all objects as
encapsulating data information about its all requests i.e. made to the servers, this object of the
ServletRequest interface is used to retrieve the information data from the user
ServletResponse: An interface examining the methods for all objects which are returning their
allowed responses from the servers and object of this current interfacing objects is used to estimate
the response to the end-user on the system
ServletConfig: declaring this interface ServletConfig useful to gaining accessing the configuration of
its main parameters which are passing through the Servlets during the phase time of initialization
and this ServletConfig object is used for providing the information data to the servlet classes external
to explicitly.
ServletContext: The object of the ServletContext interface is very helpful to featuring the info. data
to the web applications are explaining to it for servlets
GenericServlet: This is a generic classes examination to implement the Servlet. if you want to write
the Servlet’s protocols other than the HTTP, then the easy way of doing this is to extend
GenericServlet rather than by directly implementing the Servlet interfaces
ServletException: it is an exception that can be thrown when the Servlet invoking a problem of some
examples
ServletInputStream: This class ServletInputStream is used to reading the binary data from end user
request
ServletContextEvent: in this any changes are made in the servlet context of its web application, this
class notifies it to the end-user.
ServletOutputStream: This class ServletOutputStream is useful to send the transferring binary data
to the end-user side of the system
26
HttpServlet: in this HttpServlet purely abstracted class having features as functionality to extending
and applying on the HTTP requests. They have like Service() method that is declared in the Servlet
interfaces will now call its methods similar to doGet() and the doPost(), which are enabled to
providing behavior to the Calling Servlet
Cookie: This Class provides the feature Servlet an interface for the storage of small portions of data
information on the end-user computer or system.
HttpServletRequestWrapper and HttpServletResponseWrapper: this two wrapper classes allowing
capability of the HttpServletResponse and HttpServletRequest interfaces to the servlet by its
functions
HttpSessionEvent: This class HttpSessionEvent notified as any activity or changes/editing are
encountered in the session of web applications in servlet
HttpSessionBindingEvent: This class notified when any attribute is bounded, unbounded or replaced
in any Current session
Implementation: Example on servlet by implements
27
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-
app_3_1.xsd">
<servlet>
<servlet-name>Myservlet</servlet-name>
<servlet-class>ss.Myservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Myservlet</servlet-name>
<url-pattern>/Myservlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
</web-app>
Output:
1. Cookies are a simple and widely supported mechanism for session tracking.
2. Cookies are stored on the client-side, which means that server-side memory is not used for storing
session information. This can help reduce the load on the server.
3. Cookies can be configured to expire after a certain period of time or when the user closes their
browser, which can help improve security and privacy.
Benefits of using URL rewriting for session tracking:
28
1. URL rewriting is a simple and effective mechanism for session tracking that does not require
cookies.
2. URL rewriting works even if cookies are disabled or deleted, which can help ensure that session
tracking remains functional.
Both cookies and URL rewriting can be effective mechanisms for session tracking in servlet
4.Write a Servlet program to display the how many times visited the website counting using with
Cookies
29
int j = Integer.parseInt(c.getValue());
if (j == 1) ,
out.println("Welcome User ");
- else ,
out.println(" You have visited this website" + j + "times");
-
i++;
out.println("</body>");
out.println("</html>");
-
-
Output:
Unit-3: JSP: Overview of JSP Technology, Need of JSP, Advantages of JSP, Life Cycle of JSP Page, JSP
Processing, JSP Application Design with MVC, Setting Up the JSP Environment, JSP Directives, JSP
Action, JSP Implicit Objects, JSP Form Processing, JSP Session and Cookies Handling, JSP Session
Tracking JSP Database Access, JSP Standard Tag Libraries, JSP Custom Tag, JSP Expression Language,
JSP Exception Handling
Part - A
1.What is JSP?
JSP stands for Java Server Pages, otherwise known as Jakarta Server Pages. It is a server-side
technology used by web developers to create dynamic web pages that are based on HTML, XML, and
other web document types.
2. What is MVC?
MVC stands for Model View and Controller. It is a design pattern that separates the business logic,
presentation logic and data. Controller acts as an interface between View and Model. Controller
intercepts all the incoming requests. Model represents the state of the application i.e. data. It can
also have business logic.View represents the presentaion i.e. UI(User Interface).
3.What is ASP?
ASP stands for active server pages and it is a server-side script engine for building web pages.
30
The Model defines the business layer of the application This is the data layer which contains
business logic of the system, and also represents the state of the application.It’s independent of the
presentation layer, the controller fetches the data from the Model layer and sends it to the View
layer.
Implicit objects are a set of Java objects that the JSP Container makes available to developers on
each page. These objects may be accessed as built-in variables via scripting elements and can also be
accessed programmatically by JavaBeans and Servlets.JSP provide you Total 9 implicit
Part - B
JSP technology is used to create web application just like Servlet technology. It can be thought of
as an extension to Servlet because it provides more functionality than servlet such as expression
language, JSTL, etc. A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to
maintain than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.Java Server Pages (JSP) is a
technology for developing Webpages that supports dynamic content. This helps developers insert
java code in HTML pages by making use of special JSP tags, most of which start with <% and end
with %>.
A Java Server Pages component is a type of Java servlet that is designed to fulfill the role of a user
interface for a Java web application. Web developers write JSPs as text files that combine HTML or
XHTML code, XML elements, and embedded JSP actions and commands. Using JSP, you can collect
input from users through Webpage forms, present records from a database or another source, and
create Webpages dynamically. JSP tags can be used for a variety of purposes, such as retrieving
information from a database or registering user preferences, accessing JavaBeans components,
passing control between pages, and sharing information between requests, pages etc.
Advantages of JSP over Servlet
There are many advantages of JSP over the Servlet. They are as
follows:
1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the
features of the Servlet in JSP. In addition to, we can use implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes JSP
development easy.
2) Easy to maintain
31
JSP can be easily managed because we can easily separate our business
logic with presentation logic. In Servlet technology, we mix our business logic
with the presentation logic.
3) Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and feel
of the application.
4) Less code than Servlet
In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.
A JSP life cycle is defined as the process from its creation till the destruction. This is similar to a
servlet life cycle with an additional step which is required to compile a JSP into servlet.
JSP Compilation
When a browser asks for a JSP, the JSP engine first checks to see whether it needs to compile the
page. If the page has never been compiled, or if the JSP has been modified since it was last compiled,
the JSP engine compiles the page.
The compilation process involves three steps −
1. Parsing the JSP.
2. Turning the JSP into a servlet 3. Compiling the servlet.
JSP Initialization
32
When a container loads a JSP it invokes the jspInit() method before servicing any requests. If you
need to perform JSP-specific initialization, override the jspInit() method −
JSP Execution
This phase of the JSP life cycle represents all interactions with requests until the JSP is destroyed.
Whenever a browser requests a JSP and the page has been loaded and initialized, the JSP engine
invokes the _jspService() method in the JSP.
The _jspService() method takes an HttpServletRequest and an HttpServletResponse as its parameters
as follows
The _jspService() method of a JSP is invoked on request basis. This is responsible for generating the
response for that request and this method is also responsible for generating responses to all seven of
the HTTP methods, i.e, GET, POST, DELETE, etc.
JSP Cleanup
The destruction phase of the JSP life cycle represents when a JSP is being removed from use by a
container.
The jspDestroy() method is the JSP equivalent of the destroy method for servlets. Override
jspDestroy when you need to perform any cleanup, such as releasing database connections or closing
open files.
The jspDestroy() method has the following form
JavaServer Pages (JSP) is a technology that helps developers create dynamic, data-driven web
pages. JSP pages are compiled into Java servlets and run on the server. JSP uses a special syntax that
embeds snippets of Java code within HTML, and these pages are stored as regular HTML files with a .
jsp extension.
JSP program execution in web:
33
<body>
<h1>This is Srinivas Univesity Mangalore</h1>
</body>
</html>
Output:
http://localhost:8080/HelloWorldjsp/srnivasUniversity.jsp
This is Srinivas Univesity Mangalore
JSP which stands for Java Server Pages. It is a server-side technology. It is used for creating web
applications. It is used to create dynamic web content. In this JSP tags are used to insert JAVA code
into HTML pages. It is an advanced version of Servlet Technology. It is a Web-based technology that
helps us to create dynamic and platform-independent web pages. In this, Java code can be inserted
in HTML/ XML pages or both. JSP is first converted into a servlet by JSP container before processing
the client’s request. JSP Processing is illustrated and discussed in sequential steps prior to which
a pictorial media is provided as a handful pick to understand the JSP processing better which is as
follows:
JSP Processing
Step 1: The client navigates to a file ending with the .jsp extension and the browser initiates an HTTP
request to the webserver. For example, the user enters the login details and submits the button. The
browser requests a status.jsp page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file. Otherwise, the
request is forwarded to the JSP Engine. This is done by recognizing the URL ending with .jsp
extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code). This is done by
converting all the template text into println() statements and JSP elements to Java code. This process
is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded to the Servlet
engine. This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web Server. The output
is an HTML file. The Servlet engine passes the output as an HTTP response to the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.
34
4. Explain types of JSP Implicit Objects
These Objects are the Java objects that the JSP Container makes available to the developers in each
page and the developer can call them directly without being explicitly declared. JSP Implicit Objects
are also called pre-defined variables.
S.No. Object & Description
request
1 This is the HttpServletRequest object associated with the
request.
response
2 This is the HttpServletResponse object associated with the
response to the client.
out
3 This is the PrintWriter object used to send output to
the client.
session
4 This is the HttpSession object associated with the
request.
application
5 This is the ServletContext object associated with the
application context.
config
6 This is the ServletConfig object associated with the
page.
pageContext
7 This encapsulates use of server-specific features like
higher performance JspWriters.
page
8 This is simply a synonym for this, and is used to call
the methods defined by the translated servlet class.
Exception
9 The Exception object allows the exception data to be
accessed by designated JSP.
The request Object:
The request object is an instance of a javax.servlet.http.HttpServletRequest object. Each time a
client requests a page the JSP engine creates a new object to represent that request. The request
object provides methods to get the HTTP header information including form data, cookies, HTTP
methods etc.
The response Object:
The response object is an instance of a javax.servlet.http.HttpServletResponse object. Just as the
server creates the request object, it also creates an object to represent the response to the client.
The response object also defines the interfaces that deal with creating new HTTP headers. Through
this object the JSP programmer can add new cookies or date stamps, HTTP status codes, etc.
The out Object:
35
The out implicit object is an instance of a javax.servlet.jsp.JspWriter object and is used to send
content in a response. The initial JspWriter object is instantiated differently depending on whether
the page is buffered or not. Buffering can be easily turned off by using the buffered = 'false' attribute
of the page directive. The JspWriter object contains most of the same methods as
the java.io.PrintWriter class. However, JspWriter has some additional methods designed to deal with
buffering. Unlike the PrintWriter object, JspWriter throws IOExceptions.
Following table lists out the important methods that we will use to write boolean char, int, double,
object, String, etc.
S.No. Method & Description
out.print(dataType dt)
1
Print a data type value
out.println(dataType dt)
2 Print a data type value then terminate the line with new line
character.
out.flush()
3
Flush the stream.
The session Object:
The session object is an instance of javax.servlet.http.HttpSession and behaves exactly the same
way that session objects behave under Java Servlets.The session object is used to track client session
between client requests..
The application Object:
The application object is direct wrapper around the ServletContext object for the generated
Servlet and in reality an instance of a javax.servlet.ServletContext object.
This object is a representation of the JSP page through its entire lifecycle. This object is created
when the JSP page is initialized and will be removed when the JSP page is removed by
the jspDestroy() method.By adding an attribute to application, you can ensure that all JSP files that
make up your web application have access to it.
The config Object:
The config object is an instantiation of javax.servlet.ServletConfig and is a direct wrapper around
the ServletConfig object for the generated servlet.This object allows the JSP programmer access to
the Servlet or JSP engine initialization parameters such as the paths or file locations etc.The
following config method is the only one you might ever use, and its usage is trivial −
config.getServletName();
This returns the servlet name, which is the string contained in the <servlet-name> element
defined in the WEB-INF\web.xml file.
36
arguments. For example, pageContext.removeAttribute ("attrName") removes the attribute from
all scopes, while the following code only removes it from the page scope −
pageContext.removeAttribute("attrName", PAGE_SCOPE);
The page Object:
This object is an actual reference to the instance of the page. It can be thought of as an object that
represents the entire JSP page. The page object is really a direct synonym for the this object.
The exception Object:
The exception object is a wrapper containing the exception thrown from the previous page. It is
typically used to generate an appropriate response to the error condition.
5. Explain the JSP form processing.
JSP Form Processing
Forms are the common method in web processing. We need to send information to the web server
and that information. There are two commonly used methods to send and get back information to
the web server.
GET Method:
This is the default method to pass information from browser to web server.
It sends the encoded information separated by ?character appended to URL page.
It also has a size limitation, and we can only send 1024 characters in the request.
We should avoid sending password and sensitive information through GET method.
POST Method:
Post method is a most reliable method of sending information to the server.
It sends information as separate message.
It sends as text string after ?in the URL.
It is commonly used to send information which are sensitive.
JSP handles form data processing by using following methods:
getParameter():It is used to get the value of the form parameter.
getParameterValues():It is used to return the multiple values of the parameters.
getParameterNames()It is used to get the names of parameters.
getInputStream()It is used to read the binary data sent by the client.
Example:
In this example, we have taken a form with two fields.”username” and “password” with a
submit button
Action_form.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-
1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Guru Form</title>
</head>
<body>
<form action="action_form_process.jsp" method="GET">
UserName: <input type="text" name="username">
<br />
Password: <input type="text" name="password" />
<input type="submit" value="Submit" />
</form>
37
</body>
</html>
Action_form_process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Form Processing</h1>
<p><b>Welcome User:</b>
<%= request.getParameter("username")%>
</p>
</body>
</html>
Here we have defined a form and through which we have process the action to some other JSP. In
action parameter, we add that JSP to which it has to be processed through GET method.
Here we are using GET method to pass the information i.e username and password.Here we are
taking fields like username and password which are text fields, and we are getting the input from the
user. This input can be fetched using getParameter method. Also, we have submit button with type
submit type which helps us to pass the field values into action_form_process.jsp
Action_form_process.jsp , Here we get the values of the input fields from action_form.jsp
using request object’s getParameter method. Output:
Create Table
To create the Employees table in the EMP database, use the following steps –
Create the Employee table in the TEST database as follows − −
38
);
Query OK, 0 rows affected (0.08 sec)
mysql>
Create Data Records
39
</c:forEach>
</table>
</body>
</html>
Output:
40
Example: The core tags are most frequently used tags in JSP. They provide support for Iteration
Conditional logic , Catch exception , url forward Redirect, etc.
To use core tags we need to define tag library first and below is the syntax to include a tag library.
Syntax :
<%@ taglib prefix="c" uri=http://java.sun.com/jsp/jstl/core%>
Here, prefix can be used to define all the core tags and uri is the library of taglib from which it is
imported
JSTL Custom Tags
1. It is a user-defined JSP language element.
2. When JSP is translated into a servlet, custom tag is converted into a class which takes action on an
object and is called as a tag handler.
3. Those actions when the servlet is executed are invoked by the web container.
4. To create the user-defined custom tag, we need to create the tag handler which will be extending
the SimpleTagSupport and have to override doTag() method.
5. We need to create TLD where we need to map the class file in TLD.
Advantages of custom tags in JSP
Portable – An action described in a tag library must be usable in any JSP container.
Simple – Unsophisticated users must be able to understand and use this mechanism.
Vendors of JSP functionality must find it easy to make it available to users as actions.
Expressive – The mechanism must support a wide range of actions, including nested actions,
scripting elements inside action bodies, creation, use and updating of scripting variables.
Usable from different scripting languages – Although the JSP specification currently only
defines the semantics for scripts in the Java programming language, we want to leave open
the possibility of other scripting languages.
Built upon existing concepts and machinery– We do not want to reinvent what exists
elsewhere. Also, we want to avoid future conflicts whenever we can predict them
Example: Syntax:
Consider we are creating testGuru tag and we can usetaghandlertestTag class, which will override
doTag() method.
<ex:testGuru/>
Class testTag extends SimpleTagSupport{ public void doTag()}
To map this testTag class in TLD (Tag Library Descriptor) as JSP container will automatically create a
mapping between the class file and uri which has been mentioned in the TLD file.
8. Define JSP expression Language
It has introduced in JSP 2.0 version. Expression Language is mainly used to eliminate java
code from the JSP. In general, to eliminate java code and scripting elements from JSP pages,
we have to use custom action which requires a lot of java code internally in order to
implement simple programming like if, switch, for, and so on. To overcome the above
problem, we have to use Expression Language syntax along with standard actions, custom
actions, and JSTL tag library.
Example
To print the value of request parameter uname: We have to use java code before
expression language to get a particular request parameter from the request object.
<% uname=request.getParameter(“uname”);%>
41
In this example, we are able to retrieve a particular request parameter without using java
code by using expression language syntax. ${param.uname}
Advantages in JSP:
1. We can get request parameters
2. We can get any scope attributes
3. We can get values of bean objects stored in a scope
4. We can get request header values.
5. We can get context parameter values
6. We can get cookie values
7. We can get JSP implicit objects
8. We can do arithmetic, relational, logical, and conditional operations
9. We can call static methods of a class by using EL functions
42
To deactivate the evaluation of EL expressions, we specify the isELIgnored attribute of the page
directive as below:
<%@ page isELIgnored ="true|false" %>
Checked Exception
"Checked exceptions" are a type of exception that is usually a user fault or a problem that cannot
be foreseen by the programmer. This type of exception is checked at compile-time. Here is a list of
some common "Checked exceptions" that occur in the programming domain:
IO Exception: This is an example of a checked exception where some exceptions may occur while
reading and writing a file. If the file format is not supported, then the IO exception will occur.
FileNotFoundException: This is an example of a checked exception where a file in which data needs
to be written is not found on that particular path on the disk.
SQLException: This is also an example of a checked exception where the file is associated with a SQL
database. The exception will be if there is a problem or concern with the connectivity of the SQL
database.
43
Runtime Exception
"Runtime exceptions" can be defined as exceptions evaded by the programmer. They are left
unnoticed at compilation time. Here is the list of some of the common examples that
occurred in the programming domain:
ArrayIndexOutOfBoundsException: This is a runtime exception; This occurs when the array
size goes beyond the elements or index value set.
NullPointer Exception: This is also an example of a runtime exception raised when a variable
or object is empty or null, and users or programmers try to access it.
ArithmeticException: This is an example of a runtime exception when a mathematical
operation is not allowed under normal circumstances. A common example of such a scenario
is to divide the number by 0.
Errors Exception
"Error exception" arises solely because of the user or programmer. Here you might encounter error
due to stack overflows. Here is the list of some of the common examples that occurred in the
programming domain:
Error: This is a subclass of throwable that indicates serious problems the applications cannot catch.
Internal Error: This error occurs when a fault occurs in the Java Virtual Machine (JVM).
Instantiation error: This error occurs when you try to instantiate an object, ultimately failing to do
that.
input.html
<html>
<head>
<title>Division of Two Numbers</title>
</head>
<body>
<form action="divide.jsp" method="post">
<b>Number1: </b><input type="text" name="first" ><br><br>
<b>Number2: </b><input type="text" name="second" ><br><br>
<input type="submit" value="Divide">
</form>
</body>
</html>
divide.jsp
<%@page errorPage = "error.jsp" %>
<%!
String num1, num2;
int a, b, c;
%>
<%
String num1 = request.getParameter("first");
String num2 = request.getParameter("second");
a = Integer.parseInt(num1);
b = Integer.parseInt(num2);
c = a / b;
out.print("Result is: " + c);
%>
44
error.jsp
<%@ page isErrorPage = "true" %>
<h3> Exception caught!</h3>
<font color="red"><b>Exception occurred = </b></font>
<font color="blue"><%= exception %></font>
Part - C
45
4. Instantiation (Object of the Generated Servlet is created).
5. Initialization ( the container invokes jspInit() method).
6. Request processing ( the container invokes _jspService() method).
7. Destroy ( the container invokes jspDestroy() method).
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
As depicted in the above diagram, JSP page is translated into Servlet by the help of JSP translator.
The JSP translator is a part of the web server which is responsible for translating the JSP page into
Servlet. After that, Servlet page is compiled by the compiler and gets converted into the class file.
Moreover, all the processes that happen in Servlet are performed on JSP later like initialization,
committing response to the browser and destroy.
Example:
46
2. Explain the MVC Architecture in JSP.
A MVC stands for Model View and Controller. It is a design pattern that separates the business
logic, presentation logic and data. Controller acts as an interface between View and Model.
Controller intercepts all the incoming requests. Model represents the state of the application i.e.
data. It can also have business logic. View represents the presentaion i.e. UI(User Interface).
Architecture
MVC is a systematic way to use the application where the flow starts from the view layer,
where the request is raised and processed in controller layer and sent to model layer to insert
data and get back the success or failure message.
Model Layer:
This is the data layer which consists of the business logic of the system. It consists of all the data of
the application
It also represents the state of the application.
It consists of classes which have the connection to the database.
The controller connects with model and fetches the data and sends to the view layer.
The model connects with the database as well and stores the data into a database which is
connected to it.
View Layer:
This is a presentation layer.
It consists of HTML, JSP, etc. into it.
It normally presents the UI of the application.
It is used to display the data which is fetched from the controller which in turn fetching data
from model layer classes.
This view layer shows the data on UI of the application.
Controller Layer:
It acts as an interface between View and Model.
It intercepts all the requests which are coming from the view layer.
It receives the requests from the view layer and processes the requests and does the necessary
validation for the request.
47
MVC is a systematic way to use the application where the flow starts from the view layer, where
the request is raised and processed in controller layer and sent to model layer to insert data and get
back the success or failure message. M stands for Model,V stands for View and C stands for
controller.
This request is further sent to model layer for data processing, and once the request
is processed, it sends back to the controller with required information and displayed
accordingly by the view
48
By default, JSPs have session tracking enabled and a new HttpSession object is instantiated for
each new client automatically. Disabling session tracking requires explicitly turning it off by setting
the page directive session attribute to false as follows −
<%@ page session = "false" %>
The JSP engine exposes the HttpSession object to the JSP author through the implicit session object.
Since session object is already provided to the JSP programmer, the programmer can immediately
begin storing and retrieving data from the object without any initialization or getSession().
Example: This example describes how to use the HttpSession object to find out the creation time
and the last-accessed time for a session. We would associate a new session with the request if one
does not already exist.
<%@ page import = "java.io.*,java.util.*" %>
<%
// Get session creation time.
Date createTime = new Date(session.getCreationTime());
// Get last access time of this Webpage.
Date lastAccessTime = new Date(session.getLastAccessedTime());
String title = "Welcome Back to my website";
Integer visitCount = new Integer(0);
String visitCountKey = new String("visitCount");
String userIDKey = new String("userID");
String userID = new String("ABCD");
// Check if this is new comer on your Webpage.
if (session.isNew() ),
title = "Welcome to my website";
session.setAttribute(userIDKey, userID);
session.setAttribute(visitCountKey, visitCount);
-
visitCount = (Integer)session.getAttribute(visitCountKey);
visitCount = visitCount + 1;
userID = (String)session.getAttribute(userIDKey);
session.setAttribute(visitCountKey, visitCount);
%>
<html>
<head>
<title>Session Tracking</title>
</head>
<body>
<center>
<h1>Session Tracking</h1>
</center>
<table border = "1" align = "center">
<tr bgcolor = "#949494">
<th>Session info</th>
<th>Value</th>
</tr>
<tr>
<td>id</td>
<td><% out.print( session.getId()); %></td>
</tr>
<tr>
<td>Creation Time</td>
49
<td><% out.print(createTime); %></td>
</tr>
<tr>
<td>Time of Last Access</td>
<td><% out.print(lastAccessTime); %></td>
</tr>
<tr>
<td>User ID</td>
<td><% out.print(userID); %></td>
</tr>
<tr>
<td>Number of visits</td>
<td><% out.print(visitCount); %></td>
</tr>
</table>
</body>
</html>
Now put the above code in main.jsp and try to access http://localhost:8080/main.jsp. Once you run
the URL, you will receive the following result –
Welcome to my website
Session Information
Session info value
id 0AE3EC93FF44E3C525B4351B77ABB2D5
User ID ABCD
Number of visits 0
Part - A
1. What is Hibernate?
Hibernate is java based ORM tool that provides framework for mapping application domain objects
to the relational database tables
2. What is ORM?
Object Relational Mapping (ORM) is a technique used in creating a "bridge" between object-
oriented programs and, in most cases, relational databases.
50
3. What is HQL?
Hibernate Query Language is the object-oriented query language of Hibernate Framework. HQL is
very similar to SQL except that we use Objects instead of table names, that makes it more close to
object oriented programming.
A database independent, polymorphic queries supported, and easy to learn for Java
programmers. The Query interface provides object-oriented methods and capabilities for
representing and manipulating HQL queries.
Native SQL queries are useful when you need to perform complex queries that cannot be
expressed using Hibernate’s Query Language (HQL) or Criteria API. Native SQL queries can be used
to perform complex joins, aggregate functions, and subqueries
Part - B
Hibernate is the Object-Relational Mapping (ORM) framework in Java created by Gavin King in
2001. It simplifies the interaction of a database and the Java application being developed. It is an
ORM tool that is powerful and lightweight. Another important thing is that this is a high-performance
open-source tool. Hibernate implements Java Persistence API specifications and is a powerful object-
relational persistence and query service for applications developed in Java. Hibernate is an ORM tool
that maps database structures with Java objects dynamically at runtime. Using Hibernate, a
persistent framework, allows the developers to focus on just business logic code writing despite
writing accurately, as well as a good persistence layer that consists of writing the SQL Queries,
connection management, and JDBC Code. Hibernate maps Java classes to database tables and from
Java data types to SQL data types and relieves the developer from 95% of common data persistence
related programming tasks. Hibernate sits between traditional Java objects and database server to
handle all the works in persisting those objects based on the appropriate O/R mechanisms and
patterns
51
Hibernate Advantages
1. Hibernate takes care of mapping Java classes to database tables using XML files and without
writing any line of code.
2. Provides simple APIs for storing and retrieving Java objects directly to and from the database.
3. If there is change in the database or in any table, then you need to change the XML file properties
only.
4. Abstracts away the unfamiliar SQL types and provides a way to work around familiar Java Objects.
5. Hibernate does not require an application server to operate.
6. Manipulates Complex associations of objects of your database.
7. Minimizes database access with smart fetching strategies.
8. Provides simple querying of data.
Supported Databases
Hibernate supports almost all the major RDBMS. Following is a list of few of the database engines
supported by Hibernate −
• HSQL Database Engine
• DB2/NT
• MySQL
• PostgreSQL
• FrontBase
• Oracle
• Microsoft SQL Server Database
• Sybase SQL Server
• Informix Dynamic Server
2. Explain the Hibernate O-R mapping process.
Hibernate is a free and open-source object-relational mapper for Java. This simple approach gets
rid of all the problems with JDBC. Hibernate develops persistence logic, which arranges and prepares
the data for subsequent use. Its advantages over other frameworks include being open-source,
portable, and an ORM tool. Hibernate mappings are one of the key features of hibernate and
they establish the relationship between two database tables as attributes in your model that
allows you to easily navigate the associations in your model and criteria queries.
O/RM itself can be defined as a software or product that represents and/or convert the data
between the application (written in Object-Oriented Language) and the database. In other words we
can say O/RM maps an object to the relational database table. Hibernate is also an O/RM and is
available as open source project. To use Hibernate with Java you will be required to create a file with
.hbm.xml extension into which the mapping information will be provided. This file contains the
mapping of Object with the relational table that provides the information to the Hibernate at the
time of persisting the data. ORM abstracts the application from the process related to database
such as saving, updating, deleting of objects from the relational database table.
52
Example :
Employee.java
package srinivas;
public class Employee
,
private long empId;
private String empName;
public Employee() ,
-
public long getEmpId() ,
return this.empId;
-
public void setEmpId(long empId) ,
this.empId = empId;
-
public String getEmpName() ,
return this.empName;
-
public void setEmpName(String empName) ,
this.empName = empName;
-
-
employee.hbm.xml
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="srinivas.Employee" table="employee">
<id name="empId" type="long" column="Id" >
<generator class="assigned"/>
</id>
<property name="empName">
<column name="Name" />
</property>
</class>
</hibernate-mapping>
The figure given below demonstrate you how ORM abstracts the application to the database
related process and vice-versa :
53
O – R Mapping process
The above figure demonstrates that an ORM abstracts the both in respect to database how an
application tries to persist the data and in respect to an application that how objects are stored in
database.
For example, the below diagram shows a Hibernate Object Relational Mapping between Student
Java class and student table in the database.
Hibernate provides a reference implementation of Java Persistence API, which makes it a great
choice as an ORM tool with the benefits of loose coupling.
Hibernate framework is open source under the LGPL license and lightweight.
2) Fast Performance
54
The performance of hibernate framework is fast because cache is internally used in
hibernate framework. There are two types of cache in hibernate framework first level cache
and second level cache. First level cache is enabled by default.
HQL (Hibernate Query Language) is the object-oriented version of SQL. It generates the
database independent queries. So you don't need to write database specific queries. Before
Hibernate, if database is changed for the project, we need to change the SQL query as well
that leads to the maintenance problem.
Hibernate framework provides the facility to create the tables of the database automatically.
So there is no need to create tables in the database manually.
Hibernate removes a lot of boiler-plate code that comes with JDBC API, the
code looks cleaner and readable.
Hibernate supports caching that is better for performance, JDBC queries are
not cached hence performance is low.
55
Hibernate provides an option through which we can create database tables
too, for JDBC tables must exist in the database.
The Hibernate architecture includes many objects such as persistent object, session
factory, transaction factory, connection factory, session, transaction etc.
56
This is the high level architecture of Hibernate with mapping file and configuration file.
Hibernate framework uses many objects such as session factory, session, transaction
etc. along with existing Java API such as JDBC (Java Database Connectivity), JTA (Java
Transaction API) and JNDI (Java Naming Directory Interface).
Elements of Hibernate Architecture
For creating the first hibernate application, we must know the elements of Hibernate architecture.
They are as follows:
SessionFactory
The SessionFactory is a factory of session and client of ConnectionProvider. It holds
second level cache (optional) of data. The org.hibernate.SessionFactory interface
provides factory method to get the object of Session.
Session
The session object provides an interface between the application and data stored
in the database. It is a short-lived object and wraps the JDBC connection. It is factory
of Transaction, Query and Criteria. It holds a first-level cache (mandatory) of data. The
org.hibernate.Session interface provides methods to insert, update and delete the
object. It also provides factory methods for Transaction, Query and Criteria.
Transaction
The transaction object specifies the atomic unit of work. It is optional. The
org.hibernate.Transaction interface provides methods for transaction management.
ConnectionProvider
It is a factory of JDBC connections. It abstracts the application from DriverManager
or DataSource. It is optional.
TransactionFactory
It is a factory of Transaction. It is optional.
57
5. Explain the advantage of using native SQL queries in Hibernate
Hibernate is a popular object-relational mapping (ORM) tool used in Java applications. It allows
developers to map Java objects to database tables and perform CRUD (create, read, update, delete)
operations on the database without writing SQL queries manually. Native SQL queries are useful
when you need to perform complex queries that cannot be expressed using Hibernate’s Query
Language (HQL) or Criteria API. Native SQL queries can be used to perform complex joins, aggregate
functions, and subqueries. To execute a native SQL query in Hibernate, create an SQLQuery object
and set the SQL statement to be executed.
Advantages of using native SQL queries in Hibernate
While Hibernate provides a powerful and easy-to-use ORM framework for accessing relational
databases, there are some scenarios where native SQL queries can offer advantages over using the
Hibernate Query Language (HQL) or Criteria API. Here are some advantages of using native SQL
queries in Hibernate:
Performance: Native SQL queries can be optimized for performance and may outperform HQL
queries or Criteria queries in some cases. This is because native SQL queries are executed directly by
the database, bypassing the Hibernate framework and any overhead that it may introduce.
Complex queries: Native SQL queries can handle complex queries that are difficult or impossible to
express using HQL or the Criteria API. For example, queries involving complex joins or subqueries can
be expressed more easily and efficiently using native SQL.
Integration with legacy systems: In some cases, legacy systems may require the use of native SQL
queries to access the database. By providing support for native SQL queries, Hibernate can integrate
more easily with legacy systems and allow them to be modernized more gradually.
Access to database-specific features: Native SQL queries allow access to database-specific features
that may not be available through Hibernate or JPA. This can include advanced features such as
stored procedures, triggers, or custom data types.
Familiarity with SQL: Many developers are familiar with SQL and may prefer to use native SQL
queries to express their queries in a more familiar syntax. This can make the code easier to read and
maintain, especially for developers who are new to Hibernate or JPA.
1. Hibernate provides its own implementation of native SQL queries, which includes
additional features not found in the JPA specification.
2. Hibernate Native Query is created using the createSQLQuery() method of the Session
interface, which returns an instance of the SQLQuery interface.
3. Hibernate Native Query provides support for additional mapping options, including the
ability to map the result set of a query to a non-entity class using the addScalar()
method.
4. Hibernate Native Query also provides additional methods for controlling the caching
behavior of the query, including setCacheable(), setCacheRegion(), and
setCacheMode().
58
6. Explain the Transaction Interface in Hibernate
Transaction:
A transaction simply represents a unit of work. Generally speaking, a transaction is a set of SQL
operations that need to be either executed successfully or not at all.
1. Atomicity: Each transaction should be carried out in its entirety; if one part of the transaction fails,
then the whole transaction fails.
2. Consistency: The database should be in a valid state before and after the performed transaction.
3. Isolation: Each transaction should execute in complete isolation without knowing the existence of
other transactions.
4. Durability: Once the transaction is complete, the changes made by the transaction are permanent
(even in the occurrence of unusual events such as power loss).
59
6. void registerSynchronization(Synchronization s) registers a user
synchronization callback for this transaction.
7. boolean wasCommited() checks if the transaction is commited successfully.
8. boolean wasRolledBack() checks if the transaction is rolledback successfully.
Example:
Part - C
60
Programmatic Configurations
Hibernate does provide a Configuration class which provides certain methods to load the mapping
files and database configurations programmatically .
1. addResource() – We can call addResource() method and pass the path of mapping
file available in a classpath. To load multiple mapping files, simply call
addResources() method multiple times.
2. addClass()- Alternatively we can call addClass() method and pass in the class
name which needs to persist. To add multiple classes , we can call addClass()
multiple times.
Below code snippet uses addClass() method to load user and account classes
available in com.hibernate.tutorial package.
Configuration configuration = new Configuration();
configuration.addClass("com.hibernate.tutorial.user.class");
configuration.addClass("com.hibernate.tutorial.user.account.class ");
3. addJar() – We can call addJar() to specify the path of jar file containing all the
mapping files. This approach provides a generic way and need not to add mapping
every time we add a new mapping.
61
setProperty()- we can call setProperty() method on configuration object and pass
the individual property as a key value pair. We can call setProperty() multiple times.
Below code specifies hibernate dialects , driver class , database connection url,
database credentials using setProperty() method.
<strong><strong><strong><strong>Configuration configuration = new Configuration();
configuration.setProperty("hibernate.dialect", " org.hibernate.dialect.MySQLDialect");
configuration.setProperty("hibernate.connection.driver_class", "com.mysql.jdbc.Driver");
configuration.setProperty("hibernate.connection.url", "jdbc:mysql://localhost:3306/tutorial");
configuration.setProperty("hibernate.connection.username", "root");
configuration.setProperty("hibernate.connection.password", "password");
</strong></strong></strong></strong>
<hibernate-configuration>
<session-factory>
62
<property name="hibernate.connection.url">
jdbc:mysql://localhost:3306/tutorial
</property>
<property name="hibernate.connection.username">
root
</property>
<property name="hibernate.connection.password">
password
</property>
<property name="dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">false</property>
<property name="hibernate.connection.driver_class">
com.mysql.jdbc.Driver
</property>
<mapping resource="user.hbm.xml"/>
</session-factory>
</hibernate-configuration>
</strong></strong></strong></strong>
To add mapping resources we can use <mapping resource> tag in hibernate.cfg.xml file .This is
similar to addResource() method. Similarly, we can use <mapping jar> and <mapping class> tags for
addJar() and addClass()
Just need to instantiate Configuration object like below
Configuration configuration = new Configuration().configure();
new Configuration() call will load the hibernate.properties file and calling configure() method on
configuration object loads hibernate.cfg.xml. In case any property is defined in both
hibernate.properties and hibernate.cfg.xml file then xml file will get precedence.
To load the custom files, we can call
Configuration configuration = new
Configuration().configure("/configurations/myConfiguration.cfg.xml")
The Above code snippet will load myConfiguration.cfg.xml from the configuration subdirectory of
class path.
Note: We can skip prefix “hibernate” from the hibernate properties like
hibernate.connection.password is equivalent to connection.password
63
index.jsp
This page gets input from the user and sends it to the register.jsp file using post
method.
register.jsp
This file gets all request parameters and stores this information into an object of User
class. Further, it calls the register method of UserDao class passing the User class
object.
<%@page import="com.javatpoint.mypack.UserDao"%>
<jsp:useBean id="obj" class="com.javatpoint.mypack.User">
</jsp:useBean>
<jsp:setProperty property="*" name="obj"/>
<%
int i=UserDao.register(obj);
if(i>0)
out.print("You are successfully registered");
%>
User.java
package com.javatpoint.mypack;
public class User ,
private int id;
private String name,password,email;
64
user.hbm.xml
UserDao.java
package com.javatpoint.mypack;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.boot.Metadata;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
public class UserDao {
public static int register(User u){
int i=0;
StandardServiceRegistry ssr = new StandardServiceRegistryBuilder().configure("hib
ernate.cfg.xml").build();
Metadata meta = new MetadataSources(ssr).getMetadataBuilder().build();
65
SessionFactory factory = meta.getSessionFactoryBuilder().build();
Session session = factory.openSession();
Transaction t = session.beginTransaction();
i=(Integer)session.save(u);
t.commit();
session.close();
return i;
}
}
hibernate.cfg.xml
66
Output: You are successfully registered
When a worker cannot work for another department at the same time, the mapping is known as
one-to-one.
2. One to many: One property is mapped to many other characteristics in this form of relationship
by being mapped to another attribute in a specific way. An illustration will help you comprehend this
better. as in the case of a student who belongs to multiple groups, like a simultaneous cultural
organization, sports team, and robotics team.
The student and group relationship in this scenario is referred to be a many-to-one relationship.
3. Many to many: One attribute is mapped to another attribute in this type of connection so that
any number of attributes can be linked to other attributes without a limit on the quantity. An
example will help you better comprehend this. For instance, in the library, one individual may check
out a number of books, and one book may be issued to a number of other books.
Many to many partnerships are what this form of relationship is known as. Before implementation,
there must be a thorough knowledge of the business use case for this complex relationship.
Types of Mapping
The primary fundamental forms of Hibernate mapping types are:
67
1. Primitive Types: Data types such as "integer," "character," "float," "string," "double," "Boolean,"
"short," "long," etc., are defined for this type of mapping. These can be found in the hibernate
framework to map java data types to RDBMS data types.
2. Binary and Large Object Types: They include "clob," "blob," "binary," "text," etc. To maintain the
data type mapping of big things like images and videos, blob and clob data types are present.
3. Date and Time Types: "Date," "time," "calendar," "timestamp," etc. are some examples. We have
data type mappings for dates and times that are similar to primitive.
4. JDK-related Types: This category includes some mappings for things outside the scope of the
previous kind of mappings. "Class," "locale," "currency," and "timezone" are among them.
68
Example -3:Date and Time Types: Hibernate mapping types also contain the Date and Time
types.
Example – 4 JDK-related Types : The fourth category of Hibernate mapping types is JDK-related types
69
UNIT- 5 Spring Framework: Spring Basics, Spring Container, Spring AOP, Spring Data Access,
Spring O-R/mapping, Spring Transaction Management, Spring Remoting and Enterprise
Services, Spring Web MVC Framework, Securing Spring Application.
Part - A
1. What is spring?
Spring framework makes the easy development of JavaEE application. It is a lightweight, loosely
coupled and integrated framework for developing enterprise applications in java.
2. What is POJO?
POJO stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special
restriction other than those forced by the Java Language Specification and not requiring any
classpath. POJOs are used for increasing the readability and re-usability of a program
3. What is IoC?
Spring Framework. Inversion of Control (IOC) is a design principle employed by the Spring
framework to invert the control of object instantiation and dependency management from the
programmer to the framework itself.
4. What is AOP?
Aspect-Oriented Programming (AOP) is a programming paradigm that allows developers to
modularize crosscutting concerns, such as logging and security, in their applications. Spring AOP is a
powerful framework for implementing AOP in Java applications, and it is integrated with the popular
Spring Framework.
5. What is Spring Security?
Spring Security is a framework that provides authentication, authorization, and protection against
common attacks. With first class support for securing both imperative and reactive applications, it is
the de-facto standard for securing Spring-based applications.
A bean is just a Java object that is made when the application starts by the Spring framework. The
object could be a configuration, a service, a database connection factory. JavaBeans are classes
which encapsulate several objects into a single object. It helps in accessing these object from
multiple places.
7. What is Dependency Injection?
Dependency Injection is a fundamental aspect of the Spring framework, through which the Spring
container “injects” objects into other objects or “dependencies”. Simply put, this allows for loose
coupling of components and moves the responsibility of managing components onto the container.
Part - B
Spring is the most popular application development framework for enterprise Java. Millions of
developers around the world use Spring Framework to create high performing, easily testable, and
reusable code.
Spring framework is an open source Java platform. It was initially written by Rod Johnson and was
first released under the Apache 2.0 license in June 2003.
70
Spring is lightweight when it comes to size and transparency. The basic version of Spring framework
is around 2MB. The core features of the Spring Framework can be used in developing any Java
application, but there are extensions for building web applications on top of the Java EE platform.
Spring framework targets to make J2EE development easier to use and promotes good programming
practices by enabling a POJO-based programming model.
Applications of Spring
Following is the list of few of the great benefits of using Spring Framework
−
71
2. Write short notes about the AOP Terminologies.
The key unit of modularity in OOP is the class, whereas in AOP the unit of modularity is the aspect.
Dependency Injection helps you decouple your application objects from each other and AOP helps
you decouple cross-cutting concerns from the objects that they affect. AOP is like triggers in
programming languages such as Perl, .NET, Java, and others.Spring AOP module provides interceptors
to intercept an application. For example, when a method is executed, you can add extra functionality
before or after the method execution.
AOP Terminologies
Before we start working with AOP, let us become familiar with the AOP concepts and terminology.
These terms are not specific to Spring, rather they are related to AOP
Aspect
This is a module which has a set of APIs providing cross-cutting
requirements. For example, a logging module would be called
AOP aspect for logging. An application can have any number of
aspects depending on the requirement.
Join point
This represents a point in your application where you can plug-
in the AOP aspect. You can also say, it is the actual place in the
application where an action will be taken using Spring AOP
framework.
Advice
This is the actual action to be taken either before or after the
method execution. This is an actual piece of code that is
invoked during the program execution by Spring AOP
framework.
Pointcut
This is a set of one or more join points where an advice should
be executed. You can specify pointcuts using expressions or
patterns as we will see in our AOP examples.
Introduction
72
An introduction allows you to add new methods or attributes to
the existing classes.
Target object
The object being advised by one or more aspects. This object
will always be a proxied object, also referred to as the advised
object.
Weaving
Weaving is the process of linking aspects with other application
types or objects to create an advised object. This can be done
at compile time, load time, or at runtime.
Types of Advice:
Spring aspects can work with five kinds of advice mentioned as follows
Sr.No Advice & Description
before
1
Run advice before the a method execution.
after
2 Run advice after the method execution, regardless of
its outcome.
after-returning
3 Run advice after the a method execution only if
method completes successfully.
after-throwing
4 Run advice after the a method execution only if
method exits by throwing an exception.
around
5 Run advice before and after the advised method is
invoked.
73
3. Write short notes about the Spring ORM technique.
Object–relational mapping (ORM, O/RM, and O/R mapping tool) in computer science is a
programming technique for converting data between a relational database and the heap of an
object-oriented programming language.
Spring-ORM is a technique or a Design Pattern used to access a relational database from an object-
oriented language. ORM (Object Relation Mapping) covers many persistence technologies. They are
as follows:
JPA(Java Persistence API): It is mainly used to persist data between Java objects and relational
databases. It acts as a bridge between object-oriented domain models and relational database
systems.
JDO(Java Data Objects): It is one of the standard ways to access persistent data in databases, by
using plain old Java objects (POJO) to represent persistent data.
Hibernate – It is a Java framework that simplifies the development of Java applications to interact
with the database.
Oracle Toplink, and iBATIS: Oracle TopLink is a mapping and persistence framework for Java
development.
For the above technologies, Spring provides integration classes so that each of these techniques
can be used following Spring principles of configuration, and easily integrates with Spring transaction
management.For each of the above technologies, the configuration consists of injecting the
DataSource bean into some kind of SessionFactory or EntityManagerFactory, etc. For pure JDBC(Java
Database Connectivity), integration classes are not required apart from JdbcTemplate because JDBC
only depends on a DataSource. If someone wants to use an ORM like JPA(Java Persistence API) or
Hibernate then you do not need spring-JDBC, but only this module.
Note: The Spring Framework is an application framework and also an inversion of the control
container for the Java platform. The framework’s core features can be used by any of the Java
applications, but there are some extensions for building web applications on top of the Java EE
(Enterprise Edition) platform.
1. Due to the Spring framework, you do not need to write extra codes before
and after the actual database logic such as getting the connection,
starting the transaction, committing the transaction, closing the
connection, etc.
2. Spring has an IoC(Inversion of control) approach which makes it easy to
test the application.
3. Spring framework provides its API for exception handling along with the
ORM framework.
4. By using the Spring framework, we can wrap our mapping code with an
explicit template wrapper class or AOP(Aspect-oriented programming)
style method interceptor.
74
4. Explain the Programmatic vs Declarative Transactions
Spring framework provides an abstract layer on top of different underlying transaction
management APIs. Spring's transaction support aims to provide an alternative to EJB transactions by
adding transaction capabilities to POJOs. Spring supports both programmatic and declarative
transaction management. EJBs require an application server, but Spring transaction management can
be implemented without the need of an application server.
Local vs. Global Transactions: Local transactions are specific to a single transactional resource like a
JDBC connection, whereas global transactions can span multiple transactional resources like
transaction in a distributed system. Local transaction management can be useful in a centralized
computing environment where application components and resources are located at a single site,
and transaction management only involves a local data manager running on a single machine. Local
transactions are easier to be implemented. Global transaction management is required in a
distributed computing environment where all the resources are distributed across multiple systems.
In such a case, transaction management needs to be done both at local and global levels. A
distributed or a global transaction is executed across multiple systems, and its execution requires
coordination between the global transaction management system and all the local data managers of
all the involved systems.
Programmatic transaction management is usually a good idea only if you have a small number of
transactional operations. For example, if you have a web application that requires transactions only
for certain update operations, you may not want to set up transactional proxies by using Spring or
any other technology. In this case, using the TransactionTemplate may be a good approach. Being
able to set the transaction name explicitly is also something that can be done only by using the
programmatic approach to transaction management.On the other hand, if your application has
numerous transactional operations, declarative transaction management is usually worthwhile. It
keeps transaction management out of business logic and is not difficult to configure. When using the
Spring Framework, rather than EJB CMT, the configuration cost of declarative transaction
management is greatly reduced.
75
Programmatic Transaction Management
Programmatic means you have transaction management code surrounding your business code. This
gives extreme flexibility, but is difficult to maintain and, well, boilerplate.Declarative means you
separate transaction management from the business code. You can use annotations or XML based
configuration.
Declarative Transaction Management allows to eliminate any dependencies on the transaction
framework from the Java code. The four participants to provide the transaction support are
transaction manager, proxy factory, transaction interceptor, and a set of transaction attributes.
Suggest to use Declarative Transaction Management, Alternative for HibernateTemplates either
NamedJDBCTemplate or simpleJDBCTemplate
5. Describe the Spring Remoting technologies
Spring has integration classes for remoting support that use a variety of technologies. The Spring
framework simplifies the development of remote-enabled services. It saves a significant amount of
code by having its own API. The remote support simplifies the building of remote-enabled services,
which are implemented by your standard (Spring) POJOs. Spring now supports the following
remoting technologies:
Transparently expose your services across the RMI infrastructure by using Spring’s RMI support.
After you’ve done this, you’ll have a setup that’s similar to remote EJBs, except there’s no standard
support for security context propagation or remote transaction propagation. When utilizing the RMI
invoker, Spring provides hooks for such extra invocation context, so you may, for example, plug-in
security frameworks or custom security credentials.
76
Using the RmiServiceExporter to export the service.
Client-side service integration.
2. Using Hessian to call services remotely through HTTP
Spring has its own remoting service that supports HTTP serialization. HTTP Invoker makes use of
the classes HttpInvokerServiceExporter and HttpInvokerProxyFactoryBean.
• Configuring the DispatcherServlet for Hessian and company.
• Using the HessianServiceExporter to expose your beans
• Connecting the client to the service
3. Using Burlap
It is the same as Hessian but XML-based implementation provided by Coucho. The classes used in
Burlap are BurlapServiceExporter and BurlapProxyFactoryBean.
4. Using HTTP invokers to expose services
Spring HTTP invokers employ the regular Java serialization technique to expose services through
HTTP, as opposed to Burlap and Hessian, which are both lightweight protocols with their own
compact serialization mechanisms. This is especially useful if your arguments and return types are
complicated and cannot be serialized using the serialization procedures used by Hessian and Burlap
(refer to the next section for more considerations when choosing a remoting technology).
• Displaying the service object
• Client-side service integration
5. Exposing servlet-based web services using JAX-RPC
Spring provides a convenience base class for JAX-RPC servlet endpoint implementations –
ServletEndpointSupport. To expose our AccountService we extend Spring’s ServletEndpointSupport
class and implement our business logic here, usually delegating the call to the business layer.
Spring framework helps develop various types of applications using the Java platforms. It provides
an extensive level of infrastructure support. Spring also provides the “Plain Old Java Objects” (POJOs)
mechanisms using which developers can easily create the Java SE programming model with the full
and partial JAVA EE(Enterprise Edition). Spring strives to facilitate the complex and unmanageable
enterprise Java application development revolution by offering a framework that incorporates
technologies, such as:
77
Aspect-oriented Programming (AOP)
AOP provides more modularity to the cross-cutting challenges in applications.
Here are the functions we can use in our applications as per certain real-time challenges:
Logging
Caching
Transaction management
Authentication
AOP has the in-built object-oriented programming capabilities to define the structure of the
program, where OOP modularity is established in classes.
In AOP, the primary unit of modularity is a factor (cross-cutting concern). This allows users to use
AOP to build custom aspects and declarative enterprise services. The IoC container does not depend
on AOP; it provides the custom enabled based capabilities which allow writing logic as per the
programming method.
Dependency Injection is the core of Spring Framework. We can define the concept of Spring with
the Inversion of Control (IoC). DI allows the creation of dependent objects outside of a class and
provides those objects to a class in different ways. Dependency Injection can be utilized while
defining the parameters to the Constructor or by post-construction using Setter methods.
The dependency feature can be summarized into an association between two classes. For example,
suppose class X is dependent on class Y. Now, it can create many problems in the real world,
including system failure. Hence such dependencies need to be avoided. Spring IOC resolves such
dependencies with Dependency Injection. Here, it indicates that class Y will get injected into class X
by the IoC. DI thus makes the code easier to test and reuse.
While creating a complex Java application, application classes should be independent of other Java
classes to improve the possibility of reusing these classes and to test them independently of other
classes during unit testing. Dependency Injection enables these classes to be together, and at the
same time, keeps them independent.
Plain Old Java Object (POJO)
POJO stands for Plain Old Java Object. It is an ordinary Java object, not bound by any special
restriction other than those forced by the Java Language Specification and not requiring any
classpath. POJOs are used for increasing the readability and re-usability of a program. POJOs have
gained the most acceptance because they are easy to write and understand. They were introduced in
EJB 3.0 by Sun Microsystems.
78
Therefore, if there is no suitable module for solving a specific problem, or the existing one does not
fit exactly as needed, then a tech team can expand the existing module or write its own.
Speed.
Rapid start, fast shutdown, and optimized execution are the standard that Spring provides by
default. In addition, the Spring kit contains tools for speeding up iterations (LiveReload in Spring
DevTools) and getting a quick project start (Spring Initializr at start.spring.io).This way, Spring makes
Java faster, and therefore more productive.
Reliability.
Spring is a well-known DI container that retains most modern coding practices, which in turn leads
to testable and therefore more reliable code. Read more on https://tech-stack.com/blog/spring-
framework-for-enterprise-applications-main-benefits-to-get-and-common-mistakes-to-avoid/
A Spring MVC provides an elegant solution to use MVC in spring framework by the
help of DispatcherServlet. Here, DispatcherServlet is a class that receives the
incoming request and maps it to the right resource such as controllers, models, and
views.
o Model - A model contains the data of the application. A data can be a single
object or a collection of objects.
o Controller - A controller contains the business logic of an application. Here,
the @Controller annotation is used to mark the class as the controller.
o View - A view represents the provided information in a particular format.
Generally, JSP+JSTL is used to create a view page. Although spring also
supports other view technologies such as Apache Velocity, Thymeleaf and
FreeMarker.
79
o Front Controller - In Spring Web MVC, the DispatcherServlet class works as
the front controller. It is responsible to manage the flow of the Spring MVC
application.
Advantages
Separate roles - The Spring MVC separates each role, where the model object, controller, command
object, view resolver, DispatcherServlet, validator, etc. can be fulfilled by a specialized object.
Light-weight - It uses light-weight servlet container to develop and deploy your application.
Powerful Configuration - It provides a robust configuration for both framework and application
classes that includes easy referencing across contexts, such as from web controllers to business
objects and validators.
Rapid development - The Spring MVC facilitates fast and parallel development.
Reusable business code - Instead of creating new objects, it allows us to use the existing business
objects.
Easy to test - In Spring, generally we create JavaBeans classes that enable you to inject test data
using the setter methods.
Flexible Mapping - It provides the specific annotations that easily redirect the page.
80
8. What are the benefits of using Spring Security Application?
1. Proven technology, it’s better to use this than reinvent the wheel. Security is
something where we need to take extra care, otherwise our application will be
vulnerable for attackers.
2. Prevents some of the common attacks such as CSRF, session fixation
attacks.
3. Easy to integrate in any web application. We don’t need to modify web
application configurations, spring automatically injects security filters to the
web application.
4. Provides support for authentication by different ways - in-memory, DAO,
JDBC, LDAP and many more.
5. Provides option to ignore specific URL patterns, good for serving static HTML,
image files.
6. Support for groups and roles.
Authentication
Authentication is the process of verifying the Identity of a user or system.
Spring Security provides a wide range of authentication options, including
in-memory authentication, JDBC authentication, LDAP authentication,
and OAuth 2.0 authentication.
The authentication process typically involves the following steps
81
Spring Security provides support for role-based access control through the use
of annotations, configuration files, or expressions.
Permission-based access control: This strategy grants access to specific
resources based on the user’s permissions or privileges. Spring Security
supports permission-based access control through the use of annotations or
expressions.
Web access control: This is a specialized form of authorization that controls
access to web resources such as URLs or HTTP methods. Spring Security
provides support for web access control through the use of request-matching
rules and access control lists.
Part - C
82
Components of Spring
Core Container:
The Core Container consists of the Core, Beans, Context, and
Expression Language modules.
The Core and Beans modules provide the fundamental parts of the
framework, including the IoC and Dependency Injection features.
The BeanFactory is a sophisticated implementation of the factory pattern. It
removes the need for programmatic singletons and allows you to decouple
the configuration and specification of dependencies from your actual
program logic.
The Context module builds on the solid base provided by the Core and
Beans modules: it is a means to access objects in a framework-style
manner that is similar to a JNDI registry. The Context module inherits its
features from the Beans module and adds support for internationalization
(using, for example, resource bundles), event-propagation, resource-
loading, and the transparent creation of contexts by, for example, a servlet
container. The Context module also supports Java EE features such as
EJB, JMX ,and basic remoting. The ApplicationContext interface is the focal
point of the Context module.
83
The Expression Language module provides a powerful expression
language for querying and manipulating an object graph at runtime. It is an
extension of the unified expression language (unified EL) as specified in
the JSP 2.1 specification. The language supports setting and getting
property values, property assignment, method invocation, accessing the
context of arrays, collections and indexers, logical and arithmetic operators,
named variables, and retrieval of objects by name from Spring's IoC
container. It also supports list projection and selection as well as common
list aggregations.
Data Access/Integration
The Data Access/Integration layer consists of the JDBC, ORM, OXM,
JMS and Transaction modules.
The JDBC module provides a JDBC-abstraction layer that removes the
need to do tedious JDBC coding and parsing of database-vendor specific
error codes.
The ORM module provides integration layers for popular object-relational
mapping APIs, including JPA, JDO, Hibernate, and iBatis. Using the ORM
package you can use all of these O/R-mapping frameworks in combination
with all of the other features Spring offers, such as the simple declarative
transaction management feature mentioned previously.
The OXM module provides an abstraction layer that supports Object/XML
mapping implementations for JAXB, Castor, XMLBeans, JiBX and
XStream.
The Java Messaging Service (JMS) module contains features for producing
and consuming messages.
The Transaction module supports programmatic and declarative
transaction management for classes that implement special interfaces and
for all your POJOs (plain old Java objects).
Web
The Web layer consists of the Web, Web-Servlet, Web-Struts, and Web-
Portlet modules.
Spring's Web module provides basic web-oriented integration features
such as multipart file-upload functionality and the initialization of the IoC
container using servlet listeners and a web-oriented application context. It
also contains the web-related parts of Spring's remoting support.
84
The Web-Servlet module contains Spring's model-view-controller (MVC)
implementation for web applications. Spring's MVC framework provides a
clean separation between domain model code and web forms, and
integrates with all the other features of the Spring Framework.
The Web-Struts module contains the support classes for integrating a
classic Struts web tier within a Spring application. Note that this support is
now deprecated as of Spring 3.0. Consider migrating your application to
Struts 2.0 and its Spring integration or to a Spring MVC solution.
The Web-Portlet module provides the MVC implementation to be used in
a portlet environment and mirrors the functionality of Web-Servlet module.
85
configuration metadata to produce a fully configured and executable system or
application.
Internationalization No Yes
Automatic BeanPostProcessor
No Yes
registration
Automatic
BeanFactoryPostProcessor No Yes
registration
87