SlideShare a Scribd company logo
QUESTION BANK
UNIT –V
Q.1 Explain the architecture of EJB
Ans: A bean runs in a container. The container, which is part of the EJB server, provides a number of
services to the bean. These include transaction services, synchronization services, and security.
To provide these services, the bean container must be able to intercept calls
to bean methods. For example, a client application calls a bean method that
has a transaction attribute that requires the bean to create a new transaction
context. The bean container must be able to interpose code to start a new
transaction before the method call, and to commit the transaction, if possible,
when the method completes, and before any values are returned to the client.
For this reason and others, a client application does not call the remote bean
methods directly. Instead, the client invokes the bean method through a twostep process mediated
by the ORB and by the container.
 First, the client actually calls a local proxy stub for the remote method. The stub marshalls
any parameter data, and then calls a remote skeleton on the server. The skeleton
unmarshalls the data, and upcalls to the bean container.This step is required because of the
remote nature of the call. Note that this step is completely transparent both to the client
application developer as well as to the bean developer. It is a detail that you do not need to
know about to write your application code, either on the client or the server. Nevertheless, it
is useful to know what is going on, especially when it comes to understanding what happens
during bean deployment.
 In the second step, the bean container gets the skeleton upcall, then
interposes whatever services are required by the context. These can
include:
1. authenticating the client, on the first method call
2. performing transaction management
3. calling synchronization methods in the bean itself
4. identity checks and switch
 The container then delegates the method call to the bean. The bean method executes. When
it returns, the thread of control returns to the bean container,which interposes whatever
services are required by the context. For example,if the method is running in a transaction
context, the bean container performs a commit operation, if possible. This depends on the
transaction attributes in the bean descriptor.
 Then the bean container calls the skeleton, which Marshalls return data, and returns it to the
client stub.
These steps are completely invisible to client-side and server-side application
developers. One of the major advantages of the EJB development model is
that it hides the complexity of transaction and identity management from
developers.
Q.2 What are the different types of Enterprise Java Beans ? Explain
Ans: Types of EJB:
1. Session
2. Entity
3. Message-Driven
1. Session EJBs
A session EJB is a nonpersistent object: Its lifetime is the duration of a particular interaction
between the client and the EJB. The client normally creates an EJB, calls methods on it, and then
removes it. If the client fails to remove it, the EJB container will remove it after a certain period of
inactivity. Session EJBs are subdivided into ‘stateful’ and ‘stateless’ types. A stateless session EJB is
shared amongst a number of clients, while a stateful session EJB is created for a specific client and
not used by any others. The use of stateless EJBs offers efficiency advantages but, of course, it is not
always possible to use them.
2. Entity EJBs
Entity EJBs represent persistent objects: Their lifetimes are not related to the duration of interaction
with clients. In nearly all cases, entity EJBs are synchronized with relational databases. This is how
persistence is achieved. Entity EJBs are always shared amongst clients: A client cannot get an entity
EJB to itself. Thus, entity EJBs are nearly always used as a scheme for
mapping relational databases into object-oriented applications. Whereas a client normally creates a
session EJB and removes it after use, clients normally look up an existing entity EJB. Creation of an
entity EJB corresponds to adding new data items to the application (e.g., adding rows to database
tables). An important feature of entity EJBs is that they have identity—that is, one can be
distinguished from another. This is implemented by assigning a primary key to each instance of the
EJB, where ‘primary key’ has the same meaning as it does for database management. Primary keys
that identify EJBs can be of any type, including programmer-defined classes.
3. Message-driven EJBs
A message-driven bean acts as a consumer of asynchronous messages: It cannot be called directly
by clients, but is activated by the container when a message arrives. Clients interact with these EJBs
by sending messages to the queues or topics to which they are listening. Although a message-driven
EJB cannot be called directly by clients, it can call other EJBs itself. Messagedriven EJBs are the only
type that does not follow a strict request-response interaction with clients.
Q.3 What is facelet ? what are its features?
Ans: Features:
 Server-side helper classes, such as database access beans
 A custom tag library for rendering UI components on a page
 A custom tag library for representing event handlers, validators , and other actions
 UI components represented as stateful objects on the server
 Backing beans, which define properties and functions for UI components
 Validators, converters, event listeners, and event handlers
 An application configuration resource file for configuring application resources
Q.4 Explain the life cycle of JSF
Ans:
Phase 1: Restore view
 JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a
request.
 During this phase, the JSF builds the view, wires event handlers and validators to UI
components and saves the view in the FacesContext instance. The FacesContext instance will
now contains all the information required to process a request.
Phase 2: Apply request values
 After the component tree is created/restored, each component in component tree uses
decode method to extract its new value from the request parameters. Component stores this
value. If the conversion fails, an error message is generated and queued on FacesContext.
This message will be displayed during the render response phase, along with any validation
errors.
 If any decode methods / event listeners called renderResponse on the current FacesContext
instance, the JSF moves to the render response phase.
Phase 3: Process validation
 During this phase, the JSF processes all validators registered on component tree. It examines
the component attribute rules for the validation and compares these rules to the local value
stored for the component.
 If the local value is invalid, the JSF adds an error message to the FacesContext instance, and
the life cycle advances to the render response phase and display the same page again with
the error message.
Phase 4: Update model values
 After the JSF checks that the data is valid, it walks over the component tree and set the
corresponding server-side object properties to the components' local values. The JSF will
update the bean properties corresponding to input component's value attribute.
 If any updateModels methods called renderResponse on the current FacesContext instance,
the JSF moves to the render response phase.
Phase 5: Invoke application
 During this phase, the JSF handles any application-level events, such as submitting a form /
linking to another page.
Phase 6: Render response
 During this phase, the JSF asks container/application server to render the page if the
application is using JSP pages. For initial request, the components represented on the page
will be added to the component tree as the JSP container executes the page. If this is not an
initial request, the component tree is already built so components need not to be added
again. In either case, the components will render themselves as the JSP container/Application
server traverses the tags in the page.
 After the content of the view is rendered, the response state is saved so that subsequent
requests can access it and it is available to the restore view phase.
Q.5 How does JSF application gets executed ? Explain
Ans: The hello example JSF application goes through the following stages when it is deployed on the
GlassFish Server.
1. When the hello application is built and deployed on the GlassFish Server, the application is in an
uninitiated state.
2. When a client makes an initial request for the beanhello.xhtml web page, the hello Facelets
application is compiled.
3. The compiled Facelets application is executed, and a new component tree is constructed for
the hello application and is placed in ajavax.faces.context.FacesContext.
4. The component tree is populated with the component and the managed bean property
associated with it, represented by the EL expression hello.world.
5. A new view is built, based on the component tree.
6. The view is rendered to the requesting client as a response.
7. The component tree is destroyed automatically.
8. On subsequent (postback) requests, the component tree is rebuilt, and the saved state is applied.
Q.6 Write a session bean code specification that calculates compound interest. Assume principal,
terms and rate of interest is entered by the user and the input is passed through a servlet
Ans: Clacjsp.jsp: // jsp web page created
<form action="calcservlet" method="post">
Principal: <input type="text" name="t1"/>
Rate: <input type="text" name="t2"/>
No_of_years: <input type="text" name="t3"/>
<input type="submit" name="submit"/>
</form>
Calcservlet.java: // servlet file created
package mybean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class calcservlet extends HttpServlet {
@EJB
private simpleLocal simple;
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet calcservlet</title>");
out.println("</head>");
out.println("<body>");
Double a=Double.parseDouble(request.getParameter("t1"));
Double b=Double.parseDouble(request.getParameter("t2"));
Double c=Double.parseDouble(request.getParameter("t3"));
out.println("<h1>Simple Interest = " + simple.calcsimple(a, b, c)+ "</h1>");
out.println("</body>");
out.println("</html>");
}
}
}
Simple.java : // bean created
package mybean;
import javax.ejb.Stateless;
import java.util.Scanner;
@Stateless
public class simple implements simpleLocal {
@Override
public Double calccomp(double a, double b, double c) {
double ci=a*Math.pow((1+b/100),c);
return ci;
} }
Q.7. Write the benefits of using EJB
Ans: For several reasons, enterprise beans simplify the development of large, distributed applications.
 because the EJB container provides system-level services to enterprise beans, the bean
developer can concentrate on solving business problems. The EJB container, rather than the
bean developer, is responsible for system-level services, such as transaction management
and security authorization.
 because the beans rather than the clients contain the application’s business logic, the client
developer can focus on the presentation of the client. The client developer does not have to
code the routines that implement business rules or access databases. As a result, the clients
are thinner, a benefit that is particularly important for clients that run on small devices.
 because enterprise beans are portable components, the application assembler can build new
applications from existing beans. Provided that they use the standard APIs, these
applications can run on any compliant Java EE server.
Q.8 Create a JSF application for checking the validity of the user
Ans: Example:
<%@ page contentType="text/html"%>
<%@ tagliburi="http://java.sun.com/jsf/core" prefix="f"%>
<%@ tagliburi="http://java.sun.com/jsf/html" prefix="h"%>
<f:view>
<html>
<head><title>JSF Login Application</title></head>
<body> <h:form>
<h:panelGroup rendered="#{login.validationComplete and (!login.isUsernameValid or
!login.isPasswordValid)}">
<h:outputText value="Username is a Required Field" rendered="#{!login.isUsernameValid}"
style="color:red"></h:outputText> <br>
<h:outputText value="Password is a Required Field" rendered="#{!login.isPasswordValid}"
style="color:red"></h:outputText>
</h:panelGroup>
<h:panelGroup rendered="#{login.validationComplete and (login.isUsernameValid and
login.isPasswordValid)}">
<h:outputText value="Username & Password are valid" style="color:green"></h:outputText>
</h:panelGroup>
<table>
<tr>
<td><h:outputText value="Enter Username: " /></td>
<td><h:inputText id="username" value="#{login.username}" /> </td>
</tr>
<tr>
<td><h:outputText value="Enter Password: " /></td>
<td><h:inputSecret id="password" value="#{login.password}" /> </td>
</tr>
<tr>
<td> </td>
<td><h:commandButton value="Login" action="#{login.checkValidity}"/> </td>
</tr>
</table>
</h:form> </body>
</html>
</f:view>
1. <%@ tagliburi="http://java.sun.com/jsf/core" prefix="f"%>
<%@ tagliburi="http://java.sun.com/jsf/html" prefix="h"%>
This line links to the jsf core and jsf html tag libraries. The jsf html tag library
carries regular html components like text box, buttons, etc.
2. <f:view></f:view>
This tag at the beginning of the document acts as a container for all the
components enclosed between them.
3. <h:panelGroup rendered="#{login.validationComplete and (!login.isUsernameValid or
!login.isPasswordValid)}">
<h:outputText value="Username is a Required Field"
rendered="#{!login.isUsernameValid}" style="color:red"></h:outputText> <br>
<h:outputText value="Password is a Required Field"
rendered="#{!login.isPasswordValid}" style="color:red"></h:outputText>
</h:panelGroup>
The above code snippet is intended to display error and success messages. The
first part displays the error messages one after the other. The second part
displays a single success message. This code uses Expression Language (EL) to
do conditional checks and reference the managed bean values.
4. <h:panelGroup rendered="#{login.validationComplete and (login.isUsernameValid and
login.isPasswordValid)}">
<h:outputText value="Username & Password are valid"
style="color:green"></h:outputText> </h:panelGroup>
The following line in the above code snippet checks to see if the validation failed
before displaying the error messages
Q.9 Explain with suitable example <navigation-rule> element of faces-config.xml file of JSF
Ans:  Navigation between different pages of a Java Server Faces application, such as choosing the
next page to be displayed after a button or hyperlink component is clicked, is defined by a set
of rules.
 Navigation rules can be implicit, or they can be explicitly defined in the application
configuration resource file.
 These navigation rules are defined in JSF configuration files along with other definitions for a
JSF application. Usually, this file is named faces-config.xml.
Here is a navigation rule that could be used with the example just described:
<navigation-rule>
<from-view-id>/login.xhtml</from-view-id>
<navigation-case>
<from-action>#{LoginForm.login}</from-action>
<from-outcome>success</from-outcome>
<to-view-id>/storefront.xhtml</to-view-id>
</navigation-case>
<navigation-case>
<from-action>#{LoginForm.logon}</from-action>
<from-outcome>failure</from-outcome>
<to-view-id>/logon.xhtml</to-view-id>
</navigation-case>
</navigation-rule>
This navigation rule defines the possible ways to navigate from login.xhtml. Each navigation-
case element defines one possible navigation path fromlogin.xhtml. The first navigation-case says
that if LoginForm.login returns an outcome of success, then storefront.xhtml will be accessed. The
second navigation-case says that login.xhtml will be re-rendered
if LoginForm.login returns failure.
QUESTION BANK
UNIT –VI
Q.1 Explain the Hibernate Framework
Ans:
 Hibernate is an Object-relational mapping (ORM) tool. Object-relational mapping or ORM is
a programming method for mapping the objects to the relational model where
entities/classes are mapped to tables, instances are mapped to rows and attributes of
instances are mapped to columns of table.
 A “virtual object database” is created that can be used from within the programming
language.
 Hibernate is a persistence framework which is used to persist data from Java environment
to database. Persistence is a process of storing the data to some permanent medium and
retrieving it back at any point of time even after the application that had created the data
ended.
 The above diagram shows a comprehensive architecture of Hibernate. In order to persist
data to a database, Hibernate create an instance of entity class(Java class mapped with
database table). This object is called Transient object as they are not yet associated with the
session or not yet persisted to a database.
 To persist the object to database, the instance of SessionFactory interface is created.
SessionFactory is a singleton instance which implements Factory design pattern.
SessionFactory loads hibernate.cfg.xml file(Hibernate configuration file. More details in
following section) and with the help of TransactionFactory and ConnectionProvider
implements all the configuration settings on a database.
 Each database connection in Hibernate is created by creating an instance of Session
interface. Session represents a single connection with database.Session objects are created
from SessionFactory object.
 Hibernate also provides built-in Transaction APIs which abstracts away the application from
underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of
work. One Session can span through multiple transactions.
SessionFactory (org.hibernate.SessionFactory)
A thread-safe, immutable cache of compiled mappings for a single database. A factory for
org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider.
Optionally maintains a second level cache of data that is reusable between transactions at a
process or cluster level.
Session (org.hibernate.Session)
A single-threaded, short-lived object representing a conversation between the application and the
persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction.
Maintains a first level cache of persistent the application’s persistent objects and collections; this
cache is used when navigating the object graph or looking up objects by identifier.
Persistent objects and collections
Short-lived, single threaded objects containing persistent state and business function. These can be
ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the
org.hibernate.Session is closed, they will be detached and free to use in any application layer (for
example, directly as data transfer objects to and from presentation).
Transient and detached objects and collections
Instances of persistent classes that are not currently associated with a org.hibernate.Session. They
may have been instantiated by the application and not yet persisted, or they may have been
instantiated by a closed org.hibernate.Session.
Transaction (org.hibernate.Transaction)
(Optional) A single-threaded, short-lived object used by the application to specify atomic units of
work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A
org.hibernate. Session might span several org.hibernate.Transactions in some cases. However,
transaction demarcation, either using the underlying API or org.hibernate.Transaction, is
never optional.
ConnectionProvider (org.hibernate.connection.ConnectionProvider)
(Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying
javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be
extended and/or implemented by the developer.
TransactionFactory (org.hibernate.TransactionFactory)
(Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application,
but it can be extended and/or implemented by the developer.
Q.2 Explain the Struts Framework
Ans: 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.
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 flows 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
From Action to View:
(Business layer) service or function. 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.
Q.3 Explain web.xml and struts.xml files
Ans: The interactions in MVC model between Model, View and Controller flow are taken care by the
struts configuration files. These files are web.xml, struts.xml, struts-config.xml and
struts.properties.
web.xml:
 The web.xml configuration file is a J2EE configuration file that determines how elements of
the HTTP request are processed by the servlet container.
 The web.xml web application descriptor file represents the core of the Java web application,
so it is appropriate that it is also part of the core of the Struts framework.
 In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes
the Struts framework and handles all requests.
 This filter can contain initialization parameters that affect what, if any, additional
configuration files are loaded and how the framework should behave.
 The web.xml file needs to be created under the folderWebContent/WEB-INF.
 Configuring web.xml for the framework is a matter of adding a filter and filter-mapping.
struts.xml
 The struts.xml file contains the configuration information that you will be modifying as
actions are developed.
 This file can be used to override default settings for an application, for example
struts.devMode = false and other settings which are defined in property file.
 This file can be created under the folder WEB-INF/classes.
Example:
<struts>
<constant name="struts.devMode" value="true" />
<package name="helloworld" extends="struts-default">
<action name="hello"class="HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
Q.4 What is object relational mapping(ORM)? what are its advantages?
Ans: 1. Facilitates implementing the Domain Model pattern: This one reason supersedes all
others. In short using this pattern means that you model entities based on real business
concepts rather than based on your database structure. ORM tools provide this functionality
through mapping between the logical business model and the physical storage model.
2. Huge reduction in code: ORM tools provide a host of services thereby allowing developers
to focus on the business logic of the application rather than repetitive CRUD (Create Read
Update Delete) logic.
3. Changes to the object model are made in one place: One you update your object
definitions, the ORM will automatically use the updated structure for retrievals and
updates. There are no SQL Update, Delete and Insert statements strewn throughout
different layers of the application that need modification.
4. Rich query capability: ORM tools provide an object oriented query language. This allows
application developers to focus on the object model and not to have to be concerned with
the database structure or SQL semantics. The ORM tool itself will translate the query
language into the appropriate syntax for the database.
5. Navigation: You can navigate object relationships transparently. Related objects are
automatically loaded as needed. For example if you load a PO and you want to access it's
Customer, you can simply access PO. Customer and the ORM will take care of loading the
data for you without any effort on your part.
6. Data loads are completely configurable allowing you to load the data appropriate for
each scenario. For example in one scenario you might want to load a list of POs without any
of its child / related objects, while in other scenarios you can specify to load a PO, with all its
child Line Items, etc.
7. Concurrency support: Support for multiple users updating the same data simultaneously.
8. Cache management: Entities are cached in memory thereby reducing load on the database.
9. Transaction management and Isolation: All object changes occur scoped to a transaction.
The entire transaction can either be committed or rolled back. Multiple transactions can be
active in memory in the same time, and each transactions changes are isolated form on
another.
10.Key Management: Identifiers and surrogate keys are automatically propogated and
managed.
Q.5 What is the importance of hibernate mapping file? Explain with suitable example
Ans:  Mapping file is the heart of hibernate application.
 Every ORM tool needs this mapping, mapping is the mechanism of placing an object
properties into column’s of a table.
 Mapping can be given to an ORM tool either in the form of an XML or in the form of the
annotations.
 The mapping file contains mapping from a pojo class name to a table name and pojo class
variable names to table column names.
 While writing an hibernate application, we can construct one or more mapping files, mean a
hibernate application can contain any number of mapping files.
 generally an object contains 3 properties like
Identity (Object Name)
State (Object values)
Behavior (Object Methods)
Example:
<hibernate-mapping>
<class name="Employee" table="EMPLOYEE">
<meta attribute="class-description"> This class
contains the employee detail.
</meta>
<id name="id" type="int" column="id">
<generator class="native"/>
</id>
<property name="firstName" column="first_name"
type="string"/>
<property name="lastName" column="last_name"
type="string"/>
<property name="salary" column="salary" type="int"/>
</class>
</hibernate-mapping>
Q.6 Explain the working of Hibernate
Ans: Hibernate is the ORM tool given to transfer the data between a java (object) application and a
database (Relational) in the form of the objects. Hibernate is the open source light weight tool
given by Gavin King
Hibernate provides a solution to map database tables to a class. It copies one row of the database
data to a class. In the other direction it supports to save objects to the database. In this process the
object is transformed to one or more tables.
Q.7. Write a sample hibernate configuration file? Explain the elements of the file
Ans: Configuration is the file loaded into an hibernate application when working with hibernate, this
configuration file contains 3 types of information.
 Connection Properties
 Hibernate Properties
 Mapping file name(s)
 <hibernate-configuration> : This is next and parent tag for the hibernate configuration. It is
the base tag, containg all the hibernate configuration setting in its sub tags.
 <session-factory> : This is sub tag of <hibernate-configuration> that hold all the required
properties to communicate with the database, like database connection setting url,
usernate, password and etc.
 <property name = “---“>---</property> : This is the sub tag of <session-factory>, which
describe all the required properties in order to communicate with the database like
connection properties for database.
Q.8 Explain Filter Dispatcher and any two action components used by struts
Ans:  A Filter Dispatcher is used as the Controller in Struts.
 Its name in packaged Structure is org.apache.struts2.dispatcher.FilterDispatcher.
 Prior to using it in the application, it has to be registered in the web.xml as below.
 At first the FilterDispatcher verifies the request URI and determines the right action for it.
 The mappings of URI’s and the action classes are present in the struts.xml file found in the
WEB-INF/classes directory.
FilterDispatcher does the following for eact action invocation.
1)Determines which action to invoke for a requested URI by consulting the Configuration manager
2) Interceptors registered for the action are invoked one after the other.
3) Then the action method is executed.
4) Then the Filter Dispatcher executes the Result.
Optionally you can extend the ActionSupport class which implements six interfaces
including Actioninterface. The Action interface is as follows:
public interface Action {
public static final String SUCCESS = "success";
public static final String NONE = "none";
public static final String ERROR = "error";
public static final String INPUT = "input";
public static final String LOGIN = "login";
public String execute() throws Exception;
}
Q.9 Explain in brief MVC architecture with the help of suitable diagram
Ans: Model-View-Controller architecture is used for interactive web-applications. This model minimizes
the coupling between business logic and data presentation to web user. This model divides the
web based application into three layers:
 Model: Model domain contains the business logics and functions that manipulate the
business data. It provides updated information to view domain and also gives
response to query. And the controller can access the functionality which is
encapsulated in the model.
 View: View is responsible for presentation aspect of application according to the model
data and also responsible to forward query response to the controller.
 Controller: Controller accepts and intercepts user requests and controls the business
Objects to fulfill these requests. An application has one controller for related
functionality. Controller can also be depends on the type of clients.
Q.10 Write a short note on Interceptors in struts
Interceptors allow for crosscutting functionality to be implemented separately from the action as
well as the framework. You can achieve the following using interceptors:
 Providing preprocessing logic before the action is called.
 Providing postprocessing logic after the action is called.
 Catching exceptions so that alternate processing can be performed.
 Many of the features provided in the Struts2 framework are implemented using
interceptors; examples include exception handling, file uploading, lifecycle callbacks and
validation etc.
Q.11 Explain the different roles of Action in struts framework
 Actions are the core of the Struts2 framework, as they are for any MVC (Model View
Controller) framework. Each URL is mapped to a specific action, which provides the
processing logic necessary to service the request from the user.
 But the action also serves in two other important capacities. First, the action plays an
important role in the transfer of data from the request through to the view, whether its a
JSP or other type of result. Second, the action must assist the framework in determining
which result should render the view that will be returned in the response to the request.
Q.12 What is value-stack? What are the different type of object it can hold off? Explain their
accessing strategies?What is OGNL ?
The value stack is a set of several objects which keeps the following objects in the provided order:
SN Objects & Description
1
Temporary Objects
There are various temporary objects which are created during execution of a page.
For example the current iteration value for a collection being looped over in a JSP tag.
2
The Model Object
If you are using model objects in your struts application, the current model object is
placed before the action on the value stack
3
The Action Object
This will be the current action object which is being executed.
4
Named Objects
These objects include #application, #session, #request, #attr and #parameters and
refer to the corresponding servlet scopes
OGNL:
The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to
reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type
conversion.
The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a
root or default object within the context. The properties of the default or root object can be
referenced using the markup notation, which is the pound symbol.
As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use
with OGNL. The ActionContext map consists of the following:
 application - application scoped variables
 session - session scoped variables
 root / value stack - all your action variables are stored here
 request - request scoped variables
 parameters - request parameters
 atributes - the attributes stored in page, request, session and application scope
It is important to understand that the Action object is always available in the value stack. So,
therefore if your Action object has properties x and y there are readily available for you to use.

More Related Content

PPT
Issues & Morphological models NLP engineering
PPT
Regular Languages
DOCX
PHP NOTES FOR BEGGINERS
PPT
Gujarati Text-to-Speech Presentation
PDF
LR Parsing
PPTX
Estructura de archivos secuencial indexado
PPT
.Net overview|Introduction Of .net
PPTX
Huffman coding
Issues & Morphological models NLP engineering
Regular Languages
PHP NOTES FOR BEGGINERS
Gujarati Text-to-Speech Presentation
LR Parsing
Estructura de archivos secuencial indexado
.Net overview|Introduction Of .net
Huffman coding

What's hot (20)

PPT
Architecture of .net framework
PPTX
Music Recommendation system Project PPT.pptx
PPTX
PPTX
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
PDF
06-1. Representasi dan Alur Pemrosesan Data Komputer (1).pdf
PPTX
6-Practice Problems - LL(1) parser-16-05-2023.pptx
PPTX
Python programming- Part IV(Functions)
DOCX
Materi linked list dan bubble sort
PPTX
First Come First Serve & Shortest Job First-(FCFS & SJF)
PPT
Intro to scikit-learn
PPTX
First order predicate logic(fopl)
PDF
OCP Java SE 8 Exam - Sample Questions - Java Streams API
PPTX
First-Come-First-Serve (FCFS)
PPT
.Net framework
PDF
C# Cheat Sheet
PPT
Networking & Socket Programming In Java
PPTX
Giới thiệu Đại số quan hệ Phép toán tập hợp Phép chọn Phép chiếu Phép tích Ca...
PPTX
Phython Programming Language
PDF
Bài 5 Lập trình PHP (phần 3) Làm việc với dữ liệu của form - Giáo trình FPT
DOCX
C s investigatory project on telephone directory
Architecture of .net framework
Music Recommendation system Project PPT.pptx
UNIT-1 : 20ACS04 – PROBLEM SOLVING AND PROGRAMMING USING PYTHON
06-1. Representasi dan Alur Pemrosesan Data Komputer (1).pdf
6-Practice Problems - LL(1) parser-16-05-2023.pptx
Python programming- Part IV(Functions)
Materi linked list dan bubble sort
First Come First Serve & Shortest Job First-(FCFS & SJF)
Intro to scikit-learn
First order predicate logic(fopl)
OCP Java SE 8 Exam - Sample Questions - Java Streams API
First-Come-First-Serve (FCFS)
.Net framework
C# Cheat Sheet
Networking & Socket Programming In Java
Giới thiệu Đại số quan hệ Phép toán tập hợp Phép chọn Phép chiếu Phép tích Ca...
Phython Programming Language
Bài 5 Lập trình PHP (phần 3) Làm việc với dữ liệu của form - Giáo trình FPT
C s investigatory project on telephone directory
Ad

Viewers also liked (20)

DOCX
TY.BSc.IT Java QB U1
DOCX
TY.BSc.IT Java QB U4
PPT
Internet of Things
PPT
Pra taruna
DOCX
TY.BSc.IT Java QB U2
DOCX
DOC
Amr Farag CV
PPT
Παρουσίαση για πρόγραμμα του Γυμνασίου Σπηλίου
PDF
OSF BROCHURE FINAL ORIGINAL
PDF
Toyota Industrial Equipment to Partner With I.D. Systems on New Wireless Vehi...
PDF
Internship Report on Financial Statements Analysis of FSIBL by Moez Ansary
PPTX
майстер клас. 07
PDF
Internship Report on Financial Statements Analysis of FSIBL by Moez Ansary
PPTX
Community Development Through Cooperative in Ethiopia
DOCX
TY.BSc.IT Java QB U3
DOCX
TY.BSc.IT Java QB U6
DOCX
TY.BSc.IT Java QB U5
PDF
HLW Report Shahnawaz Lodhi
PPT
Sosok pilihan
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U4
Internet of Things
Pra taruna
TY.BSc.IT Java QB U2
Amr Farag CV
Παρουσίαση για πρόγραμμα του Γυμνασίου Σπηλίου
OSF BROCHURE FINAL ORIGINAL
Toyota Industrial Equipment to Partner With I.D. Systems on New Wireless Vehi...
Internship Report on Financial Statements Analysis of FSIBL by Moez Ansary
майстер клас. 07
Internship Report on Financial Statements Analysis of FSIBL by Moez Ansary
Community Development Through Cooperative in Ethiopia
TY.BSc.IT Java QB U3
TY.BSc.IT Java QB U6
TY.BSc.IT Java QB U5
HLW Report Shahnawaz Lodhi
Sosok pilihan
Ad

Similar to TY.BSc.IT Java QB U5&6 (20)

PDF
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
PPT
EJBDetailsFeb25.ppt
PPT
Ejb 2.0
PPT
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
PDF
Enterprise Java Beans - EJB
PPTX
Enterprise beans
PPT
J2EE - Practical Overview
PPT
J2 Ee Overview
PPT
Unite5-EJB-2019.ppt
PDF
What's New in Enterprise JavaBean Technology ?
PPT
ADVANCED JAVA MODULE I & II.ppt
PDF
EJB Interview Questions
PPT
Aravind vinnakota ejb_architecture
PPS
Ajs 3 b
PPTX
Java bean
PDF
Lecture 8 Enterprise Java Beans (EJB)
PPT
PDF
Ejb intro
PDF
Jsf+ejb 50
PDF
Ejb intro
S314168 - What's New in Enterprise Java Bean Technology @ JavaOne Brazil 2010
EJBDetailsFeb25.ppt
Ejb 2.0
EJB.ppthckhkhohjpfuysfzhxjvkgur6eydgdcjjggjj
Enterprise Java Beans - EJB
Enterprise beans
J2EE - Practical Overview
J2 Ee Overview
Unite5-EJB-2019.ppt
What's New in Enterprise JavaBean Technology ?
ADVANCED JAVA MODULE I & II.ppt
EJB Interview Questions
Aravind vinnakota ejb_architecture
Ajs 3 b
Java bean
Lecture 8 Enterprise Java Beans (EJB)
Ejb intro
Jsf+ejb 50
Ejb intro

More from Lokesh Singrol (13)

PDF
MCLS 45 Lab Manual
PDF
MCSL 036 (Jan 2018)
PDF
Project black book TYIT
PPTX
Computer institute website(TYIT project)
PPTX
Top Technology product failure
PPTX
HP Software Testing project (Advanced)
PPTX
Testing project (basic)
PPTX
Computer institute Website(TYIT project)
PPTX
Trees and graphs
PPTX
behavioral model (DFD & state diagram)
PPTX
Desktop system,clustered system,Handheld system
PPTX
Raster Scan display
PPT
Flash memory
MCLS 45 Lab Manual
MCSL 036 (Jan 2018)
Project black book TYIT
Computer institute website(TYIT project)
Top Technology product failure
HP Software Testing project (Advanced)
Testing project (basic)
Computer institute Website(TYIT project)
Trees and graphs
behavioral model (DFD & state diagram)
Desktop system,clustered system,Handheld system
Raster Scan display
Flash memory

Recently uploaded (20)

PPTX
PPH.pptx obstetrics and gynecology in nursing
PDF
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
Microbial disease of the cardiovascular and lymphatic systems
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
PDF
RMMM.pdf make it easy to upload and study
PDF
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
PDF
Anesthesia in Laparoscopic Surgery in India
PPTX
Cell Types and Its function , kingdom of life
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
PPTX
Institutional Correction lecture only . . .
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf
PPH.pptx obstetrics and gynecology in nursing
3rd Neelam Sanjeevareddy Memorial Lecture.pdf
O7-L3 Supply Chain Operations - ICLT Program
Microbial disease of the cardiovascular and lymphatic systems
Pharmacology of Heart Failure /Pharmacotherapy of CHF
The Lost Whites of Pakistan by Jahanzaib Mughal.pdf
RMMM.pdf make it easy to upload and study
Origin of periodic table-Mendeleev’s Periodic-Modern Periodic table
Microbial diseases, their pathogenesis and prophylaxis
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Basic Mud Logging Guide for educational purpose
Mark Klimek Lecture Notes_240423 revision books _173037.pdf
Anesthesia in Laparoscopic Surgery in India
Cell Types and Its function , kingdom of life
Renaissance Architecture: A Journey from Faith to Humanism
PPT- ENG7_QUARTER1_LESSON1_WEEK1. IMAGERY -DESCRIPTIONS pptx.pptx
Institutional Correction lecture only . . .
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
Saundersa Comprehensive Review for the NCLEX-RN Examination.pdf

TY.BSc.IT Java QB U5&6

  • 1. QUESTION BANK UNIT –V Q.1 Explain the architecture of EJB Ans: A bean runs in a container. The container, which is part of the EJB server, provides a number of services to the bean. These include transaction services, synchronization services, and security. To provide these services, the bean container must be able to intercept calls to bean methods. For example, a client application calls a bean method that has a transaction attribute that requires the bean to create a new transaction context. The bean container must be able to interpose code to start a new transaction before the method call, and to commit the transaction, if possible, when the method completes, and before any values are returned to the client. For this reason and others, a client application does not call the remote bean methods directly. Instead, the client invokes the bean method through a twostep process mediated by the ORB and by the container.  First, the client actually calls a local proxy stub for the remote method. The stub marshalls any parameter data, and then calls a remote skeleton on the server. The skeleton unmarshalls the data, and upcalls to the bean container.This step is required because of the remote nature of the call. Note that this step is completely transparent both to the client application developer as well as to the bean developer. It is a detail that you do not need to know about to write your application code, either on the client or the server. Nevertheless, it is useful to know what is going on, especially when it comes to understanding what happens during bean deployment.  In the second step, the bean container gets the skeleton upcall, then interposes whatever services are required by the context. These can include: 1. authenticating the client, on the first method call 2. performing transaction management 3. calling synchronization methods in the bean itself 4. identity checks and switch  The container then delegates the method call to the bean. The bean method executes. When it returns, the thread of control returns to the bean container,which interposes whatever services are required by the context. For example,if the method is running in a transaction context, the bean container performs a commit operation, if possible. This depends on the transaction attributes in the bean descriptor.  Then the bean container calls the skeleton, which Marshalls return data, and returns it to the client stub. These steps are completely invisible to client-side and server-side application developers. One of the major advantages of the EJB development model is that it hides the complexity of transaction and identity management from
  • 2. developers. Q.2 What are the different types of Enterprise Java Beans ? Explain Ans: Types of EJB: 1. Session 2. Entity 3. Message-Driven 1. Session EJBs A session EJB is a nonpersistent object: Its lifetime is the duration of a particular interaction between the client and the EJB. The client normally creates an EJB, calls methods on it, and then removes it. If the client fails to remove it, the EJB container will remove it after a certain period of inactivity. Session EJBs are subdivided into ‘stateful’ and ‘stateless’ types. A stateless session EJB is shared amongst a number of clients, while a stateful session EJB is created for a specific client and not used by any others. The use of stateless EJBs offers efficiency advantages but, of course, it is not always possible to use them. 2. Entity EJBs Entity EJBs represent persistent objects: Their lifetimes are not related to the duration of interaction with clients. In nearly all cases, entity EJBs are synchronized with relational databases. This is how persistence is achieved. Entity EJBs are always shared amongst clients: A client cannot get an entity EJB to itself. Thus, entity EJBs are nearly always used as a scheme for mapping relational databases into object-oriented applications. Whereas a client normally creates a session EJB and removes it after use, clients normally look up an existing entity EJB. Creation of an entity EJB corresponds to adding new data items to the application (e.g., adding rows to database tables). An important feature of entity EJBs is that they have identity—that is, one can be distinguished from another. This is implemented by assigning a primary key to each instance of the EJB, where ‘primary key’ has the same meaning as it does for database management. Primary keys that identify EJBs can be of any type, including programmer-defined classes. 3. Message-driven EJBs A message-driven bean acts as a consumer of asynchronous messages: It cannot be called directly by clients, but is activated by the container when a message arrives. Clients interact with these EJBs by sending messages to the queues or topics to which they are listening. Although a message-driven EJB cannot be called directly by clients, it can call other EJBs itself. Messagedriven EJBs are the only type that does not follow a strict request-response interaction with clients. Q.3 What is facelet ? what are its features? Ans: Features:  Server-side helper classes, such as database access beans  A custom tag library for rendering UI components on a page  A custom tag library for representing event handlers, validators , and other actions
  • 3.  UI components represented as stateful objects on the server  Backing beans, which define properties and functions for UI components  Validators, converters, event listeners, and event handlers  An application configuration resource file for configuring application resources Q.4 Explain the life cycle of JSF Ans: Phase 1: Restore view  JSF begins the restore view phase as soon as a link or a button is clicked and JSF receives a request.  During this phase, the JSF builds the view, wires event handlers and validators to UI components and saves the view in the FacesContext instance. The FacesContext instance will now contains all the information required to process a request. Phase 2: Apply request values  After the component tree is created/restored, each component in component tree uses decode method to extract its new value from the request parameters. Component stores this value. If the conversion fails, an error message is generated and queued on FacesContext. This message will be displayed during the render response phase, along with any validation errors.  If any decode methods / event listeners called renderResponse on the current FacesContext instance, the JSF moves to the render response phase. Phase 3: Process validation  During this phase, the JSF processes all validators registered on component tree. It examines the component attribute rules for the validation and compares these rules to the local value
  • 4. stored for the component.  If the local value is invalid, the JSF adds an error message to the FacesContext instance, and the life cycle advances to the render response phase and display the same page again with the error message. Phase 4: Update model values  After the JSF checks that the data is valid, it walks over the component tree and set the corresponding server-side object properties to the components' local values. The JSF will update the bean properties corresponding to input component's value attribute.  If any updateModels methods called renderResponse on the current FacesContext instance, the JSF moves to the render response phase. Phase 5: Invoke application  During this phase, the JSF handles any application-level events, such as submitting a form / linking to another page. Phase 6: Render response  During this phase, the JSF asks container/application server to render the page if the application is using JSP pages. For initial request, the components represented on the page will be added to the component tree as the JSP container executes the page. If this is not an initial request, the component tree is already built so components need not to be added again. In either case, the components will render themselves as the JSP container/Application server traverses the tags in the page.  After the content of the view is rendered, the response state is saved so that subsequent requests can access it and it is available to the restore view phase. Q.5 How does JSF application gets executed ? Explain Ans: The hello example JSF application goes through the following stages when it is deployed on the GlassFish Server. 1. When the hello application is built and deployed on the GlassFish Server, the application is in an uninitiated state. 2. When a client makes an initial request for the beanhello.xhtml web page, the hello Facelets application is compiled. 3. The compiled Facelets application is executed, and a new component tree is constructed for the hello application and is placed in ajavax.faces.context.FacesContext. 4. The component tree is populated with the component and the managed bean property associated with it, represented by the EL expression hello.world. 5. A new view is built, based on the component tree. 6. The view is rendered to the requesting client as a response. 7. The component tree is destroyed automatically. 8. On subsequent (postback) requests, the component tree is rebuilt, and the saved state is applied. Q.6 Write a session bean code specification that calculates compound interest. Assume principal, terms and rate of interest is entered by the user and the input is passed through a servlet
  • 5. Ans: Clacjsp.jsp: // jsp web page created <form action="calcservlet" method="post"> Principal: <input type="text" name="t1"/> Rate: <input type="text" name="t2"/> No_of_years: <input type="text" name="t3"/> <input type="submit" name="submit"/> </form> Calcservlet.java: // servlet file created package mybean; import java.io.IOException; import java.io.PrintWriter; import javax.ejb.EJB; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class calcservlet extends HttpServlet { @EJB private simpleLocal simple; protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); try (PrintWriter out = response.getWriter()) { out.println("<!DOCTYPE html>"); out.println("<html>"); out.println("<head>"); out.println("<title>Servlet calcservlet</title>"); out.println("</head>"); out.println("<body>"); Double a=Double.parseDouble(request.getParameter("t1")); Double b=Double.parseDouble(request.getParameter("t2")); Double c=Double.parseDouble(request.getParameter("t3")); out.println("<h1>Simple Interest = " + simple.calcsimple(a, b, c)+ "</h1>"); out.println("</body>"); out.println("</html>"); } } } Simple.java : // bean created package mybean;
  • 6. import javax.ejb.Stateless; import java.util.Scanner; @Stateless public class simple implements simpleLocal { @Override public Double calccomp(double a, double b, double c) { double ci=a*Math.pow((1+b/100),c); return ci; } } Q.7. Write the benefits of using EJB Ans: For several reasons, enterprise beans simplify the development of large, distributed applications.  because the EJB container provides system-level services to enterprise beans, the bean developer can concentrate on solving business problems. The EJB container, rather than the bean developer, is responsible for system-level services, such as transaction management and security authorization.  because the beans rather than the clients contain the application’s business logic, the client developer can focus on the presentation of the client. The client developer does not have to code the routines that implement business rules or access databases. As a result, the clients are thinner, a benefit that is particularly important for clients that run on small devices.  because enterprise beans are portable components, the application assembler can build new applications from existing beans. Provided that they use the standard APIs, these applications can run on any compliant Java EE server. Q.8 Create a JSF application for checking the validity of the user Ans: Example: <%@ page contentType="text/html"%> <%@ tagliburi="http://java.sun.com/jsf/core" prefix="f"%> <%@ tagliburi="http://java.sun.com/jsf/html" prefix="h"%> <f:view> <html> <head><title>JSF Login Application</title></head> <body> <h:form> <h:panelGroup rendered="#{login.validationComplete and (!login.isUsernameValid or !login.isPasswordValid)}"> <h:outputText value="Username is a Required Field" rendered="#{!login.isUsernameValid}" style="color:red"></h:outputText> <br> <h:outputText value="Password is a Required Field" rendered="#{!login.isPasswordValid}" style="color:red"></h:outputText> </h:panelGroup>
  • 7. <h:panelGroup rendered="#{login.validationComplete and (login.isUsernameValid and login.isPasswordValid)}"> <h:outputText value="Username & Password are valid" style="color:green"></h:outputText> </h:panelGroup> <table> <tr> <td><h:outputText value="Enter Username: " /></td> <td><h:inputText id="username" value="#{login.username}" /> </td> </tr> <tr> <td><h:outputText value="Enter Password: " /></td> <td><h:inputSecret id="password" value="#{login.password}" /> </td> </tr> <tr> <td> </td> <td><h:commandButton value="Login" action="#{login.checkValidity}"/> </td> </tr> </table> </h:form> </body> </html> </f:view> 1. <%@ tagliburi="http://java.sun.com/jsf/core" prefix="f"%> <%@ tagliburi="http://java.sun.com/jsf/html" prefix="h"%> This line links to the jsf core and jsf html tag libraries. The jsf html tag library carries regular html components like text box, buttons, etc.
  • 8. 2. <f:view></f:view> This tag at the beginning of the document acts as a container for all the components enclosed between them. 3. <h:panelGroup rendered="#{login.validationComplete and (!login.isUsernameValid or !login.isPasswordValid)}"> <h:outputText value="Username is a Required Field" rendered="#{!login.isUsernameValid}" style="color:red"></h:outputText> <br> <h:outputText value="Password is a Required Field" rendered="#{!login.isPasswordValid}" style="color:red"></h:outputText> </h:panelGroup> The above code snippet is intended to display error and success messages. The first part displays the error messages one after the other. The second part displays a single success message. This code uses Expression Language (EL) to do conditional checks and reference the managed bean values. 4. <h:panelGroup rendered="#{login.validationComplete and (login.isUsernameValid and login.isPasswordValid)}"> <h:outputText value="Username & Password are valid" style="color:green"></h:outputText> </h:panelGroup> The following line in the above code snippet checks to see if the validation failed before displaying the error messages Q.9 Explain with suitable example <navigation-rule> element of faces-config.xml file of JSF Ans:  Navigation between different pages of a Java Server Faces application, such as choosing the next page to be displayed after a button or hyperlink component is clicked, is defined by a set of rules.  Navigation rules can be implicit, or they can be explicitly defined in the application configuration resource file.  These navigation rules are defined in JSF configuration files along with other definitions for a JSF application. Usually, this file is named faces-config.xml. Here is a navigation rule that could be used with the example just described: <navigation-rule> <from-view-id>/login.xhtml</from-view-id> <navigation-case> <from-action>#{LoginForm.login}</from-action> <from-outcome>success</from-outcome> <to-view-id>/storefront.xhtml</to-view-id> </navigation-case> <navigation-case> <from-action>#{LoginForm.logon}</from-action>
  • 9. <from-outcome>failure</from-outcome> <to-view-id>/logon.xhtml</to-view-id> </navigation-case> </navigation-rule> This navigation rule defines the possible ways to navigate from login.xhtml. Each navigation- case element defines one possible navigation path fromlogin.xhtml. The first navigation-case says that if LoginForm.login returns an outcome of success, then storefront.xhtml will be accessed. The second navigation-case says that login.xhtml will be re-rendered if LoginForm.login returns failure. QUESTION BANK UNIT –VI Q.1 Explain the Hibernate Framework
  • 10. Ans:  Hibernate is an Object-relational mapping (ORM) tool. Object-relational mapping or ORM is a programming method for mapping the objects to the relational model where entities/classes are mapped to tables, instances are mapped to rows and attributes of instances are mapped to columns of table.  A “virtual object database” is created that can be used from within the programming language.  Hibernate is a persistence framework which is used to persist data from Java environment to database. Persistence is a process of storing the data to some permanent medium and retrieving it back at any point of time even after the application that had created the data ended.  The above diagram shows a comprehensive architecture of Hibernate. In order to persist data to a database, Hibernate create an instance of entity class(Java class mapped with database table). This object is called Transient object as they are not yet associated with the session or not yet persisted to a database.  To persist the object to database, the instance of SessionFactory interface is created. SessionFactory is a singleton instance which implements Factory design pattern. SessionFactory loads hibernate.cfg.xml file(Hibernate configuration file. More details in following section) and with the help of TransactionFactory and ConnectionProvider implements all the configuration settings on a database.  Each database connection in Hibernate is created by creating an instance of Session interface. Session represents a single connection with database.Session objects are created from SessionFactory object.  Hibernate also provides built-in Transaction APIs which abstracts away the application from underlying JDBC or JTA transaction. Each transaction represents a single atomic unit of work. One Session can span through multiple transactions. SessionFactory (org.hibernate.SessionFactory) A thread-safe, immutable cache of compiled mappings for a single database. A factory for org.hibernate.Session instances. A client of org.hibernate.connection.ConnectionProvider. Optionally maintains a second level cache of data that is reusable between transactions at a
  • 11. process or cluster level. Session (org.hibernate.Session) A single-threaded, short-lived object representing a conversation between the application and the persistent store. Wraps a JDBC java.sql.Connection. Factory for org.hibernate.Transaction. Maintains a first level cache of persistent the application’s persistent objects and collections; this cache is used when navigating the object graph or looking up objects by identifier. Persistent objects and collections Short-lived, single threaded objects containing persistent state and business function. These can be ordinary JavaBeans/POJOs. They are associated with exactly one org.hibernate.Session. Once the org.hibernate.Session is closed, they will be detached and free to use in any application layer (for example, directly as data transfer objects to and from presentation). Transient and detached objects and collections Instances of persistent classes that are not currently associated with a org.hibernate.Session. They may have been instantiated by the application and not yet persisted, or they may have been instantiated by a closed org.hibernate.Session. Transaction (org.hibernate.Transaction) (Optional) A single-threaded, short-lived object used by the application to specify atomic units of work. It abstracts the application from the underlying JDBC, JTA or CORBA transaction. A org.hibernate. Session might span several org.hibernate.Transactions in some cases. However, transaction demarcation, either using the underlying API or org.hibernate.Transaction, is never optional. ConnectionProvider (org.hibernate.connection.ConnectionProvider) (Optional) A factory for, and pool of, JDBC connections. It abstracts the application from underlying javax.sql.DataSource or java.sql.DriverManager. It is not exposed to application, but it can be extended and/or implemented by the developer. TransactionFactory (org.hibernate.TransactionFactory) (Optional) A factory for org.hibernate.Transaction instances. It is not exposed to the application, but it can be extended and/or implemented by the developer. Q.2 Explain the Struts Framework Ans: 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.
  • 12. 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 flows 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 From Action to View: (Business layer) service or function. 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. Q.3 Explain web.xml and struts.xml files Ans: The interactions in MVC model between Model, View and Controller flow are taken care by the struts configuration files. These files are web.xml, struts.xml, struts-config.xml and
  • 13. struts.properties. web.xml:  The web.xml configuration file is a J2EE configuration file that determines how elements of the HTTP request are processed by the servlet container.  The web.xml web application descriptor file represents the core of the Java web application, so it is appropriate that it is also part of the core of the Struts framework.  In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts framework and handles all requests.  This filter can contain initialization parameters that affect what, if any, additional configuration files are loaded and how the framework should behave.  The web.xml file needs to be created under the folderWebContent/WEB-INF.  Configuring web.xml for the framework is a matter of adding a filter and filter-mapping. struts.xml  The struts.xml file contains the configuration information that you will be modifying as actions are developed.  This file can be used to override default settings for an application, for example struts.devMode = false and other settings which are defined in property file.  This file can be created under the folder WEB-INF/classes. Example: <struts> <constant name="struts.devMode" value="true" /> <package name="helloworld" extends="struts-default"> <action name="hello"class="HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts>
  • 14. Q.4 What is object relational mapping(ORM)? what are its advantages? Ans: 1. Facilitates implementing the Domain Model pattern: This one reason supersedes all others. In short using this pattern means that you model entities based on real business concepts rather than based on your database structure. ORM tools provide this functionality through mapping between the logical business model and the physical storage model. 2. Huge reduction in code: ORM tools provide a host of services thereby allowing developers to focus on the business logic of the application rather than repetitive CRUD (Create Read Update Delete) logic. 3. Changes to the object model are made in one place: One you update your object definitions, the ORM will automatically use the updated structure for retrievals and updates. There are no SQL Update, Delete and Insert statements strewn throughout different layers of the application that need modification. 4. Rich query capability: ORM tools provide an object oriented query language. This allows application developers to focus on the object model and not to have to be concerned with the database structure or SQL semantics. The ORM tool itself will translate the query language into the appropriate syntax for the database. 5. Navigation: You can navigate object relationships transparently. Related objects are automatically loaded as needed. For example if you load a PO and you want to access it's Customer, you can simply access PO. Customer and the ORM will take care of loading the data for you without any effort on your part. 6. Data loads are completely configurable allowing you to load the data appropriate for each scenario. For example in one scenario you might want to load a list of POs without any of its child / related objects, while in other scenarios you can specify to load a PO, with all its child Line Items, etc. 7. Concurrency support: Support for multiple users updating the same data simultaneously. 8. Cache management: Entities are cached in memory thereby reducing load on the database. 9. Transaction management and Isolation: All object changes occur scoped to a transaction. The entire transaction can either be committed or rolled back. Multiple transactions can be active in memory in the same time, and each transactions changes are isolated form on another. 10.Key Management: Identifiers and surrogate keys are automatically propogated and managed. Q.5 What is the importance of hibernate mapping file? Explain with suitable example Ans:  Mapping file is the heart of hibernate application.  Every ORM tool needs this mapping, mapping is the mechanism of placing an object properties into column’s of a table.  Mapping can be given to an ORM tool either in the form of an XML or in the form of the annotations.  The mapping file contains mapping from a pojo class name to a table name and pojo class variable names to table column names.  While writing an hibernate application, we can construct one or more mapping files, mean a hibernate application can contain any number of mapping files.
  • 15.  generally an object contains 3 properties like Identity (Object Name) State (Object values) Behavior (Object Methods) Example: <hibernate-mapping> <class name="Employee" table="EMPLOYEE"> <meta attribute="class-description"> This class contains the employee detail. </meta> <id name="id" type="int" column="id"> <generator class="native"/> </id> <property name="firstName" column="first_name" type="string"/> <property name="lastName" column="last_name" type="string"/> <property name="salary" column="salary" type="int"/> </class> </hibernate-mapping> Q.6 Explain the working of Hibernate Ans: Hibernate is the ORM tool given to transfer the data between a java (object) application and a database (Relational) in the form of the objects. Hibernate is the open source light weight tool given by Gavin King
  • 16. Hibernate provides a solution to map database tables to a class. It copies one row of the database data to a class. In the other direction it supports to save objects to the database. In this process the object is transformed to one or more tables. Q.7. Write a sample hibernate configuration file? Explain the elements of the file Ans: Configuration is the file loaded into an hibernate application when working with hibernate, this configuration file contains 3 types of information.  Connection Properties  Hibernate Properties  Mapping file name(s)
  • 17.  <hibernate-configuration> : This is next and parent tag for the hibernate configuration. It is the base tag, containg all the hibernate configuration setting in its sub tags.  <session-factory> : This is sub tag of <hibernate-configuration> that hold all the required properties to communicate with the database, like database connection setting url, usernate, password and etc.  <property name = “---“>---</property> : This is the sub tag of <session-factory>, which describe all the required properties in order to communicate with the database like connection properties for database. Q.8 Explain Filter Dispatcher and any two action components used by struts Ans:  A Filter Dispatcher is used as the Controller in Struts.  Its name in packaged Structure is org.apache.struts2.dispatcher.FilterDispatcher.  Prior to using it in the application, it has to be registered in the web.xml as below.  At first the FilterDispatcher verifies the request URI and determines the right action for it.  The mappings of URI’s and the action classes are present in the struts.xml file found in the WEB-INF/classes directory. FilterDispatcher does the following for eact action invocation. 1)Determines which action to invoke for a requested URI by consulting the Configuration manager 2) Interceptors registered for the action are invoked one after the other. 3) Then the action method is executed. 4) Then the Filter Dispatcher executes the Result. Optionally you can extend the ActionSupport class which implements six interfaces including Actioninterface. The Action interface is as follows:
  • 18. public interface Action { public static final String SUCCESS = "success"; public static final String NONE = "none"; public static final String ERROR = "error"; public static final String INPUT = "input"; public static final String LOGIN = "login"; public String execute() throws Exception; } Q.9 Explain in brief MVC architecture with the help of suitable diagram Ans: Model-View-Controller architecture is used for interactive web-applications. This model minimizes the coupling between business logic and data presentation to web user. This model divides the web based application into three layers:  Model: Model domain contains the business logics and functions that manipulate the business data. It provides updated information to view domain and also gives response to query. And the controller can access the functionality which is encapsulated in the model.  View: View is responsible for presentation aspect of application according to the model data and also responsible to forward query response to the controller.  Controller: Controller accepts and intercepts user requests and controls the business Objects to fulfill these requests. An application has one controller for related functionality. Controller can also be depends on the type of clients.
  • 19. Q.10 Write a short note on Interceptors in struts Interceptors allow for crosscutting functionality to be implemented separately from the action as well as the framework. You can achieve the following using interceptors:  Providing preprocessing logic before the action is called.  Providing postprocessing logic after the action is called.  Catching exceptions so that alternate processing can be performed.  Many of the features provided in the Struts2 framework are implemented using interceptors; examples include exception handling, file uploading, lifecycle callbacks and validation etc. Q.11 Explain the different roles of Action in struts framework  Actions are the core of the Struts2 framework, as they are for any MVC (Model View Controller) framework. Each URL is mapped to a specific action, which provides the processing logic necessary to service the request from the user.  But the action also serves in two other important capacities. First, the action plays an important role in the transfer of data from the request through to the view, whether its a JSP or other type of result. Second, the action must assist the framework in determining which result should render the view that will be returned in the response to the request. Q.12 What is value-stack? What are the different type of object it can hold off? Explain their
  • 20. accessing strategies?What is OGNL ? The value stack is a set of several objects which keeps the following objects in the provided order: SN Objects & Description 1 Temporary Objects There are various temporary objects which are created during execution of a page. For example the current iteration value for a collection being looped over in a JSP tag. 2 The Model Object If you are using model objects in your struts application, the current model object is placed before the action on the value stack 3 The Action Object This will be the current action object which is being executed. 4 Named Objects These objects include #application, #session, #request, #attr and #parameters and refer to the corresponding servlet scopes OGNL: The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulate data on the ValueStack. OGNL also helps in data transfer and type conversion. The OGNL is very similar to the JSP Expression Language. OGNL is based on the idea of having a root or default object within the context. The properties of the default or root object can be referenced using the markup notation, which is the pound symbol. As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContext map consists of the following:  application - application scoped variables  session - session scoped variables  root / value stack - all your action variables are stored here  request - request scoped variables  parameters - request parameters  atributes - the attributes stored in page, request, session and application scope It is important to understand that the Action object is always available in the value stack. So, therefore if your Action object has properties x and y there are readily available for you to use.