0% found this document useful (0 votes)
70 views25 pages

Question Bank-Part A (2 Marks) - Unit II Struts and Hibernate

The document discusses Struts and Hibernate frameworks. It provides questions and answers related to key concepts in Struts like MVC architecture, components, roles of ActionServlet, ActionForm, Action class, ActionMapping etc. For Hibernate, it covers concepts like ORM tools, advantages over JDBC, query language, inheritance models etc.

Uploaded by

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

Question Bank-Part A (2 Marks) - Unit II Struts and Hibernate

The document discusses Struts and Hibernate frameworks. It provides questions and answers related to key concepts in Struts like MVC architecture, components, roles of ActionServlet, ActionForm, Action class, ActionMapping etc. For Hibernate, it covers concepts like ORM tools, advantages over JDBC, query language, inheritance models etc.

Uploaded by

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

Question Bank- Part A (2 Marks) - Unit II Struts and Hibernate:

1.List out the benefits of struts framework.


The Struts Framework is a standard for developing well-architected Web applications. It has the
following features:
- Open source
- Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all
three levels:
Model: application state
View: presentation of data (JSP, HTML)
Controller: routing of the application flow
- Implements the JSP Model 2 Architecture
- Stores application routing information and request mapping in a single core file, strutsconfig.xml
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left
to the developer.
2. What are the components of struts?
Base framework, JSP Tag library, Tiles plug in, Validator plug in
3.What is role of ActionServlet?
The ActionServlet takes the following steps :
1. First, the ActionServlet checks the user's Session to see if an instance of
the ActionForm already exists. A new Bean will be created if none exists, and the
new Bean will be added to the user's Session.
2. The next step is that the request parameters are examined. For each request parameter that has
a corresponding named property in the Bean, the setter method is called.
3. If the validation is turned on once the properties are set, then the validate() method of
the ActionForm is called. The validate()method is used to validate any necessary fields prior to
the Action's execute() method being called by the ActionServlet.
- If the validation fails, then the request never makes it to the Action for processing.
- If the validation succeeds, then the updated ActionForm Bean is passed as a parameter to the

appropriate Action class in theexecute() method signature. The Action class can then pull out
whatever information is necessary from the ActionForm.

4.What is the ActionForm?


These greatly simplify user form validation by capturing user data from the HTTP request. They
act as a "firewall" between forms (Web pages) and the application (actions). These components
allow the validation of user input before proceeding to an Action. If the input is invalid, a page
with an error can be displayed.

5.Mention the need for ActionForward Class.


An ActionForward represents a destination to which the controller, RequestProcessor, might be
directed to perform a RequestDispatcher.forward or HttpServletResponse.sendRedirect to, as a
result of processing activities of an Action class. Instances of this class may be created
dynamically as necessary, or configured in association with an ActionMapping instance for
named lookup of potentially multiple destinations for a particular mapping instance.
An ActionForward has the following minimal set of properties. Additional properties can be
provided as needed by subclassses.
contextRelative - Should the path value be interpreted as context-relative (instead of modulerelative, if it starts with a '/' character? [false]
name - Logical name by which this instance may be looked up in relationship to a particular
ActionMapping.
path - Module-relative or context-relative URI to which control should be forwarded, or an
absolute or relative URI to which control should be redirected.
redirect - Set to true if the controller servlet should call HttpServletResponse.sendRedirect() on
the associated path; otherwise false. [false]

6. What is the role of Action Class?


An Action is an adapter between the contents of an incoming HTTP request and the
corresponding business logic that should be executed to process it. Think of each Action as the
glue between the client request and the business logic that must be performed. Actions are
usually thin classes with most of the business logic being performed in a separate JavaBean or
EJB. The ActionServlet selects an appropriate Action for each request, creates an instance (if
necessary), and calls the execute() method.

7. What is ActionMapping?

An ActionMapping represents the information that the controller, RequestProcessor, knows about
the mapping of a particular request to an instance of a particular Action class. The
ActionMapping instance used to select a particular Action is passed on to that Action, thereby
providing access to any custom configuration information included with the ActionMapping
object.
ActionMapping object contains all the mapping information in struts_config.xml. ActionServlet
create the instance of ActionMapping and load all the struts_config.xml data to ActionMapping
object.
8. What are the different kinds of actions in struts?
We have following types of action classes in struts:
Action - The basic action class in which we implement our business logic.
Include Action - Similar as include page directive in jsp.
Forward Action - Used in case we need to forward the request from one JSP to another. If we
directly forward the request from one jsp it violates the MVC architecture. Hence an action class
is used to do this job.
Dispatch Action - Handles multiple operations in multiple methods. It is better to have one
method per operation instead of merging the entire business logic in a single execute method of
an action class.
Look up Dispatch Action - Same as dispatch action but recommended not to use.
Switch Action - used to switch between different modules in struts application.
9. What are the five steps involved in Tiles Framework.
Step 1. Enable the Tiles Plug-in
Step 2.Create Tiles Definitions
Step 3.Create layout JSP and use the Tiles Tag Library
Step 4. Create content JSP to fill in the layout JSP
Step 5. Use the Tiles definitions

10. Why do you need ORM tools like hibernate?


When we work with an object-oriented systems, there's mismatch between the object model and
the relational database. RDBMSs represent data in a tabular format whereas object-oriented
languages, such as Java or C# represent it as an interconnected graph of objects.
11. What does Hibernate simplify?

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open


source persistent framework created by Gavin King in 2001. It is a powerful, high performance
Object-Relational Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and
relieve the developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the work in
persisting those objects based on the appropriate O/R mechanisms and patterns.

12. What is the advantage of Hibernate over jdbc?


Hibernate takes care of mapping Java classes to database tables using XML files and without
writing any line of code.
Provides simple APIs for storing and retrieving Java objects directly to and from the database.
If there is change in Database or in any table then the only need to change XML file properties.
Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Minimize database access with smart fetching strategies.
Provides Simple querying of data.
13. What is Hibernate Query Language?
Hibernate Query Language (HQL) is an object-oriented query language, similar to SQL, but
instead of operating on tables and columns, HQL works with persistent objects and their
properties. HQL queries are translated by Hibernate into conventional SQL queries which in
turns perform action on database.
Although you can use SQL statements directly with Hibernate using Native SQL but I would
recommend to use HQL whenever possible to avoid database portability hassles, and to take
advantage of Hibernate's SQL generation and caching strategies.
14. What are the types of inheritance models in Hibernate?
There are three types of inheritance mapping in hibernate
1. Table per concrete class with unions
2. Table per class hierarchy
3. Table per subclass

Question Bank - Part B (8 Marks) - Unit II Struts and Hibernate:

1. Explain Model 1 and Model 2 (MVC) Architecture in detail with an example (8).
Before developing the web applications, we need to have idea about design models. There are two types
of programming models (design models)
Model 1 Architecture:
Servlet and JSP are the main technologies to develop the web applications.
Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it creates thread
to handle request. The advantage of creating thread over process is that it doesn't allocate separate
memory area. Thus many subsequent requests can be easily handled by servlet.
Problem in Servlet technology Servlet needs to recompile if any designing code is modified. It doesn't
provide separation of concern. Presentation and Business logic are mixed up.
JSP overcomes almost all the problems of Servlet. It provides better separation of concern, now
presentation and business logic can be easily separated. You don't need to redeploy the application if JSP
page is modified. JSP provides support to develop web application using JavaBean, custom tags and JSTL
so that we can put the business logic separate from our JSP that will be easier to test and debug.

As you can see in the above figure, there is picture which show the flow of the model1 architecture.
1. Browser sends request for the JSP page
2. JSP accesses Java Bean and invokes business logic
3. Java Bean connects to the database and get/save data
4. Response is sent to the browser which is generated by JSP

Advantage of Model 1 Architecture

Easy and Quick to develop web application

Disadvantage of Model 1 Architecture

Navigation control is decentralized since every page contains the logic to determine the next
page. If JSP page name is changed that is referred by other pages, we need to change it in all the
pages that leads to the maintenance problem.

Time consuming You need to spend more time to develop custom tags in JSP. So that we don't
need to use scriptlet tag.

Hard to extend It is better for small applications but not for large applications.

Model 2 (MVC) Architecture:


Model 2 is based on the MVC (Model View Controller) design pattern. The MVC design pattern consists
of three modules model, view and controller.
Model The model represents the state (data) and business logic of the application.
View The view module is responsible to display data i.e. it represents the presentation.
Controller The controller module acts as an interface between view and model. It intercepts all the
requests i.e. receives input and commands to Model / View to change accordingly.

Advantage of Model 2 (MVC) Architecture

Navigation control is centralized Now only controller contains the logic to determine the next
page.

Easy to maintain

Easy to extend

Easy to test

Better separation of concerns

Disadvantage of Model 2 (MVC) Architecture

We need to write the controller code self. If we change the controller code, we need to recompile
the class and redeploy the application.

Example of MVC using Servlet and JSP:


In this example, we are using servlet as a controller, jsp as a view component, Java Bean class as a
model.
In this example, we have created 5 pages:

index.jsp a page that gets input from the user.

ControllerServlet.java a servlet that acts as a controller.

login-success.jsp and login-error.jsp files acts as view components.

web.xml file for mapping the servlet.

File: index.jsp
1.
2.
3.
4.
5.

<form action="ControllerServlet" method="post">


Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
<input type="submit" value="login">
</form>

File: ControllerServlet
1.
2.
3.
4.
5.

package com.javatpoint;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;

6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.
36.
37.
38.
39.
40.
41.

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ControllerServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String name=request.getParameter("name");
String password=request.getParameter("password");
LoginBean bean=new LoginBean();
bean.setName(name);
bean.setPassword(password);
request.setAttribute("bean",bean);
boolean status=bean.validate();
if(status){
RequestDispatcher rd=request.getRequestDispatcher("login-success.jsp");
rd.forward(request, response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("login-error.jsp");
rd.forward(request, response);
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
doPost(req, resp);
}
}

File: LoginBean.java
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.

package com.javatpoint;
public class LoginBean {
private String name,password;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {

12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.

return password;
}
public void setPassword(String password) {
this.password = password;
}
public boolean validate(){
if(password.equals("admin")){
return true;
}
else{
return false;
}
}
}

File: login-success.jsp
1.
2.
3.
4.
5.
6.
7.

<%@page import="com.javatpoint.LoginBean"%>
<p>You are successfully logged in!</p>
<%
LoginBean bean=(LoginBean)request.getAttribute("bean");
out.print("Welcome, "+bean.getName());
%>

File: login-error.jsp
1. <p>Sorry! username or password error</p>
2. <%@ include file="index.jsp" %>
File: web.xml
1. <?xml version="1.0" encoding="UTF-8"?>
2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/webapp_2_5.xsd"
4. xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/webapp_3_0.xsd"
5. id="WebApp_ID" version="3.0">
6.
7. <servlet>
8. <servlet-name>s1</servlet-name>
9. <servlet-class>com.javatpoint.ControllerServlet</servlet-class>
10. </servlet>
11. <servlet-mapping>
12. <servlet-name>s1</servlet-name>
13. <url-pattern>/ControllerServlet</url-pattern>
14. </servlet-mapping>
15. </web-app>

2. Explain Struts Framework in detail(16)


The struts framework was initially created by Craig McClanahan and donated to Apache Foundation in
May, 2000 and Struts 1.0 was released in June 2001.
The current stable release of Struts is Struts 2.3.16.1 in March 2, 2014.
What Is the Struts Framework?
The Struts Framework is a standard for developing well-architected Web applications. It has the following
features:

Open source
Based on the Model-View-Controller (MVC) design paradigm, distinctly separating all three
levels:
o Model: application state
o View: presentation of data (JSP, HTML)
o Controller: routing of the application flow
Implements the JSP Model 2 Architecture
Stores application routing information and request mapping in a single core file, struts-config.xml
The Struts Framework, itself, only fills in the View and Controller layers. The Model layer is left to the
developer.
Struts Components:
The Controller
This receives all incoming requests. Its primary function is the mapping of a request URI to an action
class selecting the proper application module. It's provided by the framework.
The struts-config.xml File
This file contains all of the routing and configuration information for the Struts application. This XML
file needs to be in the WEB-INF directory of the application.

Action Classes
It's the developer's responsibility to create these classes. They act as bridges between user-invoked URIs
and business services. Actions process a request and return an ActionForward object that identifies the
next component to invoke. They're part of the Controller layer, not the Model layer.
View Resources
View resources consist of Java Server Pages, HTML pages, JavaScript and Stylesheet files, Resource
bundles, JavaBeans, and Struts JSP tags.
ActionForms
These greatly simplify user form validation by capturing user data from the HTTP request. They act as a
"firewall" between forms (Web pages) and the application (actions). These components allow the
validation of user input before proceeding to an Action. If the input is invalid, a page with an error can be
displayed.
Model Components
The Struts Framework has no built-in support for the Model layer. Struts supports any model components:

JavaBeans
EJB
CORBA
JDO
any other

Model Action classes


View - Action form classes
Controller Action Servlet classes
Architecture Overview:

All incoming requests are intercepted by the Struts servlet controller. The Struts Configuration
file struts-config.xml is used by the controller to determine the routing of the flow.

This flow consists of an alternation between two transitions:

From View to Action

A user clicks on a link or submits a form on an HTML or JSP page. The


controller receives the request, looks up the mapping for this request, and
forwards it to an action. The action in turn calls a Model layer (Business
layer) service or function.

From Action to View

After the call to an underlying function or service returns to the action class,
the action forwards to a resource in the View layer and a page is displayed in
a web browser.

The diagram below describes the flow in more detail:

1. User clicks on a link in an HTML page.


2. Servlet controller receives the request, looks up mapping information in struts-config.xml, and
routes to an action.
3. Action makes a call to a Model layer service.
4. Service makes a call to the Data layer (database) and the requested data is returned.
5. Service returns to the action.
6. Action forwards to a View resource (JSP page)
7. Servlet looks up the mapping for the requested resource and forwards to the appropriate JSP
page.
8. JSP file is invoked and sent to the browser as HTML.
9. User is presented with a new HTML page in a web browser.

9. What is JDBC? (16)


JDBC stands for Java Database Connectivity and provides a set of Java API for accessing the
relational databases from Java program. These Java APIs enables Java programs to execute SQL
statements and interact with any SQL compliant database.
JDBC provides a flexible architecture to write a database independent application that can run on
different platforms and interact with different DBMS without any modification.
Pros and Cons of JDBC
Pros of JDBC

Cons of JDBC

Clean and
processing

SQL

Complex if it is used in large


projects

Good performance with large


data

Large programming overhead

No encapsulation

Hard to
concept

Query is DBMS specific

Very
good
applications

simple

for

small

Simple syntax so easy to


learn

implement

MVC

10. Why Object Relational Mapping (ORM)? (8)


When we work with an object-oriented systems, there's a mismatch between the object model and the
relational database. RDBMSs represent data in a tabular format whereas object-oriented languages, such
as Java or C# represent it as an interconnected graph of objects. Consider the following Java Class with
proper constructors and associated public function:
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;

public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}
public int getId() {
return id;
}
public String getFirstName() {
return first_name;
}
public String getLastName() {
return last_name;
}
public int getSalary() {
return salary;
}}

Consider above objects need to be stored and retrieved into the following RDBMS table:
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary

INT default NULL,

PRIMARY KEY (id)


);

First problem, what if we need to modify the design of our database after having developed few pages or
our application? Second, Loading and storing objects in a relational database exposes us to the following
five mismatch problems.
Mismatch

Description

Granularity

Sometimes you will have an object model which has more classes
than the number of corresponding tables in the database.

Inheritance

RDBMSs do not define anything similar to Inheritance which is a


natural paradigm in object-oriented programming languages.

Identity

A RDBMS defines exactly one notion of 'sameness': the primary


key. Java, however, defines both object identity (a==b) and object
equality (a.equals(b)).

Associations

Object-oriented languages represent associations using object


references where as am RDBMS represents an association as a
foreign key column.

Navigation

The ways you access objects in Java and in a RDBMS are


fundamentally different.

The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.

11.What is ORM? (8)


ORM stands for Object-Relational Mapping (ORM) is a programming technique for converting data
between relational databases and object oriented programming languages such as Java, C# etc. An ORM
system has following advantages over plain JDBC
S.N.

Advantages

Lets business code access objects rather than DB tables.

Hides details of SQL queries from OO logic.

Based on JDBC 'under the hood'

No need to deal with the database implementation.

Entities based on business concepts rather than database structure.

Transaction management and automatic key generation.

Fast development of application.

An ORM solution consists of the following four entities:


S.N.

Solutions

An API to perform basic CRUD operations on objects of persistent classes.

A language or API to specify queries that refer to classes and properties of


classes.

A configurable facility for specifying mapping metadata.

A technique to interact with transactional objects to perform dirty


checking, lazy association fetching, and other optimization functions.

Java ORM Frameworks:


There are several persistent frameworks and ORM options in Java. A persistent framework is an ORM
service that stores and retrieves objects into a relational database.

Enterprise JavaBeans Entity Beans

Java Data Objects

Castor

TopLink

Spring DAO

Hibernate

And many more

12. What is Hibernate? (8)

Hibernate is an Object-Relational Mapping(ORM) solution for JAVA and it raised as an open source
persistent framework created by Gavin King in 2001. It is a powerful, high performance ObjectRelational Persistence and Query service for any Java Application.
Hibernate maps Java classes to database tables and from Java data types to SQL data types and relieve
the developer from 95% of common data persistence related programming tasks.
Hibernate sits between traditional Java objects and database server to handle all the work in persisting
those objects based on the appropriate O/R mechanisms and patterns.

Hibernate Advantages:
Hibernate takes care of mapping Java classes to database tables using XML files and without writing any
line of code.
Provides simple APIs for storing and retrieving Java objects directly to and from the database.
If there is change in Database or in any table then the only need to change XML file properties.
Abstract away the unfamiliar SQL types and provide us to work around familiar Java Objects.
Hibernate does not require an application server to operate.
Manipulates Complex associations of objects of your database.
Minimize database access with smart fetching strategies.
Provides Simple querying of data.
Supported Databases:
Hibernate supports almost all the major RDBMS. Following is 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
Supported Technologies:

Hibernate supports a variety of other technologies, including the following:


XDoclet Spring
J2EE
Eclipse plug-ins
Maven

13. Explain Hibernate Architecture in detail (16)


The Hibernate architecture is layered to keep you isolated from having to know the underlying APIs.
Hibernate makes use of the database and configuration data to provide persistence services (and
persistent objects) to the application.
Following is a very high level view of the Hibernate Application Architecture.

Following is a detailed view of the Hibernate Application Architecture with few important core classes.

Hibernate uses various existing Java APIs, like JDBC, Java Transaction API(JTA), and Java Naming and
Directory Interface (JNDI). JDBC provides a rudimentary level of abstraction of functionality common
to relational databases, allowing almost any database with a JDBC driver to be supported by Hibernate.
JNDI and JTA allow Hibernate to be integrated with J2EE application servers.
Following section gives brief description of each of the class objects involved in Hibernate Application
Architecture.
Configuration Object:
The Configuration object is the first Hibernate object you create in any Hibernate application and usually
created only once during application initialization. It represents a configuration or properties file
required by the Hibernate. The Configuration object provides two keys components:

Database Connection: This is handled through one or more configuration files supported by
Hibernate. These files arehibernate.properties and hibernate.cfg.xml.

Class Mapping Setup


This component creates the connection between the Java classes and database tables..

SessionFactory Object:
Configuration object is used to create a SessionFactory object which inturn configures Hibernate for the
application using the supplied configuration file and allows for a Session object to be instantiated. The
SessionFactory is a thread safe object and used by all the threads of an application.
The SessionFactory is heavyweight object so usually it is created during application start up and kept for
later use. You would need one SessionFactory object per database using a separate configuration file. So
if you are using multiple databases then you would have to create multiple SessionFactory objects.
Session Object:
A Session is used to get a physical connection with a database. The Session object is lightweight and
designed to be instantiated each time an interaction is needed with the database. Persistent objects are
saved and retrieved through a Session object.
The session objects should not be kept open for a long time because they are not usually thread safe and
they should be created and destroyed them as needed.
Transaction Object:
A Transaction represents a unit of work with the database and most of the RDBMS supports transaction
functionality. Transactions in Hibernate are handled by an underlying transaction manager and
transaction (from JDBC or JTA).
This is an optional object and Hibernate applications may choose not to use this interface, instead
managing transactions in their own application code.
Query Object:
Query objects use SQL or Hibernate Query Language (HQL) string to retrieve data from the database
and create objects. A Query instance is used to bind query parameters, limit the number of results
returned by the query, and finally to execute the query.
Criteria Object:
Criteria object are used to create and execute object oriented criteria queries to retrieve objects.

You might also like