Question Bank-Part A (2 Marks) - Unit II Struts and Hibernate
Question Bank-Part A (2 Marks) - Unit II Struts and Hibernate
appropriate Action class in theexecute() method signature. The Action class can then pull out
whatever information is necessary from the ActionForm.
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
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
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.
Navigation control is centralized Now only controller contains the logic to determine the next
page.
Easy to maintain
Easy to extend
Easy to test
We need to write the controller code self. If we change the controller code, we need to recompile
the class and redeploy the application.
File: index.jsp
1.
2.
3.
4.
5.
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>
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
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.
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.
Cons of JDBC
Clean and
processing
SQL
No encapsulation
Hard to
concept
Very
good
applications
simple
for
small
implement
MVC
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
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
Identity
Associations
Navigation
The Object-Relational Mapping (ORM) is the solution to handle all the above impedance mismatches.
Advantages
Solutions
Castor
TopLink
Spring DAO
Hibernate
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:
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.
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.