SlideShare a Scribd company logo
1 of 9
QUESTION BANK
UNIT –VI
Q.1 Explainthe Hibernate Framework
Ans:
 Hibernateis an Object-relationalmapping (ORM)tool.Object-relationalmappingorORMis a
programming method formapping theobjectsto the relational modelwhereentities/classesare mapped
to tables,instancesaremapped to rowsand attributesof instancesaremapped to columnsof table.
 A “virtual objectdatabase”iscreated thatcan be used fromwithin the programming language.
 Hibernateis a persistenceframeworkwhich isused to persist data fromJava environmentto database.
Persistenceis a processof storing the data to some permanentmediumand retrieving it backat any
pointof time even afterthe application thathad created thedata ended.
 The abovediagramshowsa comprehensivearchitectureof Hibernate.In orderto persistdatato a
database,Hibernatecreatean instanceof entity class(Java classmapped with databasetable). This
objectis called Transient objectasthey arenot yet associated with thesession or notyet persisted to a
database.
 To persist theobjectto database,theinstanceof SessionFactory interfaceiscreated.SessionFactory isa
singleton instancewhich implements Factory design pattern.SessionFactory loadshibernate.cfg.xml
file(Hibernateconfiguration file.Moredetails in following section) and with the help of
TransactionFactory and ConnectionProviderimplementsallthe configuration settingson a database.
 Each databaseconnection in Hibernateis created by creating an instanceof Session interface.Session
representsa single connection with database.Session objectsarecreated fromSessionFactory object.
 Hibernatealso providesbuilt-in Transaction APIswhich abstractsaway the application fromunderlying
JDBC or JTA transaction.Each transaction representsa singleatomic unitof work.OneSession can span
through multipletransactions.
SessionFactory(org.hibernate.SessionFactory)
A thread-safe,immutablecacheof compiled mappingsfora single database. A factory fororg.hibernate.Session
instances.A client of org.hibernate.connection.ConnectionProvider.Optionally maintainsa second levelcache of
datathatis reusable between transactions ata processor cluster level.
Session(org.hibernate.Session)
A single-threaded,short-lived objectrepresenting a conversationbetween the application and thepersistent
store.Wrapsa JDBC java.sql.Connection. Factory fororg.hibernate.Transaction.Maintainsa firstlevel cacheof
persistentthe application’spersistentobjectsand collections;thiscache is used when navigating theobject
graph orlooking up objectsby identifier.
Persistent objectsand collections
Short-lived,singlethreaded objects containing persistentstateand businessfunction.Thesecan beordinary
JavaBeans/POJOs.They areassociated with exactly oneorg.hibernate.Session.Oncetheorg.hibernate.Session is
closed, they will bedetached and free to use in any application layer (forexample, directly as datatransfer
objectsto and frompresentation).
Transient anddetached objects andcollections
Instancesof persistentclassesthatare notcurrently associated with a org.hibernate.Session.They may have
been instantiated by the application and notyet persisted,orthey may havebeen instantiated by a closed
org.hibernate.Session.
Transaction(org.hibernate.Transaction)
(Optional) A single-threaded,short-lived objectused by theapplication to specify atomicunits of work.It
abstractstheapplication fromthe underlying JDBC,JTA or CORBA transaction.A org.hibernate. Session might
span severalorg.hibernate.Transactionsin somecases.However,transaction demarcation,eitherusing the
underlying APIororg.hibernate.Transaction,is
neveroptional.
ConnectionProvider(org.hibernate.connection.ConnectionProvider)
(Optional) A factory for,and poolof,JDBCconnections.Itabstractsthe application fromunderlying
javax.sql.DataSourceorjava.sql.DriverManager. Itisnotexposed to application,butit can be extended and/or
implemented by the developer.
TransactionFactory(org.hibernate.TransactionFactory)
(Optional) A factory fororg.hibernate.Transaction instances.Itisnot exposed to theapplication, butit can be
extended and/orimplemented by the developer.
Q.2 Explainthe Struts Framework
Ans: The StrutsFrameworkisa standard fordeveloping well-architected Web applications.Ithasthe following
features:
 Open source
 Based on the Model-View-Controller(MVC) design paradigm,distinctly separating allthreelevels:
o Model: application state
o View: presentation of data (JSP,HTML)
o Controller:routing of theapplication flow
 ImplementstheJSPModel 2 Architecture
 Storesapplication routing information and requestmappingin a single core file, struts-config.xml
The StrutsFramework,itself,only fills in theView and Controllerlayers. The Modellayer is left to the developer.
All incoming requestsareintercepted by the Strutsservlet controller.The StrutsConfiguration filestruts-
config.xmlisused by the controllerto determine therouting of the flow.This flowsconsistsof an alternation
between two transitions:
From Viewto Action:
A userclicks on a link orsubmitsa formon an HTML or JSPpage.The controller receives the request, looksup the
mapping forthisrequest,and forwardsitto an action.The action in turn calls a Modellayer
From Actionto View:
(Businesslayer) service or function.Afterthecall to an underlying function orservicereturnsto the action class,
the action forwardsto a resource in the View layer and a pageis displayed in a web browser.
The diagrambelowdescribes the flowin more detail:
1. User clicks on a link in an HTML page.
2. Servlet controller receives therequest,looksup mapping information in struts-config.xml,and
routesto an action.
3. Action makesa call to a Modellayer service.
4. Service makesa call to the Datalayer (database)and therequested data isreturned.
5. Service returnsto theaction.
6. Action forwardsto a View resource(JSPpage)
7. Servlet looksup the mapping fortherequested resourceand forwards to theappropriateJSP
page.
8. JSP file is invoked and sentto the browserasHTML.
9. User is presented witha newHTML pagein a web browser.
Q.3 Explainweb.xml and struts.xml files
Ans: The interactions in MVCmodel between Model,View and Controllerflow are taken care by the struts
configuration files.Thesefiles are web.xml,struts.xml,struts-config.xmland struts.properties.
web.xml:
 The web.xmlconfiguration fileis a J2EE configuration filethatdetermines how elementsof the HTTP
requestare processed by the servlet container.
 The web.xml web application descriptor file represents the core of the Java web application, so it is
appropriatethatit is also partof the core of the Strutsframework.
 In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts
frameworkand handlesallrequests.
 This filter can contain initialization parameters that affect what, if any, additional configuration files are
loaded and howtheframeworkshould behave.
 The web.xmlfile needsto be created underthefolderWebContent/WEB-INF.
 Configuring web.xmlfortheframeworkisa matterof 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 =
falseand other settingswhich are defined in property file.
 This file can be created underthe folder WEB-INF/classes.
Example:
<struts>
<constantname="struts.devMode"value="true"/>
<packagename="helloworld"extends="struts-default">
<action name="hello"class="HelloWorldAction" method="execute">
<result name="success">/HelloWorld.jsp</result>
</action>
</package>
</struts>
Q.4 What is objectrelational mapping(ORM)?what are its advantages?
Ans: 1. FacilitatesimplementingtheDomainModel pattern: This onereason supersedesall others.In short
using this pattern meansthatyou modelentities based on real businessconceptsratherthan based on
yourdatabasestructure.ORMtoolsprovidethisfunctionality through mapping between thelogical
businessmodeland the physicalstoragemodel.
2. Huge reduction incode: ORM toolsprovidea hostof services thereby allowing developersto focuson the
businesslogic of the application rather than repetitive CRUD(CreateRead UpdateDelete) logic.
3. Changesto the object model are made in one place:One you updateyourobjectdefinitions,theORM
will automatically usethe updated structurefor retrievalsand updates.Thereare no SQL Update,Delete
and Insertstatementsstrewn throughoutdifferentlayersof theapplication thatneed modification.
4. Rich query capability:ORMtoolsprovidean objectoriented query language.Thisallowsapplication
developersto focuson the objectmodel and notto haveto be concerned with thedatabasestructureor
SQL semantics.TheORM tool itself will translatethequery languageinto the appropriatesyntax forthe
database.
5. Navigation:You can navigateobjectrelationshipstransparently.Related objectsareautomatically
loaded asneeded.For exampleif you load a POand you wantto accessit's Customer,you can simply
access PO. Customerand theORMwill take care of loading thedata for you without any efforton your
part.
6. Data loadsare completelyconfigurableallowingyoutoloadthe data appropriatefor each scenario.
For examplein onescenario you mightwantto load a list of POswithoutany of its child / related objects,
while in other scenariosyou can specify to load a PO,with all its child Line Items,etc.
7. Concurrencysupport: Supportformultipleusers updating thesamedata simultaneously.
8. Cache management:Entities are cached in memory thereby reducing load on the database.
9. Transactionmanagementand Isolation:Allobjectchangesoccurscoped to a transaction.Theentire
transaction can either be committed orrolled back. Multipletransactionscan be activein memory in the
sametime, and each transactionschangesareisolated formon another.
10. Key Management: Identifiersand surrogatekeysareautomatically propogated and managed.
Q.5 What is the importance of hibernate mapping file?Explainwith suitable example
Ans:  Mapping fileis the heartof hibernateapplication.
 Every ORMtool needsthis mapping,mappingisthe mechanismof placing an objectpropertiesinto
column’sof a table.
 Mapping can begiven to an ORMtool either in the formof an XMLor in theformof theannotations.
 The mapping file contains mapping froma pojo classnameto a table nameand pojo classvariable
namesto table column names.
 While writing an hibernateapplication,wecan construct oneor more mapping files,mean a hibernate
application can contain any numberof mapping files.
 generally an objectcontains 3 properties like
Identity (ObjectName)
State(Objectvalues)
Behavior(ObjectMethods)
Example:
<hibernate-mapping>
<class name="Employee"table="EMPLOYEE">
<meta attribute="class-description">Thisclass
containstheemployeedetail.
</meta>
<id name="id"type="int"column="id">
<generatorclass="native"/>
</id>
<propertyname="firstName"column="first_name"
type="string"/>
<propertyname="lastName"column="last_name"
type="string"/>
<propertyname="salary"column="salary"type="int"/>
</class>
</hibernate-mapping>
Q.6 Explainthe working of Hibernate
Ans: Hibernateis the ORMtool given to transferthedata between a java (object) application and a database
(Relational) in theformof the objects. Hibernate is the open sourcelight weighttool given by GavinKing
Hibernateprovidesa solution to map databasetablesto a class. It copiesone row of the databasedatato a
class.In the otherdirection it supportsto saveobjectsto thedatabase.In thisprocess the objectis transformed
to oneor more tables.
Q.7. Write a sample hibernate configurationfile?Explainthe elementsofthe file
Ans: Configuration isthefile loaded into an hibernateapplication when working with hibernate,thisconfiguration file
contains 3 typesof information.
 Connection Properties
 HibernateProperties
 Mapping filename(s)
 <hibernate-configuration>:This is nextand parenttag for thehibernateconfiguration.Itis thebasetag,
containg all the hibernateconfiguration setting in its sub tags.
 <session-factory>: This is sub tag of <hibernate-configuration>thathold all the required propertiesto
communicatewiththe database,likedatabaseconnection setting url,usernate,password and etc.
 <property name = “---“>---</property>:This is the sub tag of <session-factory>,which describeall the
required propertiesin orderto communicatewith thedatabaselike connection propertiesfordatabase.
Q.8 ExplainFilterDispatcher and any two action componentsused by struts
Ans:  A Filter Dispatcheris used as the Controllerin Struts.
 Its namein packaged Structureisorg.apache.struts2.dispatcher.FilterDispatcher.
 Prior to using it in the application,it hasto be registered in theweb.xmlasbelow.
 At first theFilterDispatcher verifies therequest URIand determinesthe rightaction forit.
 The mappingsof URI’sand theaction classes are presentin the struts.xmlfilefound in theWEB-
INF/classesdirectory.
FilterDispatcherdoes the followingforeact actioninvocation.
1)Determineswhich action to invokefora requested URIby consulting theConfiguration manager
2) Interceptorsregistered forthe action areinvoked oneafter theother.
3) Then the action method is executed.
4) Then the Filter Dispatcherexecutesthe Result.
Optionally you can extend the ActionSupportclasswhich implementssix 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 Explainin briefMVC architecture with the helpof suitable diagram
Ans: Model-View-Controllerarchitectureis used for interactiveweb-applications.Thismodelminimizes
the coupling between businesslogicand data presentation to web user.This model dividesthe web based
application into three layers:
 Model:Model domain containsthebusinesslogicsand functionsthatmanipulatethe
businessdata.Itprovidesupdated information to view domain and also gives
responseto query.And thecontroller can accessthe functionality which is
encapsulated in themodel.
 View: Viewis responsibleforpresentation aspectof application according to themodel
dataand also responsibleto forward query responseto thecontroller.
 Controller:Controlleraccepts and interceptsuser requestsand controlsthebusiness
Objectsto fulfill these requests.An application hasonecontrollerfor related
functionality.Controllercan also be dependson thetype of clients.
Q.10 Write a short note on Interceptors instruts
Interceptorsallowforcrosscutting functionality to beimplemented separately fromthe action aswell as the
framework.You can achievethe following using interceptors:
 Providing preprocessing logicbeforetheaction is called.
 Providing postprocessinglogicafterthe action is called.
 Catching exceptionsso thatalternateprocessing can be performed.
 Many of the featuresprovided in the Struts2frameworkareimplemented using interceptors;examples
include exception handling,fileuploading,lifecyclecallbacksand validation etc.
Q.11 Explainthe differentrolesof Action in struts framework
 Actionsare the core of the Struts2framework,asthey arefor any MVC(ModelView Controller)
framework.Each URLis mapped to a specific action,which providesthe processing logicnecessary to
service the requestfromthe user.
 But the action also serves in two otherimportantcapacities.First, the action playsan importantrole in
the transferof datafromtherequestthrough to the view,whetherits a JSP orother typeof result.
Second,theaction must assistthe frameworkin determining which result should rendertheview that
will be returned in the responseto the request.
Q.12 What is value-stack?Whatare the differenttype of objectit can holdoff? Explaintheir accessing
strategies?WhatisOGNL ?
The valuestack is a set of several objects which keepsthe following objectsin the provided order:
SN Objects & Description
1
Temporary Objects
There are varioustemporary objectswhich arecreated during execution of a
page.Forexamplethe currentiteration valuefor a collection being looped
overin a JSPtag.
2
The Model Object
If you are using model objectsin yourstrutsapplication,thecurrentmodel
objectis placed beforetheaction on the valuestack
3
The ActionObject
This will be the currentaction objectwhich is being executed.
4
NamedObjects
These objectsinclude#application,#session,#request,#attr and #parameters
and refer to thecorresponding servletscopes
OGNL:
The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and
manipulatedataon theValueStack.OGNLalso helps in data transferand typeconversion.
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 thepound symbol.
As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The
ActionContextmap consistsof thefollowing:
 application - application scoped variables
 session- session scoped variables
 root / valuestack - all youraction variablesare stored here
 request - requestscoped variables
 parameters - requestparameters
 atributes- the attributesstored 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 objecthaspropertiesx and y there are readily availablefor you to use.

More Related Content

What's hot

Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
Tuna Tore
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
Tuna Tore
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
Pankaj Singh
 

What's hot (20)

Introduction to JSF
Introduction toJSFIntroduction toJSF
Introduction to JSF
 
Jsf
JsfJsf
Jsf
 
Exploring Maven SVN GIT
Exploring Maven SVN GITExploring Maven SVN GIT
Exploring Maven SVN GIT
 
Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)Lecture 10 - Java Server Faces (JSF)
Lecture 10 - Java Server Faces (JSF)
 
Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5Java Spring MVC Framework with AngularJS by Google and HTML5
Java Spring MVC Framework with AngularJS by Google and HTML5
 
Spring Web MVC
Spring Web MVCSpring Web MVC
Spring Web MVC
 
Java Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 BasicsJava Web Programming [7/9] : Struts2 Basics
Java Web Programming [7/9] : Struts2 Basics
 
Overview of JEE Technology
Overview of JEE TechnologyOverview of JEE Technology
Overview of JEE Technology
 
Spring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topicsSpring 3.x - Spring MVC - Advanced topics
Spring 3.x - Spring MVC - Advanced topics
 
Java Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVCJava Web Programming [6/9] : MVC
Java Web Programming [6/9] : MVC
 
Jsf intro
Jsf introJsf intro
Jsf intro
 
Building a Web-bridge for JADE agents
Building a Web-bridge for JADE agentsBuilding a Web-bridge for JADE agents
Building a Web-bridge for JADE agents
 
Introduction to struts
Introduction to strutsIntroduction to struts
Introduction to struts
 
Spring MVC
Spring MVCSpring MVC
Spring MVC
 
Struts ppt 1
Struts ppt 1Struts ppt 1
Struts ppt 1
 
Struts 1
Struts 1Struts 1
Struts 1
 
Java Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP BasicJava Web Programming [4/9] : JSP Basic
Java Web Programming [4/9] : JSP Basic
 
springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892springmvc-150923124312-lva1-app6892
springmvc-150923124312-lva1-app6892
 
Introduction to EJB
Introduction to EJBIntroduction to EJB
Introduction to EJB
 
Bea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guideBea weblogic job_interview_preparation_guide
Bea weblogic job_interview_preparation_guide
 

Viewers also liked

A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
SlideShare
 

Viewers also liked (14)

Computer institute website(TYIT project)
Computer institute website(TYIT project)Computer institute website(TYIT project)
Computer institute website(TYIT project)
 
HP Software Testing project (Advanced)
HP Software Testing project (Advanced)HP Software Testing project (Advanced)
HP Software Testing project (Advanced)
 
Testing project (basic)
Testing project (basic)Testing project (basic)
Testing project (basic)
 
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
A Guide to SlideShare Analytics - Excerpts from Hubspot's Step by Step Guide ...
 
What Makes Great Infographics
What Makes Great InfographicsWhat Makes Great Infographics
What Makes Great Infographics
 
Masters of SlideShare
Masters of SlideShareMasters of SlideShare
Masters of SlideShare
 
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to SlideshareSTOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
STOP! VIEW THIS! 10-Step Checklist When Uploading to Slideshare
 
You Suck At PowerPoint!
You Suck At PowerPoint!You Suck At PowerPoint!
You Suck At PowerPoint!
 
10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization10 Ways to Win at SlideShare SEO & Presentation Optimization
10 Ways to Win at SlideShare SEO & Presentation Optimization
 
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content MarketingHow To Get More From SlideShare - Super-Simple Tips For Content Marketing
How To Get More From SlideShare - Super-Simple Tips For Content Marketing
 
2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare2015 Upload Campaigns Calendar - SlideShare
2015 Upload Campaigns Calendar - SlideShare
 
What to Upload to SlideShare
What to Upload to SlideShareWhat to Upload to SlideShare
What to Upload to SlideShare
 
How to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & TricksHow to Make Awesome SlideShares: Tips & Tricks
How to Make Awesome SlideShares: Tips & Tricks
 
Getting Started With SlideShare
Getting Started With SlideShareGetting Started With SlideShare
Getting Started With SlideShare
 

Similar to TY.BSc.IT Java QB U6

Similar to TY.BSc.IT Java QB U6 (20)

Hibernate3 q&a
Hibernate3 q&aHibernate3 q&a
Hibernate3 q&a
 
141060753008 3715301
141060753008 3715301141060753008 3715301
141060753008 3715301
 
Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2Java J2EE Interview Question Part 2
Java J2EE Interview Question Part 2
 
Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2Java J2EE Interview Questions Part 2
Java J2EE Interview Questions Part 2
 
MVC
MVCMVC
MVC
 
Java hibernate orm implementation tool
Java hibernate   orm implementation toolJava hibernate   orm implementation tool
Java hibernate orm implementation tool
 
Hibernate Interview Questions and Answers
Hibernate Interview Questions and AnswersHibernate Interview Questions and Answers
Hibernate Interview Questions and Answers
 
Introduction to ejb and struts framework
Introduction to ejb and struts frameworkIntroduction to ejb and struts framework
Introduction to ejb and struts framework
 
Hibernate tutorial for beginners
Hibernate tutorial for beginnersHibernate tutorial for beginners
Hibernate tutorial for beginners
 
Free Hibernate Tutorial | VirtualNuggets
Free Hibernate Tutorial  | VirtualNuggetsFree Hibernate Tutorial  | VirtualNuggets
Free Hibernate Tutorial | VirtualNuggets
 
P20CSP105-AdvJavaProg.pptx
P20CSP105-AdvJavaProg.pptxP20CSP105-AdvJavaProg.pptx
P20CSP105-AdvJavaProg.pptx
 
Hibernate Developer Reference
Hibernate Developer ReferenceHibernate Developer Reference
Hibernate Developer Reference
 
Spatial approximate string search Doc
Spatial approximate string search DocSpatial approximate string search Doc
Spatial approximate string search Doc
 
Hibernate.pdf
Hibernate.pdfHibernate.pdf
Hibernate.pdf
 
Spring 2
Spring 2Spring 2
Spring 2
 
Introduction to Hibernate
Introduction to HibernateIntroduction to Hibernate
Introduction to Hibernate
 
Hibernate interview questions
Hibernate interview questionsHibernate interview questions
Hibernate interview questions
 
Hibernate in Action
Hibernate in ActionHibernate in Action
Hibernate in Action
 
Hibernate
HibernateHibernate
Hibernate
 
Struts N E W
Struts N E WStruts N E W
Struts N E W
 

More from Lokesh Singrol

More from Lokesh Singrol (13)

MCLS 45 Lab Manual
MCLS 45 Lab ManualMCLS 45 Lab Manual
MCLS 45 Lab Manual
 
MCSL 036 (Jan 2018)
MCSL 036 (Jan 2018)MCSL 036 (Jan 2018)
MCSL 036 (Jan 2018)
 
TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1TY.BSc.IT Java QB U1
TY.BSc.IT Java QB U1
 
TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2TY.BSc.IT Java QB U2
TY.BSc.IT Java QB U2
 
Project black book TYIT
Project black book TYITProject black book TYIT
Project black book TYIT
 
Internet of Things
Internet of ThingsInternet of Things
Internet of Things
 
Top Technology product failure
Top Technology product failureTop Technology product failure
Top Technology product failure
 
Computer institute Website(TYIT project)
Computer institute Website(TYIT project)Computer institute Website(TYIT project)
Computer institute Website(TYIT project)
 
Trees and graphs
Trees and graphsTrees and graphs
Trees and graphs
 
behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)behavioral model (DFD & state diagram)
behavioral model (DFD & state diagram)
 
Desktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld systemDesktop system,clustered system,Handheld system
Desktop system,clustered system,Handheld system
 
Raster Scan display
Raster Scan displayRaster Scan display
Raster Scan display
 
Flash memory
Flash memoryFlash memory
Flash memory
 

Recently uploaded

Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
EADTU
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
AnaAcapella
 

Recently uploaded (20)

Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptxExploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
Exploring_the_Narrative_Style_of_Amitav_Ghoshs_Gun_Island.pptx
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptxOn_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
On_Translating_a_Tamil_Poem_by_A_K_Ramanujan.pptx
 
21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx21st_Century_Skills_Framework_Final_Presentation_2.pptx
21st_Century_Skills_Framework_Final_Presentation_2.pptx
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
80 ĐỀ THI THỬ TUYỂN SINH TIẾNG ANH VÀO 10 SỞ GD – ĐT THÀNH PHỐ HỒ CHÍ MINH NĂ...
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
Towards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptxTowards a code of practice for AI in AT.pptx
Towards a code of practice for AI in AT.pptx
 
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPSSpellings Wk 4 and Wk 5 for Grade 4 at CAPS
Spellings Wk 4 and Wk 5 for Grade 4 at CAPS
 
Play hard learn harder: The Serious Business of Play
Play hard learn harder:  The Serious Business of PlayPlay hard learn harder:  The Serious Business of Play
Play hard learn harder: The Serious Business of Play
 
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdfUGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
UGC NET Paper 1 Unit 7 DATA INTERPRETATION.pdf
 
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptxHMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
HMCS Max Bernays Pre-Deployment Brief (May 2024).pptx
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Python Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docxPython Notes for mca i year students osmania university.docx
Python Notes for mca i year students osmania university.docx
 
Understanding Accommodations and Modifications
Understanding  Accommodations and ModificationsUnderstanding  Accommodations and Modifications
Understanding Accommodations and Modifications
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)Accessible Digital Futures project (20/03/2024)
Accessible Digital Futures project (20/03/2024)
 

TY.BSc.IT Java QB U6

  • 1. QUESTION BANK UNIT –VI Q.1 Explainthe Hibernate Framework Ans:  Hibernateis an Object-relationalmapping (ORM)tool.Object-relationalmappingorORMis a programming method formapping theobjectsto the relational modelwhereentities/classesare mapped to tables,instancesaremapped to rowsand attributesof instancesaremapped to columnsof table.  A “virtual objectdatabase”iscreated thatcan be used fromwithin the programming language.  Hibernateis a persistenceframeworkwhich isused to persist data fromJava environmentto database. Persistenceis a processof storing the data to some permanentmediumand retrieving it backat any pointof time even afterthe application thathad created thedata ended.  The abovediagramshowsa comprehensivearchitectureof Hibernate.In orderto persistdatato a database,Hibernatecreatean instanceof entity class(Java classmapped with databasetable). This objectis called Transient objectasthey arenot yet associated with thesession or notyet persisted to a database.  To persist theobjectto database,theinstanceof SessionFactory interfaceiscreated.SessionFactory isa singleton instancewhich implements Factory design pattern.SessionFactory loadshibernate.cfg.xml file(Hibernateconfiguration file.Moredetails in following section) and with the help of TransactionFactory and ConnectionProviderimplementsallthe configuration settingson a database.  Each databaseconnection in Hibernateis created by creating an instanceof Session interface.Session representsa single connection with database.Session objectsarecreated fromSessionFactory object.  Hibernatealso providesbuilt-in Transaction APIswhich abstractsaway the application fromunderlying JDBC or JTA transaction.Each transaction representsa singleatomic unitof work.OneSession can span through multipletransactions. SessionFactory(org.hibernate.SessionFactory) A thread-safe,immutablecacheof compiled mappingsfora single database. A factory fororg.hibernate.Session instances.A client of org.hibernate.connection.ConnectionProvider.Optionally maintainsa second levelcache of datathatis reusable between transactions ata processor cluster level. Session(org.hibernate.Session) A single-threaded,short-lived objectrepresenting a conversationbetween the application and thepersistent store.Wrapsa JDBC java.sql.Connection. Factory fororg.hibernate.Transaction.Maintainsa firstlevel cacheof persistentthe application’spersistentobjectsand collections;thiscache is used when navigating theobject graph orlooking up objectsby identifier.
  • 2. Persistent objectsand collections Short-lived,singlethreaded objects containing persistentstateand businessfunction.Thesecan beordinary JavaBeans/POJOs.They areassociated with exactly oneorg.hibernate.Session.Oncetheorg.hibernate.Session is closed, they will bedetached and free to use in any application layer (forexample, directly as datatransfer objectsto and frompresentation). Transient anddetached objects andcollections Instancesof persistentclassesthatare notcurrently associated with a org.hibernate.Session.They may have been instantiated by the application and notyet persisted,orthey may havebeen instantiated by a closed org.hibernate.Session. Transaction(org.hibernate.Transaction) (Optional) A single-threaded,short-lived objectused by theapplication to specify atomicunits of work.It abstractstheapplication fromthe underlying JDBC,JTA or CORBA transaction.A org.hibernate. Session might span severalorg.hibernate.Transactionsin somecases.However,transaction demarcation,eitherusing the underlying APIororg.hibernate.Transaction,is neveroptional. ConnectionProvider(org.hibernate.connection.ConnectionProvider) (Optional) A factory for,and poolof,JDBCconnections.Itabstractsthe application fromunderlying javax.sql.DataSourceorjava.sql.DriverManager. Itisnotexposed to application,butit can be extended and/or implemented by the developer. TransactionFactory(org.hibernate.TransactionFactory) (Optional) A factory fororg.hibernate.Transaction instances.Itisnot exposed to theapplication, butit can be extended and/orimplemented by the developer. Q.2 Explainthe Struts Framework Ans: The StrutsFrameworkisa standard fordeveloping well-architected Web applications.Ithasthe following features:  Open source  Based on the Model-View-Controller(MVC) design paradigm,distinctly separating allthreelevels: o Model: application state o View: presentation of data (JSP,HTML) o Controller:routing of theapplication flow  ImplementstheJSPModel 2 Architecture  Storesapplication routing information and requestmappingin a single core file, struts-config.xml The StrutsFramework,itself,only fills in theView and Controllerlayers. The Modellayer is left to the developer. All incoming requestsareintercepted by the Strutsservlet controller.The StrutsConfiguration filestruts-
  • 3. config.xmlisused by the controllerto determine therouting of the flow.This flowsconsistsof an alternation between two transitions: From Viewto Action: A userclicks on a link orsubmitsa formon an HTML or JSPpage.The controller receives the request, looksup the mapping forthisrequest,and forwardsitto an action.The action in turn calls a Modellayer From Actionto View: (Businesslayer) service or function.Afterthecall to an underlying function orservicereturnsto the action class, the action forwardsto a resource in the View layer and a pageis displayed in a web browser. The diagrambelowdescribes the flowin more detail: 1. User clicks on a link in an HTML page. 2. Servlet controller receives therequest,looksup mapping information in struts-config.xml,and routesto an action. 3. Action makesa call to a Modellayer service. 4. Service makesa call to the Datalayer (database)and therequested data isreturned. 5. Service returnsto theaction. 6. Action forwardsto a View resource(JSPpage) 7. Servlet looksup the mapping fortherequested resourceand forwards to theappropriateJSP page. 8. JSP file is invoked and sentto the browserasHTML. 9. User is presented witha newHTML pagein a web browser. Q.3 Explainweb.xml and struts.xml files Ans: The interactions in MVCmodel between Model,View and Controllerflow are taken care by the struts configuration files.Thesefiles are web.xml,struts.xml,struts-config.xmland struts.properties. web.xml:  The web.xmlconfiguration fileis a J2EE configuration filethatdetermines how elementsof the HTTP requestare processed by the servlet container.  The web.xml web application descriptor file represents the core of the Java web application, so it is appropriatethatit is also partof the core of the Strutsframework.  In the web.xml file, Struts defines its FilterDispatcher, the Servlet Filter class that initializes the Struts frameworkand handlesallrequests.  This filter can contain initialization parameters that affect what, if any, additional configuration files are loaded and howtheframeworkshould behave.  The web.xmlfile needsto be created underthefolderWebContent/WEB-INF.  Configuring web.xmlfortheframeworkisa matterof adding a filter and filter-mapping.
  • 4. 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 = falseand other settingswhich are defined in property file.  This file can be created underthe folder WEB-INF/classes. Example: <struts> <constantname="struts.devMode"value="true"/> <packagename="helloworld"extends="struts-default"> <action name="hello"class="HelloWorldAction" method="execute"> <result name="success">/HelloWorld.jsp</result> </action> </package> </struts> Q.4 What is objectrelational mapping(ORM)?what are its advantages? Ans: 1. FacilitatesimplementingtheDomainModel pattern: This onereason supersedesall others.In short using this pattern meansthatyou modelentities based on real businessconceptsratherthan based on yourdatabasestructure.ORMtoolsprovidethisfunctionality through mapping between thelogical businessmodeland the physicalstoragemodel. 2. Huge reduction incode: ORM toolsprovidea hostof services thereby allowing developersto focuson the businesslogic of the application rather than repetitive CRUD(CreateRead UpdateDelete) logic. 3. Changesto the object model are made in one place:One you updateyourobjectdefinitions,theORM will automatically usethe updated structurefor retrievalsand updates.Thereare no SQL Update,Delete and Insertstatementsstrewn throughoutdifferentlayersof theapplication thatneed modification. 4. Rich query capability:ORMtoolsprovidean objectoriented query language.Thisallowsapplication developersto focuson the objectmodel and notto haveto be concerned with thedatabasestructureor SQL semantics.TheORM tool itself will translatethequery languageinto the appropriatesyntax forthe database. 5. Navigation:You can navigateobjectrelationshipstransparently.Related objectsareautomatically loaded asneeded.For exampleif you load a POand you wantto accessit's Customer,you can simply access PO. Customerand theORMwill take care of loading thedata for you without any efforton your part. 6. Data loadsare completelyconfigurableallowingyoutoloadthe data appropriatefor each scenario. For examplein onescenario you mightwantto load a list of POswithoutany of its child / related objects, while in other scenariosyou can specify to load a PO,with all its child Line Items,etc. 7. Concurrencysupport: Supportformultipleusers updating thesamedata simultaneously. 8. Cache management:Entities are cached in memory thereby reducing load on the database. 9. Transactionmanagementand Isolation:Allobjectchangesoccurscoped to a transaction.Theentire transaction can either be committed orrolled back. Multipletransactionscan be activein memory in the sametime, and each transactionschangesareisolated formon another. 10. Key Management: Identifiersand surrogatekeysareautomatically propogated and managed. Q.5 What is the importance of hibernate mapping file?Explainwith suitable example Ans:  Mapping fileis the heartof hibernateapplication.  Every ORMtool needsthis mapping,mappingisthe mechanismof placing an objectpropertiesinto column’sof a table.  Mapping can begiven to an ORMtool either in the formof an XMLor in theformof theannotations.  The mapping file contains mapping froma pojo classnameto a table nameand pojo classvariable namesto table column names.  While writing an hibernateapplication,wecan construct oneor more mapping files,mean a hibernate application can contain any numberof mapping files.
  • 5.  generally an objectcontains 3 properties like Identity (ObjectName) State(Objectvalues) Behavior(ObjectMethods) Example: <hibernate-mapping> <class name="Employee"table="EMPLOYEE"> <meta attribute="class-description">Thisclass containstheemployeedetail. </meta> <id name="id"type="int"column="id"> <generatorclass="native"/> </id> <propertyname="firstName"column="first_name" type="string"/> <propertyname="lastName"column="last_name" type="string"/> <propertyname="salary"column="salary"type="int"/> </class> </hibernate-mapping> Q.6 Explainthe working of Hibernate Ans: Hibernateis the ORMtool given to transferthedata between a java (object) application and a database (Relational) in theformof the objects. Hibernate is the open sourcelight weighttool given by GavinKing Hibernateprovidesa solution to map databasetablesto a class. It copiesone row of the databasedatato a class.In the otherdirection it supportsto saveobjectsto thedatabase.In thisprocess the objectis transformed to oneor more tables. Q.7. Write a sample hibernate configurationfile?Explainthe elementsofthe file
  • 6. Ans: Configuration isthefile loaded into an hibernateapplication when working with hibernate,thisconfiguration file contains 3 typesof information.  Connection Properties  HibernateProperties  Mapping filename(s)  <hibernate-configuration>:This is nextand parenttag for thehibernateconfiguration.Itis thebasetag, containg all the hibernateconfiguration setting in its sub tags.  <session-factory>: This is sub tag of <hibernate-configuration>thathold all the required propertiesto communicatewiththe database,likedatabaseconnection setting url,usernate,password and etc.  <property name = “---“>---</property>:This is the sub tag of <session-factory>,which describeall the required propertiesin orderto communicatewith thedatabaselike connection propertiesfordatabase. Q.8 ExplainFilterDispatcher and any two action componentsused by struts Ans:  A Filter Dispatcheris used as the Controllerin Struts.  Its namein packaged Structureisorg.apache.struts2.dispatcher.FilterDispatcher.  Prior to using it in the application,it hasto be registered in theweb.xmlasbelow.  At first theFilterDispatcher verifies therequest URIand determinesthe rightaction forit.  The mappingsof URI’sand theaction classes are presentin the struts.xmlfilefound in theWEB- INF/classesdirectory. FilterDispatcherdoes the followingforeact actioninvocation. 1)Determineswhich action to invokefora requested URIby consulting theConfiguration manager 2) Interceptorsregistered forthe action areinvoked oneafter theother. 3) Then the action method is executed. 4) Then the Filter Dispatcherexecutesthe Result. Optionally you can extend the ActionSupportclasswhich implementssix interfaces including Actioninterface.The Action interface is as follows: public interface Action {
  • 7. 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 Explainin briefMVC architecture with the helpof suitable diagram Ans: Model-View-Controllerarchitectureis used for interactiveweb-applications.Thismodelminimizes the coupling between businesslogicand data presentation to web user.This model dividesthe web based application into three layers:  Model:Model domain containsthebusinesslogicsand functionsthatmanipulatethe businessdata.Itprovidesupdated information to view domain and also gives responseto query.And thecontroller can accessthe functionality which is encapsulated in themodel.  View: Viewis responsibleforpresentation aspectof application according to themodel dataand also responsibleto forward query responseto thecontroller.  Controller:Controlleraccepts and interceptsuser requestsand controlsthebusiness Objectsto fulfill these requests.An application hasonecontrollerfor related functionality.Controllercan also be dependson thetype of clients. Q.10 Write a short note on Interceptors instruts Interceptorsallowforcrosscutting functionality to beimplemented separately fromthe action aswell as the framework.You can achievethe following using interceptors:  Providing preprocessing logicbeforetheaction is called.  Providing postprocessinglogicafterthe action is called.  Catching exceptionsso thatalternateprocessing can be performed.  Many of the featuresprovided in the Struts2frameworkareimplemented using interceptors;examples
  • 8. include exception handling,fileuploading,lifecyclecallbacksand validation etc. Q.11 Explainthe differentrolesof Action in struts framework  Actionsare the core of the Struts2framework,asthey arefor any MVC(ModelView Controller) framework.Each URLis mapped to a specific action,which providesthe processing logicnecessary to service the requestfromthe user.  But the action also serves in two otherimportantcapacities.First, the action playsan importantrole in the transferof datafromtherequestthrough to the view,whetherits a JSP orother typeof result. Second,theaction must assistthe frameworkin determining which result should rendertheview that will be returned in the responseto the request. Q.12 What is value-stack?Whatare the differenttype of objectit can holdoff? Explaintheir accessing strategies?WhatisOGNL ? The valuestack is a set of several objects which keepsthe following objectsin the provided order: SN Objects & Description 1 Temporary Objects There are varioustemporary objectswhich arecreated during execution of a page.Forexamplethe currentiteration valuefor a collection being looped overin a JSPtag. 2 The Model Object If you are using model objectsin yourstrutsapplication,thecurrentmodel objectis placed beforetheaction on the valuestack 3 The ActionObject This will be the currentaction objectwhich is being executed. 4 NamedObjects These objectsinclude#application,#session,#request,#attr and #parameters and refer to thecorresponding servletscopes OGNL: The Object-Graph Navigation Language (OGNL) is a powerful expression language that is used to reference and manipulatedataon theValueStack.OGNLalso helps in data transferand typeconversion. 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 thepound symbol. As mentioned earlier, OGNL is based on a context and Struts builds an ActionContext map for use with OGNL. The ActionContextmap consistsof thefollowing:  application - application scoped variables  session- session scoped variables  root / valuestack - all youraction variablesare stored here  request - requestscoped variables  parameters - requestparameters  atributes- the attributesstored 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
  • 9. Action objecthaspropertiesx and y there are readily availablefor you to use.