Sie sind auf Seite 1von 73

MahatmaGandhiMissions

JawaharlalNehruEngineeringCollege

LaboratoryManual

ADVANCEDJAVA

For

FinalYearCSEStudents Dept:ComputerScience&Engineering(NBAAccredited)

Author JNEC, Aurangabad

FOREWORD

It is my great pleasure to present this laboratory manual for Final Year engineering students for the subject of Advanced Java keeping in view the vastcoveragerequiredforProgrammingwithJavaLanguage

Asastudent,manyofyoumaybewonderingwithsomeofthequestionsin yourmindregardingthesubjectandexactlywhathasbeentriedistoanswer throughthismanual.

Asyou maybeawarethatMGMhasalreadybeenawardedwithISO9000 certificationanditisourenduretotechnicallyequipourstudentstakingthe advantageoftheproceduralaspectsofISO9000Certification.

Facultymembersarealsoadvisedthatcoveringtheseaspectsininitialstage itself,will greatly relived them in futureas muchof the loadwillbe taken care by the enthusiasmenergies of the students once they are conceptually clear.

Dr.S.D.Deshmukh Principal

LABORATORYMANUALCONTENTS
This manual is intended for the Final Year students of Computer Science and Engineering in the subject of Advanced Java. This manual typically contains practical/Lab Sessions related Advanced Java covering various aspectsrelatedthesubjecttoenhancedunderstanding.

AsperthesyllabusalongwithStudyofAdvancedJava,wehave madethe efforts to cover various aspects of Advanced Java covering different Techniques used to construct and understand concepts of Advanced Java Programming.

Studentsareadvisedtothoroughlygothroughthis manualratherthanonly topics mentioned in the syllabus as practical aspects are the key to understandingandconceptualvisualizationoftheoreticalaspectscoveredin thebooks.

GoodLuckforyourEnjoyableLaboratorySessions

Ms.D.S.DeshpandeMs. S.A.Shingare HOD, ComputerScience&EnggDept. Lecturer, ComputerScience&EnggDept.

DOsandDONTsinLaboratory:

1.MakeentryintheLogBookassoonasyouentertheLaboratory.

2.Allthestudentsshouldsitaccordingtotheirrollnumbersstartingfrom theirlefttoright.

3.Allthestudentsaresupposedtoentertheterminalnumberinthelog book.

4.Donotchangetheterminalonwhichyouareworking.

5.Allthestudentsareexpectedtogetatleastthealgorithmofthe program/concepttobeimplemented.

6.Strictlyobservetheinstructionsgivenbytheteacher/LabInstructor.

InstructionforLaboratoryTeachers::

1.Submissionrelatedtowhateverlabworkhasbeencompletedshouldbe doneduringthenextlabsession.Theimmediatearrangementsforprintouts relatedtosubmissiononthedayofpracticalassignments.

2.Studentsshouldbetaughtfortakingtheprintoutsundertheobservationof labteacher.

3.Thepromptnessofsubmissionshouldbeencouragedbywayofmarking andevaluationpatternsthatwillbenefitthesincerestudents.
4

SUBJECTINDEX

1.Programtoperformdatabaseoperation. 2.Basicservletprogram 3.BasicJSPprogram 4.DatabaseOperationinjsp 5.Programfor<jsp:useBean>Tag 6.Sessionmanagementinjsp 7.ProgramforCustomJSPTag 8.ProgramforBasicHibernate 9.DatabaseOperationUsingHibernate 10.WebServices.

HARDWARE REQUIRED

PIV/III PROCESSOR HDD 40GB RAM 128 OR ABOVE

SOFTWARE REQUIRED

Windows 98/2000/ME/XP Java Enterprise Edition 5 Web Server (Apache Tomcat) Eclipse OR Net Beans IDE

1.Program to perform database operation


Aim:Write Program to perform database operation.

Theory: JDBC Calllevel interfaces such as JDBC are programming interfaces allowing externalaccesstoSQLdatabasemanipulationandupdatecommands.They allowtheintegrationofSQLcallsintoageneralprogrammingenvironment byprovidinglibraryroutinewhichinterfacewiththedatabase.Inparticular, java based JDBC has a rich collection of routines which make such an interfaceextremelysimpleandintuitive. What happens in a call level interface: you are writing a normal java program.Somewhere ina program, youneedto interact withadatabase. Using standard library routines, you open a connection with database. you thenuseJDBStosendyourSQLcodetothedatabase,andprocesstheresult thatarereturned.Whenyouaredone,you closetheconnection. A file system does not work well for data storage applications for e.g. Business applications so we required power of database. Java provide file systemaccesswithdatabaseconnectivitycalledJDBC. TheJDBC(JavaDatabaseConnectivity)APIdefinesinterfacesandclasses for writing database applications in Java by making database connections. Using JDBC, you can send SQL, PL/SQL statements to almost any relationaldatabase.JDBC isaJava API forexecutingSQLstatementsand supports basic SQL functionality. It provides RDBMS access by allowing youtoembedSQLinsideJavacode.BecauseJavacanrunonathinclient, applets embedded in Web pages can contain downloadable JDBC code to enableremotedatabaseaccess.
7

We can also create a table, insert values into it, query the table, retrieve results,andupdatethetablewiththehelpofaJDBCProgramexample. Although JDBC was designed specifically to provide a Java interface to relationaldatabases,wemayfindthatyouneedtowriteJavacodetoaccess nonrelationaldatabasesaswell.

JDBCArchitecture

JavaapplicationcallstheJDBClibrary.JDBCloadsadriverthattalkstothe database.Wecanchangedatabaseengineswithoutchangingdatabasecode. JDBCBasicsJavaDatabaseConnectivitySteps Beforeyoucancreateajavajdbcconnectiontothedatabase,youmustfirst importthejava.sqlpackage. importjava.sql.*Thestar(*)indicatesthatalloftheclassesinthepackage java.sqlaretobeimported. 1.Loadingadatabasedriver, Inthisstepofthejdbcconnectionprocess,weloadthedriverclassby callingClass.forName()withtheDriverclassnameasanargument.Once loaded,theDriverclasscreatesaninstanceofitself.Aclientcanconnectto DatabaseServerthroughJDBCDriver.SincemostoftheDatabaseservers supportODBCdriverthereforeJDBCODBCBridgedriveriscommonly used.
8

ThereturntypeoftheClass.forName(StringClassName)methodisClass. java.langpackage.

Syntax:
try{

Class.forName(sun.jdbc.odbc.JdbcOdbcDriver)//Oranyother driver } catch(Exceptionx){ System.out.println(Unabletoloadthedriverclass!)

2.CreatingaoraclejdbcConnection TheJDBCDriverManagerclassdefinesobjectswhichcanconnectJava applicationstoaJDBCdriver.DriverManagerisconsideredthebackboneof JDBCarchitecture.DriverManagerclassmanagestheJDBCdriversthatare installedonthesystem.ItsgetConnection()methodisusedtoestablisha connectiontoadatabase.Itusesausername,password,andajdbcurlto establishaconnectiontothedatabaseandreturnsaconnectionobject.A jdbcConnectionrepresentsasession/connectionwithaspecificdatabase. WithinthecontextofaConnection,SQL,PL/SQLstatementsareexecuted andresultsarereturned.Anapplicationcanhaveoneormoreconnections withasingledatabase,oritcanhavemanyconnectionswithdifferent databases.AConnectionobjectprovidesmetadatai.e.informationaboutthe database,tables,andfields.Italsocontainsmethodstodealwith transactions. 3.CreatingajdbcStatementobject, Onceaconnectionisobtainedwecaninteractwiththedatabase.Connection interface defines methods for interacting with the database via the
9

establishedconnection.ToexecuteSQLstatements,youneedtoinstantiatea StatementobjectfromyourconnectionobjectbyusingthecreateStatement() method. Statementstatement=dbConnection.createStatement() A statement object is used to send and execute SQL statements to a database.
4.ExecutingaSQLstatementwiththeStatementobject,andreturning

ajdbcresultSet. Statement interface defines methods that are used to interact with database viatheexecutionofSQLstatements.TheStatementclasshasthreemethods executeQuery(),executeUpdate(),andexecute().
JDBCdriversTypes:

JDBCdriversaredividedintofourtypesorlevels.Thedifferenttypesof jdbcdriversare: Type1:JDBCODBCBridgedriver(Bridge) Type2:NativeAPI/partlyJavadriver(Native) Type3:AllJava/Netprotocoldriver(Middleware) Type4:AllJava/Nativeprotocoldriver(Pure) Type1JDBCDriver:JDBCODBCBridgedriver TheType1drivertranslatesallJDBCcallsintoODBCcallsandsendsthem to the ODBC driver. ODBC is a generic API. The JDBCODBC Bridge

10

Type1:JDBCODBCBridge

NativeAPI/partlyJavadriver Thedistinctivecharacteristicoftype2jdbcdriversare that Type 2drivers convertJDBCcallsintodatabasespecificcallsi.e.thisdriverisspecifictoa particulardatabase.Somedistinctivecharacteristicoftype2jdbcdriversare shownbelow.Example:Oraclewillhaveoraclenativeapi.

Type2:Nativeapi/PartlyJavaDriver E.g.:
11

OrdersTable:

CREATETABLEOrders( Prod_IDINTEGER, ProductNameVARCHAR(20), Employee_IDINTEGER ) Type3JDBCDriver


AllJava/Netprotocoldriver

Type3databaserequestsarepassedthroughthenetworktothemiddletier server. The middletier then translates the request to the database. If the middletierservercanin turnuseType1,Type2orType4drivers.

Type3:AllJava/NetProtocolDriver

Type4JDBCDriver Nativeprotocol/allJavadriver TheType4usesjavanetworkinglibrariestocommunicatedirectlywiththe databaseserver.

12

Type4:Nativeprotocol/allJavadriver Advantage The JDBCODBC Bridge allows access to almost any database, since the databasesODBCdriversarealreadyavailable. Disadvantages 1. SincetheBridgedriverisnotwrittenfullyinJava,Type1driversare notportable. 2. AperformanceissueisseenasaJDBCcallgoesthroughthebridge totheODBCdriver,thentothedatabase,andthisapplieseveninthe reverseprocess.Theyaretheslowestofalldrivertypes. 3. TheclientsystemrequirestheODBCInstallationtousethedriver. 4. NotgoodfortheWeb.

13

Algorithm: 1)CerateaTableinMsAccess,saveitindatabase. 2)writejavaprogram,ImportjavaPackagesinprogram. 3)DefineclassestablishODBCconnectionwiththehelpofjavacode. 4)Insertrecordintodatabasewiththehelpof SQLqueries. 5)Executeprogram,seetheOponconsoleprompt.

ThemethodClass.forName(String)isusedtoloadtheJDBCdriverclass. ThelinebelowcausestheJDBCdriverfrom somejdbcvendortobeloaded intotheapplication.(SomeJVMsalsorequiretheclasstobeinstantiated with .newInstance().)

Class.forName("com.somejdbcvendor.TheirJdbcDriver" )

WhenaDriverclassisloaded,itcreatesaninstanceofitselfandregistersit withtheDriverManager.Thiscanbedonebyincludingtheneededcodein thedriverclass'sstaticblock.e.g.DriverManager.registerDriver(Driver driver) Nowwhenaconnectionisneeded,oneofthe DriverManager.getConnection()methodsisusedtocreateaJDBC connection.

Connection conn=DriverManager.getConnection( "jdbc:somejdbcvendor:otherdataneededbysomejdbcvendor", "myLogin", "myPassword" )


14

TheURLusedisdependentupontheparticularJDBCdriver.Itwillalways beginwiththe"jdbc:"protocol,buttherestisuptotheparticularvendor. Onceaconnectionisestablished,astatementmustbecreated.

Statementstmt=conn.createStatement() try { stmt.executeUpdate("INSERTINTOMyTable(name)VALUES('my name')" ) }finally { //It'simportanttoclosethestatementwhenyouaredonewithit stmt.close() }

Output:

Conclusion:

Hence,welearnthowtoperformdatabaseoperation.
15

2. BasicServletProgram

Aim:Writeaprogram todemonstrateBasicServlet.

Theory: AsweknowthattheservletextendstheHttpServletandoverridesthe doGet()methodwhichitinheritsfromtheHttpServletclass.The server invokesdoGet()methodwheneverwebserverreceivestheGETrequest fromtheservlet.ThedoGet()methodtakestwoargumentsfirstis HttpServletRequestobjectandthesecondoneisHttpServletResponseobject andthismethodthrowstheServletException. Whenevertheusersendstherequesttotheserverthenservergenerates twoobjectsfirstisHttpServletRequestobjectandthesecondoneis HttpServletResponseobject.HttpServletRequestobjectrepresentsthe client'srequestandtheHttpServletResponserepresentstheservlet's response. InsidethedoGet()methodourservlethasfirstusedthesetContentType() methodoftheresponseobjectwhichsetsthecontenttypeoftheresponse totext/htmlItisthestandardMIMEcontenttypeforthehtmlpages. AfterthatithasusedthemethodgetWriter()oftheresponseobjectto retrieveaPrintWriterobject. Todisplaytheoutputonthebrowserwe usetheprintln()methodofthePrintWriterclass.

16

Program Import java.io.IOException import java.io.PrintWriter import javax.servlet.ServletException import javax.servlet.http.HttpServlet import javax.servlet.http.HttpServletRequest import javax.servlet.http.HttpServletResponse public classhelloextendsHttpServlet{ privatestaticfinallongserialVersionUID=1L publicvoiddoGet(HttpServletRequestrequest,HttpServletResponse response)throwsServletException,IOException{ PrintWriterout=response.getWriter() java.util.Datetoday=newjava.util.Date() out.println("<html>"+"<body>"+"<h1align=center>welcometo excitingworldofservlet</h1>"+"<br>"+today+"</body>"+"</html>") } }

SteptoRuntheProgram 1)Removealltheerrorsintheprogram. 2)Startthewebserver. 3)Deployyourprogramtothewebserver 4)Open thewebbrowserandexecutetheprogramas http://localhost:8080/myservlet/hello

17

Output:

Conclusion: Hencewestudiedhowtocreateasampleservlettodisplaydate andthetime.

18

3. Basic JSP program

Aim:Writeaprogram todemonstratebasicjspexample.

Theory: JAVASERVERPAGES JavaServerPages(JSP)isajavatechnologythatallowssoftwaredeveloper todynamicallygenerateaHTML,XMLorothertypesofthedocumentsin response to a web client request. The technology allows java code and certainpredefinedactionstobeembeddedintostaticcontent. ThejspsyntaxaddsadditionalXMLliketags,calledJSPaction,to beused to invoke built in functionality dynamically generate .Additionally the technologyallows us for thecreationofthe jsptags librariesthatactsasa extension to the standard HTML or XML tags. Tag libraries provide the platformindependentwayofextendingthecapabilitiesofawebserver. JSParecompiledintothejavaservletbythejavacompiler.Ajspcompiler may generate a servlet in java code that is then compiled by the java compiler. JSP technology may enable the web developer and designers to rapidly develops and easily maintain, information rich, dynamic web pages that leverageexistingbusinesssystem. ThissimplepagecontainsplainHTML,exceptforcoupleoftheJSP directivesandtags.ThefirstoneintheHelloWorld.jspisapagedirective thatdefinesthecontenttypeandcharactersetoftheentirepage.Java methodprintln()toprintoutput.By thisexamplewearegoingtolearn thathowcanyouwriteajspprogramonyourbrowser..

19

ThisprogramalsocontainsHTML(HypertextMarkupLanguage)codefor designingthepageandthecontents.Followingcodeoftheprogramprints thestring"HelloWorld!"byusing <%="HelloWorld!"%>whileyoucan alsoprintthestringbyusingout.println().

Program:

<%@pagelanguage="java" contentType="text/htmlcharset=ISO88591" pageEncoding="ISO88591"%> <%@pagelanguage="java" %> <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttpequiv="ContentType" content="text/htmlcharset=ISO8859 1"> <title>thisisjsp1</title> </head> <bodybgcolor="red"> <fontsize="10"> <% Stringname="roseindia.net" out.println("hello"+name+"!") %> </font> </body> </html>

SteptoRuntheProgram: 1)Removealltheerrorsintheprogram. 2)Startthewebserver. 3)Deployyourprogramtothewebserver


20

4)Openthewebbrowserandexecutetheprogramas http://localhost:8080/secondjsp/jsp1.jsp

Output:

Conclusion: HencewestudiedhowcreatetheServlet.

21

4.Programfor DatabaseOperationinjsp

Aim:Writeaprogram toperformdatabaseoperationinjsp.

Theory:

Createadatabase: Firstcreateadatabasenamed'student'inmysqlandtablenamed "stu_info"insamedatabasebysqlquerygivenbelow: Createdatabasestudent createtablestu_info( IDintnotnullauto_increment, Namevarchar(20), Cityvarchar(20), Phonevarchar(15), primarykey(ID) )

Createanewdirectorynamed"user"inthetomcat6.0.16/webappsand WEBINFdirectoryinsamedirectory.Beforerunningthisjavacodeyou needtopastea.jarfilenamedmysqlconnector.jarintheTomcat 6.0.16/webapps/user/WEBINF/lib. prepared_statement_query.jsp Savethiscodeasa.jspfilenamed"prepared_statement_query.jsp"inthe directoryTomcat6.0.16/webapps/user/andyoucanrunthisjsppagewith urlhttp://localhost:8080/user/prepared_statement_query.jspinaddress barofthebrowser

22

<!DOCTYPEHTML PUBLIC"//W3C//DTDHTML4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@pageimport="java.sql.*"%> <%@pageimport="java.io.*"%> <HTML> <HEAD> <TITLE>insertdatausingpreparedstatement</TITLE> </HEAD> <BODYbgcolor="#ffffcc"> <fontsize="+3" color="green"><br>Welcomeinwww.roseindia.net !</font> <FORMaction="prepared_statement_query.jsp"method="get"> <TABLEstyle="backgroundcolor:#ECE5B6"WIDTH="30%"> <TR> <THwidth="50%">Name</TH> <TDwidth="50%"><INPUTTYPE="text"NAME="name"></TD> </tr> <TR> <THwidth="50%">City</TH> <TDwidth="50%"><INPUTTYPE="text"NAME="city"></TD> </tr> <TR> <THwidth="50%">Phone</TH> <TDwidth="50%"><INPUTTYPE="text"NAME="phone"></TD> </tr> <TR> <TH></TH> <TDwidth="50%"><INPUTTYPE="submit"VALUE="submit"></TD> </tr> </TABLE> <% Stringname=request.getParameter("name") Stringcity=request.getParameter("city") Stringphone=request.getParameter("phone") StringconnectionURL="jdbc:mysql: Connection connection=null PreparedStatementpstatement=null
23

Class.forName("com.mysql.jdbc.Driver").newInstance() intupdateQuery=0 if(name!=null&&city!=null&&phone!=null){ if(name!=""&&city!=""&&phone!=""){ try{ connection=DriverManager.getConnection (connectionURL,"root","root") StringqueryString="INSERTINTOstu_info(Name, Address,Phone)VALUES(?,?,?)" pstatement=connection.prepareStatement(queryString) pstatement.setString(1,name) pstatement.setString(2,city) pstatement.setString(3,phone) updateQuery=pstatement.executeUpdate() if(updateQuery!=0){%> <br> <TABLEstyle="backgroundcolor:#E3E4FA" WIDTH="30%"border="1"> <tr><th>Dataisinsertedsuccessfully indatabase.</th></tr> </table> <% } } catch(Exceptionex){ out.println("Unabletoconnecttodatabase.") } finally{ . pstatement.close() connection.close() } } } %> </FORM> </body> </html>
24

Output:

Fillallthefieldsandclickonsubmitbutton,thatshowsaresponsemessage. Ifanyfieldisblankoronlyblankspacesaretherepagewillremainsame afterclickingonsubmitbutton.

25

UpdateData: Thisexampleshowshowtoupdatetheexisting recordofmysqltableusing jdbcconnectivityinthejsppage.Inthisexamplewehavecreatedtwojsp pagesupdate.jspandupdatingDatabase.jsp. Intheupdate.jsppage,we areusingaTextboxwhereusercangivehis/hernameandsubmitthepage. Aftersubmittingthepage, updatingDatabase.jspwillbecalledandthesql query ("updateservletsetname=?whereid=?")isexecutedwhichwill modifythetablerecord.

26

<%@pagelanguage=javasession=true contentType=text/htmlcharset=%> <fontcolorbluePleaseEnterYourName</font><br><br> <formname="frm"method="post" action="updatingDatabase.jsp"> <tableborder="0"> <tralign="left"valign="top"> <td>Name:</td> <td><inputtype="text"name="name" /></td> </tr> <tralign="left"valign="top"> <td></td> <td><inputtype="submit" name="submit"value="submit"/></td> </tr> </table> </form> Typetheurl:http://localhost:8080/ServletExample/jsp/update.jspon yourbrowser.Followingoutputwillbedisplayed:

27

updatingDatabase.jsp

<%@pagelanguage="java" contentType= "text/htmlcharset=ISO88591" import="java.io.*" import="java.sql.*" import="java.util.*" import="javax.sql.*" import="java.sql.ResultSet" import="java.sql.Statement" import="java.sql.Connection" import="java.sql.DriverManager" import="java.sql.SQLException" %> <% Connection con =null PreparedStatementps=null ResultSetrs=null Statementstmt=null Stringname=request.getParameter("name") Integerid=5 %> <html> <head> <title>Updating Database</title> </head> <body> <% try{ Class.forName("com.mysql.jdbc.Driver") con =DriverManager.getConnection ("jdbc:mysql://192.168.10.59:3306/example", "root","root") ps= con.prepareStatement("updateservletset name=? whereid=?") ps.setInt(2,id) ps.setString(1,name) ps.executeUpdate() %> Database successfullyUpdated!<br> <% if(ps.executeUpdate()>=1){
28

stmt=con.createStatement() rs= stmt.executeQuery("SELECT* FROMservlet") while(rs.next()){ %> <%=rs.getObject(1).toString()%> <%=("\t\t\t")%> <%=rs.getObject(2).toString()%> <%=("<br>")%> <% } } }catch (IOException e){ thrownew IOException("Cannotdisplay records.",e) }catch (ClassNotFoundException e){ thrownew SQLException("JDBCDrivernotfound.",e) } finally{ try{ if(stmt!=null){ stmt.close() stmt=null } if(ps!=null){ ps.close() ps =null } if(con!=null){ con.close() con =null } }catch (SQLException e){} } %> </body> </html> Aftersubmittingthename,itwillbeupdatedinthedatabaseandtherecords willbedisplayedonyourbrowser.

29

Savethiscodeasa.jspfilenamed"prepared_statement_query.jsp"inthe directoryTomcat6.0.16/webapps/user/andyoucanrunthisjsppagewith urlhttp://localhost:8080/user/prepared_statement_query.jspinaddress barofthebrowser.

Conclusion: Hencewestudiedhowtoperformdifferentdatabase operationinjsp.

30

5.Programfor<jsp:useBean>Tag

Aim:Program touse<jsp:useBean>TaginJSP.

Theory: The<jsp:useBean>elementlocatesorinstantiatesaJavaBeanscomponent. <jsp:useBean>firstattemptstolocateaninstanceoftheBean.IftheBean doesnotexist,<jsp:useBean>instantiatesitfromaclassorserialized template. TolocateorinstantiatetheBean,<jsp:useBean>takesthefollowingsteps, inthisorder: 1. AttemptstolocateaBeanwiththescopeandnameyouspecify. 2. Definesanobjectreferencevariablewiththenameyouspecify. 3. IfitfindstheBean,storesareferencetoitinthevariable.Ifyou specifiedtype,givestheBeanthattype. 4. IfitdoesnotfindtheBean,instantiatesitfromtheclassyouspecify, storingareferencetoitinthenewvariable.Iftheclassname representsaserializedtemplate,theBeanisinstantiatedby java.beans.Beans.instantiate. 5. If <jsp:useBean>hasinstantiatedtheBean,andifithasbodytagsor elements(between <jsp:useBean>and</jsp:useBean>),executesthe bodytags. Thebodyofa<jsp:useBean>elementoftencontainsa<jsp:setProperty> elementthatsetspropertyvaluesintheBean.Asdescribedin Step5,the bodytagsareonlyprocessedif <jsp:useBean>instantiatestheBean.Ifthe Beanalreadyexistsand<jsp:useBean>locatesit,thebodytagshaveno effect.

31

JSPSyntax <jsp:useBean id="beanInstanceName" scope="page|request|session|application" { class="package.class"| type="package.class"| class="package.class"type="package.class"| beanName="{package.class| <%=expression%>}" type="package.class" } { />| > otherelements</jsp:useBean> } Examples <jsp:useBeanid="cart"scope="session"class="session.Carts"/> <jsp:setPropertyname="cart"property="*"/> <jsp:useBeanid="checking"scope="session"class="bank.Checking"> <jsp:setPropertyname="checking"property="balance"value="0.0"/> </jsp:useBean>

AttributesandUsage

id="beanInstanceName" AvariablethatidentifiestheBeaninthescopeyouspecify.Youcan usethevariablenameinexpressionsorscriptletsintheJSPfile. Thenameiscasesensitiveandmustconformtothenaming conventionsofthescriptinglanguageusedintheJSPpage.Ifyouuse theJavaprogramminglanguage,theconventionsintheJava LanguageSpecification.IftheBeanhasalreadybeencreatedby another<jsp:useBean>element,thevalueofidmustmatchthevalue of idusedintheoriginal <jsp:useBean>element.

scope="page|request|session|application"
32

ThescopeinwhichtheBeanexistsandthevariablenamedinidis available.Thedefaultvalueispage.Themeaningsofthedifferent scopesareshownbelow: pageYoucanusetheBeanwithintheJSPpagewiththe <jsp:useBean>elementoranyofthepage'sstaticincludefiles, untilthepagesendsaresponsebacktotheclientorforwardsa requesttoanotherfile. o requestYoucanusetheBeanfromanyJSPpageprocessing thesamerequest,untilaJSPpagesendsaresponsetotheclient orforwardstherequesttoanotherfile.Youcanusetherequest objecttoaccesstheBean,forexample, request.getAttribute(beanInstanceName). o session YoucanusetheBeanfromanyJSPpageinthesame sessionastheJSPpagethatcreatedtheBean.TheBeanexists acrosstheentiresession,andanypagethatparticipatesinthe sessioncanuseit.ThepageinwhichyoucreatetheBeanmust havea<%@page%>directivewith session=true. o application YoucanusetheBeanfromanyJSPpageinthe sameapplicationastheJSPpagethatcreatedtheBean.The BeanexistsacrossanentireJSPapplication,andanypagein theapplicationcanusetheBean. class="package.class"
o

InstantiatesaBeanfromaclass,usingthenewkeywordandtheclass constructor.Theclassmustnotbeabstractandmusthaveapublic, noargumentconstructor.Thepackageandclassnamearecase sensitive.

type="package.class" IftheBeanalreadyexistsinthescope,givestheBeanadatatype otherthantheclassfromwhichitwasinstantiated.Ifyouusetype withoutclassorbeanName,noBeanisinstantiated.Thepackageand classnamearecasesensitive.

class="package.class"type="package.class" InstantiatesaBeanfromtheclassnamedinclassandassignstheBean thedatatypeyouspecifyin type.Thevalueof typecanbethesameas class,asuperclassof class,oraninterfaceimplementedby class.

33

Theclassyouspecifyin classmustnotbeabstractandmusthavea public,noargumentconstructor.Thepackageandclassnamesyou usewithboth classandtypearecasesensitive.

beanName="{package.class|<%=expression%>}" type="package.class" InstantiatesaBeanfromeitheraclassoraserializedtemplate,using thejava.beans.Beans.instantiatemethod,andgivestheBeanthetype specifiedin type.TheBeans.instantiatemethodcheckswhethera namerepresentsaclassoraserializedtemplate.IftheBeanis serialized,Beans.instantiatereadstheserializedform(withaname likepackage.class.ser)usingaclassloader.Formoreinformation,see theJavaBeansAPISpecification. Thevalueof beanNameiseitherapackageandclassnameoran Expression thatevaluatestoapackageandclassname,andispassed toBeans.instantiate.Thevalueof typecanbethesameasbeanName, asuperclassof beanName,oraninterfaceimplementedby beanName. Thepackageandclassnamesyouusewithboth beanNameandtype arecasesensitive

Program: ThestandardwayofhandlingformsinJSPistodefinea"bean".Youjust needtodefineaclassthathasafieldcorrespondingtoeachfieldinthe form. Theclassfieldsmusthave"setters"thatmatchthenamesoftheform fields. getname.html <HTML> <BODY> <FORMMETHOD=POSTACTION="SaveName.jsp"> What'syourname?<INPUTTYPE=TEXTNAME=username SIZE=20><BR> What'syouremailaddress?<INPUTTYPE=TEXTNAME=email SIZE=20><BR> What'syourage?<INPUTTYPE=TEXTNAME=ageSIZE=4> <P><INPUTTYPE=SUBMIT> </FORM> </BODY>
34

</HTML> Tocollectthisdata,wedefineaJavaclasswithfields"username", "email"and"age"andweprovidesettermethods"setUsername", "setEmail"and"setAge",asshown. A"setter"methodisjustamethod thatstartswith "set"followedbythenameofthefield. Thefirstcharacter ofthefieldnameisuppercased. Soifthefieldis"email",its"setter" methodwillbe"setEmail". Gettermethodsaredefinedsimilarly,with "get"insteadof"set".

UserData.java

packageuser publicclassUserData{ Stringusername Stringemail intage publicvoidsetUsername(Stringvalue) { username=value } publicvoidsetEmail(Stringvalue) { email=value } publicvoidsetAge(intvalue) { age=value } publicStringgetUsername(){returnusername}
35

publicStringgetEmail(){returnemail} publicintgetAge(){returnage} }

Themethodnamesmustbeexactlyasshown. Onceyouhavedefinedthe class,compileitandmakesureitisavailableinthewebserver'sclasspath.

Nowletuschange"SaveName.jsp"touseabeantocollectthedata. savename.jsp <jsp:useBeanid="user"class="user.UserData"scope="session"/> <jsp:setPropertyname="user"property="*"/> <HTML> <BODY> <AHREF="NextPage.jsp">Continue</A> </BODY> </HTML> Allweneedtodonowistoaddthejsp:useBean tagandthe jsp:setPropertytag! TheuseBeantagwilllookforaninstanceofthe "user.UserData"inthesession. Iftheinstanceisalreadythere,itwill updatetheoldinstance. Otherwise,itwillcreateanewinstanceof user.UserDataandputitinthesession. ThesetPropertytagwillautomaticallycollecttheinputdata,matchnames againstthebeanmethodnames,andplacethedatainthebean!

36

LetusmodifyNextPage.jsptoretrievethedatafrombean.. nextpage.jsp <jsp:useBeanid="user"class="user.UserData"scope="session"/> <HTML> <BODY> Youentered<BR> Name:<%=user.getUsername()%><BR> Email:<%=user.getEmail()%><BR> Age:<%=user.getAge()%><BR> </BODY> </HTML> StepForTheExecution: 1) Removealltheerrorsinprogram 2) StartYourWebServer 3) Deployment 4) OpenYourWebBrowserandTypeasFollowing http://localhost:8080/usebean2/getname.html Output:

37

Conclusion: Hencewestudiedhowtouse<jsp:useBean>taginjsp.

38

6.Programforsessionmanagement

Aim:ProgramtoCreateSessionManagementinjsp.

Theory: SessionManagementinJSP InJava,theSession objectisaninstanceofjavax.servlet.http.HttpSession. TheSessionobjectprovidesastatefulcontextacrossmultiplepagerequests fromthesameclientduringaconversationwiththeserver.Inotherwords, onceauserhasconnectedtotheWebsite,theSession objectwillbe availabletoalloftheservletsandJSPsthattheuseraccessesuntilthe sessionisclosedduetotimeoutorerror.YoucanaccesstheHttpSession objectforaservletusingthefollowingcode: Listing1.AccessingtheHttpSession //InsidedoGet()ordoPost() HttpSessionsession=req.getSession() InJSP,Session objectsareusedjustastheyareinservlets,exceptthatyou donotneedtheinitializationcode.Forexample,tostoreattributesina Session object,youwouldusecodelikethis: Listing2.UsingthesessionvariableinJSP <%session.setAttribute("number",newFloat(42.5))%> Thiscreatesakeyinthesessionvariablenamednumber,andassignstoita valueof"42.5."Toretrieveinformationfromasession,wesimplyusethe getAttributefunction,likethis: Listing3.Retrievinginformationfromasession <td>Number:<%= session.getAttribute("number")%></td>

39

Attributes ThemostcommonlyusedfeatureoftheSession objectistheattribute storage.attributesareattachedtoseveralsupportobjectsandarethemeans forstoringWebstateinaparticularscope.Sessionattributesarecommonly usedtostoreuservalues(suchasnameandauthentication)andother informationthatneedstobesharedbetweenpages.Forexample,youcould easilystoreanecommerceshoppingcartJavaBeaninasessionattribute. Whentheuserselectsthefirstproduct,anewshoppingcartbeanwouldbe createdandstoredintheSession object.Anyshoppingpagewouldhave accesstothecart,regardlessofhowtheusernavigatesbetweenpages. Session managementcanbeachievedbyusingthefollowingthing. 1.Cookies:cookiesaresmallbitsoftextualinformationthatawebserver sendstoabrowserandthatbrowsersreturnsthecookiewhenitvisitsthe samesiteagain.Incookietheinformationisstoredintheformofaname, valuepair.Bydefaultthecookieisgenerated.Iftheuserdoesn'twantto usecookiesthenitcandisablethem. 2.URLrewriting:InURLrewritingweappendsomeextrainformation ontheendofeachURLthatidentifiesthesession.ThisURLrewritingcan beusedwhereacookieisdisabled.ItisagoodpracticetouseURL rewriting.InthissessionIDinformationisembeddedintheURL,whichis recievedbytheapplicationthroughHttpGETrequestswhentheclient clicksonthelinksembeddedwithapage. 3.Hiddenformfields:Inhiddenformfieldsthehtmlentrywillbelike this:<inputtype="hidden"name="name"value="">.Thismeansthat whenyousubmittheform,thespecifiednameandvaluewillbeget includedingetorpostmethod.InthissessionIDinformationwouldbe embeddedwithintheformasahiddenfieldandsubmittedwiththeHttp POSTcommand. InJSPwehavebeenprovidedaimplicitobjectsessionsowedon'tneedto createaobjectofsessionexplicitlyaswedoinServlets.InJspthesession isbydefaulttrue.Thesessionisdefinedinsidethedirective<%@page session="true/false"%>.Ifwedon'tdeclareitinsidethejsppagethen sessionwill beavailabletothepage,asitisdefaultbytrue. Inthiswillcreateansessionthattakestheusernamefromtheuserand thensavesintotheusersession.Wewilldisplaythesaveddatatotheuser inanotherpage.

40

savenameform.jsp <%@pagelanguage="java" contentType="text/htmlcharset=ISO88591" pageEncoding="ISO88591"%> <!DOCTYPEhtmlPUBLIC"//W3C//DTDHTML4.01Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <metahttpequiv="ContentType" content="text/htmlcharset=ISO8859 1"> <title>nameinputfrom</title> </head> <body> <formmethod="post" action="savenametosession.jsp"> <p><b>EnterYourName:</b><inputtype="text"name="username"><br> <inputtype="submit"value="Submit"> </form> </body> </html>

Theaboveform promptstheusertoenterhis/hername.Oncetheuserclicks onthesubmitbutton,savenametosession.jspiscalled.TheJSP savenametosession.jspretrievestheusernamefromrequestattributesand savesintotheusersessionusingthefunction session.setAttribute("username",username). savenametosession.jsp: <%@pagelanguage="java"%> <% Stringusername=request.getParameter("username") if(username==null)username="" session.setAttribute("username",username) %> <html> <head> <title>NameSaved</title> </head>
41

<body> <p><ahref="showsessionvalue.jsp">NextPagetoviewthesession value</a><p> </body>

TheaboveJSPsavestheusernameintothesessionobjectanddisplaysa linktonextpages(showsessionvalue.jsp).Whenuserclicksonthe"Next Pagetoviewsessionvalue"link,theJSPpageshowsessionvalue.jsp displaystheusernametotheuser. showsessionvalue.jsp:

<%@pagelanguage="java"%> <% Stringusername=(String)session.getAttribute("username") if(username==null)username="" %> <html> <head> <title>ShowSavedName</title> </head> <body> <p>Welcome: <%=username%><p> </body>

StepForTheExecution:

1) Removealltheerrorsinprogram 2) StartYourWebServer 3) Deployment 4) OpenYourWebBrowserandTypeasFollowing http://localhost:8080/sessionmg1/savenameform.jsp

42

Output:

43

Conclusion: Hencewestudiedhowtocreateandmanagethesessioninjsp.

44

7.ProgramFor CustomJSPTag
Aim:ProgramToCreateCustomJSPTag.

Theory:
JSP Custom Tags

JSPcustomtagsaremerelyJavaclassesthatimplementspecialinterfaces. Oncetheyaredevelopedanddeployed,theiractionscanbecalledfromyour HTMLusingXMLsyntax.Theyhaveastarttagandanendtag.Theymay ormaynothaveabody.Abodylesstagcanbeexpressedas: <tagLibrary:tagName/> And,atagwithabodycanbeexpressedas: <tagLibrary:tagName> body </tagLibrary:tagName> Again,bothtypesmayhaveattributesthatservetocustomizethebehavior ofatag.Thefollowingtaghasanattributecalledname,whichacceptsa Stringvalueobtainedby evaluatingthevariableyourName: <mylib:helloname="<%=yourName%>"/> Or,itcanbewrittenasatagwithabodyas: <mylib:hello> <%=yourName%> </mylib:hello> BenefitsofCustomTags AveryimportantthingtonoteaboutJSPcustomtagsisthattheydonot offermorefunctionalitythanscriptlets,theysimplyprovidebetter packaging,byhelpingyouimprovetheseparationofbusinesslogicand presentationlogic.Someofthebenefitsofcustomtagsare:
45

TheycanreduceoreliminatescriptletsinyourJSPapplications.Any necessaryparameterstothetagcanbepassedasattributesorbody content,andthereforenoJavacodeisneededtoinitializeorset componentproperties. Theyhavesimplersyntax.ScriptletsarewritteninJava,butcustom tagscanbeusedinanHTMLlikesyntax. Theycanimprovetheproductivityofnonprogrammercontent developers,byallowingthemtoperformtasksthatcannotbedonewith HTML. Theyarereusable.Theysavedevelopmentandtestingtime.Scritplets arenotreusable,unlessyoucallcutandpastereuse. Inshort,youcanusecustomtagstoaccomplishcomplextasksthesameway youuseHTMLtocreateapresentation.
DefiningaTag

AtagisaJavaclassthatimplementsaspecializedinterface.Itisusedto encapsulatethefunctionalityfromaJSPpage.Todefineasimplebodyless tag,yourclassmustimplementtheTaginterface.Developingtagswitha bodyisdiscussedlater.Sample1showsthesourcecodefortheTag interfacethatyoumustimplement: Sample1:Tag.java publicinterfaceTag{ publicfinalstaticintSKIP_BODY=0 publicfinalstaticintEVAL_BODY_INCLUDE=1 publicfinalstaticintSKIP_PAGE=5 publicfinalstaticintEVAL_PAGE=6 voidsetPageContext(PageContextpageContext) voidsetParent(Tagparent) TaggetParent() intdoStartTag()throwsJspException intdoEndTag()throwsJspException voidrelease() } AlltagsmustimplementtheTaginterface(oroneofitssubinterfaces)asit definesallthemethodstheJSPruntimeenginecallstoexecuteatag.

46

MyFirstTag

Now,let'slookatasampletagthatwheninvokedprintsamessagetothe client. Thereareafewstepsinvolvedindevelopingacustomtag.Thesestepscan besummarizedasfollows: 1. 2. 3. Developthetaghandler Createataglibrarydescriptor Testthetag

1.DeveloptheTagHandler

A taghandlerisanobjectinvokedbytheJSPruntimetoevaluateacustom tagduringtheexecutionofaJSPpagethatreferencesthetag.Themethods ofthetaghandlerarecalledbytheimplementationclassatvariouspoints duringtheevaluationofthetag.Everytaghandlermustimplementa specializedinterface.Inthisexample,thesimpletagimplementstheTag interfaceasshowninSample2. Sample2: HelloTag.java packagetags importjava.io.* importjavax.servlet.jsp.* importjavax.servlet.jsp.tagext.* publicclassHelloTagimplementsTag{ privatePageContextpageContext privateTagparent publicHelloTag(){ super() } publicintdoStartTag()throwsJspException{ try{ pageContext.getOut().print( "Thisismyfirsttag!") }catch(IOExceptionioe){
47

thrownewJspException("Error: IOExceptionwhilewritingtoclient" +ioe.getMessage()) } returnSKIP_BODY } publicintdoEndTag()throwsJspException{ returnSKIP_PAGE } publicvoidrelease(){ } publicvoidsetPageContext(PageContext pageContext){ this.pageContext=pageContext } publicvoidsetParent(Tagparent){ this.parent=parent } publicTaggetParent(){ returnparent } } ThetwoimportantmethodstonoteinHelloTag aredoStartTag and doEndTag.ThedoStartTagmethodisinvokedwhenthestarttagis encountered.Inthisexample,thismethodreturnsSKIP_BODYbecausea simpletaghasnobody.ThedoEndTagmethodisinvokedwhentheendtag isencountered.Inthisexample,thismethodreturnsSKIP_PAGEbecause wedonotwanttoevaluatetherestofthepageotherwiseitshouldreturn EVAL_PAGE TocompiletheHelloTag class,assumingthatTomcatisinstalledat: c:\tomcat: Createanewsubdirectorycalledtags,whichisthenameofthe packagecontainingtheHelloTag class.Thisshouldbecreatedat: c:\tomcat\webapps\examples\webinf\classes. SaveHelloTag.javainthetagssubdirectory. Compilewiththecommand:
48

c:\tomcat\webapps\examples\webinf\classes\tags> javacclasspathc:\tomcat\lib\servlet.jar HelloTag.java 2.CreateaTagLibraryDescriptor ThenextstepistospecifyhowthetagwillbeusedbytheJSPruntimethat executesit.ThiscanbedonebycreatingaTagLibraryDescriptor(TLD), whichisanXMLdocument.Sample3showsasampleTLD: Sample3:mytaglib.tld <?xmlversion="1.0"encoding="ISO88591"?> <!DOCTYPEtaglib PUBLIC"//SunMicrosystems,Inc.// DTDJSPTagLibrary1.1//EN" "http://java.sun.com/j2ee/dtds/ webjsptaglibrary_1_1.dtd"> <!ataglibrarydescriptor> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>first</shortname> <uri></uri> <info>Asimpletablibraryforthe examples</info> <tag> <name>hello</name> <tagclass>tags.HelloTag</tagclass> <bodycontent>empty</bodycontent> <info>SayHi</info> </tag> </taglib> FirstwespecifythetaglibraryversionandJSPversion.The<shortname> tagspecifieshowwearegoingtoreferencethetaglibraryfromtheJSP page.The<uri>tagcanbeusedasauniqueidentifierforyourtaglibrary. Savemytaglib.tldinthedirectory:c:\tomcat\webapps\examples\web inf\jsp.
49

4. TesttheTag Thefinalstepistotestthetagwehavedeveloped.Inordertousethetag,we havetoreferenceit,andthiscanbedoneinthreeways: 1. Referencethetaglibrarydescriptorofanunpackedtaglibrary.For example: 2. <@tagliburi="/WEBINF/jsp/mytaglib.tld" 3. prefix="first"%> 4. ReferenceaJARfilecontainingataglibrary.Forexample: 5. <@tagliburi="/WEBINF/myJARfile.jar" 6. prefix='first"%> 7. Defineareferencetothetaglibrarydescriptorfromtheweb applicationdescriptor(web.xml)anddefineashortnametoreferencethe taglibraryfromtheJSP.Todothis,openthefile: c:\tomcat\webapps\examples\webinf\web.xmlandaddthefollowing linesbeforetheendline,whichis<webapp>: 3.TesttheTag

Thefinalstepistotestthetagwehavedeveloped.Inordertousethetag,we havetoreferenceit,andthiscanbedoneinthreeways: 1. Referencethetaglibrarydescriptorofanunpackedtaglibrary.For example: 2. <@tagliburi="/WEBINF/jsp/mytaglib.tld" 3. prefix="first"%> 4. ReferenceaJARfilecontainingataglibrary.Forexample: 5. <@tagliburi="/WEBINF/myJARfile.jar" 6. prefix='first"%> 7. Defineareferencetothetaglibrarydescriptorfromtheweb applicationdescriptor(web.xml)anddefineashortnametoreferencethe taglibraryfromtheJSP.Todothis,openthefile: c:\tomcat\webapps\examples\webinf\web.xmlandaddthefollowing linesbeforetheendline,whichis<webapp>:\

50

<taglib> <tagliburi>mytags</tagliburi> <tagliblocation>/WEBINF/jsp/ mytaglib.tld</tagliblocation> </taglib Now,writeaJSPandusethefirstsyntax.Sample4showsanexample: Sample4: Hello.jsp <%@tagliburi="/WEBINF/jsp/mytaglib.tld" prefix="first"%> <HTML> <HEAD> <TITLE>HelloTag</TITLE> </HEAD> <BODYbgcolor="#ffffcc"> <B>Myfirsttagprints</B>: <first:hello/> </BODY> </HTML>

ThetaglibisusedtotelltheJSPruntimewheretofindthedescriptorforour taglibrary,andtheprefix specifieshowwewillrefertotagsinthislibrary. Withthisinplace,theJSPruntimewillrecognizeanyusageofourtag throughouttheJSP,aslongasweprecedeourtagnamewiththeprefixfirst asin <first:hello/>. Alternatively,youcanusethesecondreferenceoptionbycreatingaJAR file.Or,youcanusethethirdreferenceoptionsimplybyreplacingthefirst lineinSample4withthefollowingline: <%@tagliburi="mytags"prefix="first"%> Basically,wehaveusedthemytagsname,whichwasaddedtoweb.xml,to referencethetaglibrary.Fortherestoftheexamplesinthisarticle,this referencewillbeused.
51

Now,ifyourequestHello.jspfromabrowser,youwouldseesomething similartoFigurebelow.

Output:

Conclusion: Thus,westudiedhowtocreatecustomtaginjsp

52

8. BasicHibernateProgram.

Aim: Programtocreatesimplehibernate Theory: Hibernateisanobjectrelationalmapping(ORM)libraryfortheJava language,providingaframeworkformappinganobjectorienteddomain modeltoatraditionalrelationaldatabase.Hibernatesolvesobjectrelational impedancemismatchproblemsbyreplacingdirectpersistencerelated databaseaccesseswithhighlevelobjecthandlingfunctions. HibernateisfreeasopensourcesoftwarethatisdistributedundertheGNU LesserGeneralPublicLicense. Hibernate'sprimaryfeatureismappingfromJavaclassestodatabasetables (andfromJavadatatypestoSQLdatatypes).Hibernatealsoprovidesdata queryandretrievalfacilities.HibernategeneratestheSQLcallsandrelieves thedeveloperfrommanualresultsethandlingandobjectconversion, keepingtheapplicationportabletoallsupportedSQLdatabases,with databaseportabilitydeliveredatverylittleperformanceoverhead Hibernateapplicationsdefinepersistentclassesthatare"mapped"to databasetables.Our"HelloWorld"exampleconsistsofoneclassandone mappingfile.Let'sseewhatasimplepersistentclasslookslike,howthe mappingisspecified,andsomeofthethingswecandowithinstancesofthe persistentclassusingHibernate. Theobjectiveofoursampleapplicationistostoremessagesinadatabase andtoretrievethemfordisplay.Theapplicationhasasimplepersistent class,Message,whichrepresents

53

Listing1.Message.java:Asimplepersistentclass packagehello publicclassMessage{ privateLongid privateStringtext privateMessagenextMessage privateMessage(){} publicMessage(Stringtext){ this.text=text } publicLonggetId(){ returnid } privatevoidsetId(Longid){ this.id=id } publicStringgetText(){ returntext } publicvoidsetText(Stringtext){ this.text=text } publicMessagegetNextMessage(){ returnnextMessage } publicvoidsetNextMessage(MessagenextMessage){ this.nextMessage=nextMessage } }

OurMessageclasshasthreeattributes:theidentifierattribute,thetextofthe message,andareferencetoanotherMessage.Theidentifierattributeallows theapplicationtoaccessthedatabaseidentitytheprimarykeyvalueofa persistentobject.Iftwoinstancesof Messagehavethesameidentifiervalue, theyrepresentthesamerowinthedatabase.We'vechosenLongforthetype ofouridentifierattribute,butthisisn'tarequirement.Hibernateallows virtuallyanythingfortheidentifiertype,asyou'llseelater.


54

YoumayhavenoticedthatallattributesoftheMessageclasshave JavaBeanstylepropertyaccessormethods.Theclassalsohasaconstructor withnoparameters.Thepersistentclassesweuseinourexampleswill almostalwayslooksomethinglikethis. InstancesoftheMessageclassmaybemanaged(madepersistent)by Hibernate,buttheydon'thavetobe.SincetheMessageobjectdoesn't implementanyHibernatespecificclassesorinterfaces,wecanuseitlike anyotherJavaclass: Messagemessage=newMessage("HelloWorld") System.out.println(message.getText()) Thiscodefragmentprints"HelloWorld" totheconsole.Ourpersistentclass canbeusedinanyexecution saveanewMessagetothedatabase: Sessionsession=getSessionFactory().openSession() Transactiontx=session.beginTransaction() Messagemessage=newMessage("HelloWorld") session.save(message) tx.commit() session.close() ThiscodecallstheHibernateSession andTransaction interfaces.Itresultsin theexecutionofsomethingsimilartothefollowingSQL: insertintoMESSAGES(MESSAGE_ID,MESSAGE_TEXT, NEXT_MESSAGE_ID) values(1,'HelloWorld',null) HoldontheMESSAGE_IDcolumnisbeinginitializedtoastrangevalue. idpropertyisidentifierpropertyitholdsagenerateduniquevalue.The valueisassignedtotheMessageinstancebyHibernatewhen save()is called. Forthisexample,weassumethattheMESSAGEStablealreadyexists.Of course,wewantour"HelloWorld"programtoprintthemessagetothe console.Nowthatwehaveamessageinthedatabase,we'rereadyto demonstratethis.Thenextexampleretrievesallmessagesfromthedatabase, inalphabeticalorder,andprintsthem:

55

SessionnewSession=getSessionFactory().openSession() TransactionnewTransaction=newSession.beginTransaction() Listmessages= newSession.find("fromMessageasmorderbym.textasc") System.out.println(messages.size()+"message(s)found:") for(Iteratoriter=messages.iterator()iter.hasNext()){ Messagemessage=(Message)iter.next() System.out.println(message.getText()) } newTransaction.commit() newSession.close()

Theliteralstring"fromMessageasmorderbym.textasc"isaHibernate query,expressedinHibernate'sownobjectorientedHibernateQuery Language(HQL).ThisqueryisinternallytranslatedintothefollowingSQL whenfind()iscalled: selectm.MESSAGE_ID,m.MESSAGE_TEXT,m.NEXT_MESSAGE_ID fromMESSAGESm orderbym.MESSAGE_TEXTasc

HibernateneedsmoreinformationabouthowtheMessageclassshouldbe madepersistent.Thisinformationisusuallyprovidedinan XMLmapping document.Themappingdocumentdefines,amongotherthings,how propertiesoftheMessageclassmaptocolumnsoftheMESSAGEStable. Let'slookatthemappingdocumentinListing2.

56

Listing2.AsimpleHibernateXMLmapping <?xmlversion="1.0"?> <!DOCTYPEhibernatemappingPUBLIC "//Hibernate/HibernateMappingDTD//EN" "http://hibernate.sourceforge.net/hibernatemapping2.0.dtd"> <hibernatemapping> <class name="hello.Message" table="MESSAGES"> <id name="id" column="MESSAGE_ID"> <generatorclass="increment"/> </id> <property name="text" column="MESSAGE_TEXT"/> <manytoone name="nextMessage" cascade="all" column="NEXT_MESSAGE_ID"/> </class> </hibernatemapping> ThemappingdocumenttellsHibernatethattheMessageclassistobe persistedtotheMESSAGEStable,thattheidentifierpropertymapstoa columnnamedMESSAGE_ID,thatthetextpropertymapstoacolumn namedMESSAGE_TEXT,andthatthepropertynamednextMessageisan associationwith manytoonemultiplicitythatmapstoacolumnnamed NEXT_MESSAGE_ID. 1 2 3

57

Output:

Conclusion: Thus,westudiedhowtocreatesimplehibernateapplication.

58

9. DatabaseOperationUsingHibernate

Aim: ProgramtoperformdifferentdatabaseoperationusingHQL. Theory: Hibernate provides a powerful query language Hibernate Query Language thatisexpressedinafamiliarSQLlikesyntaxandincludesfullsupportfor polymorphicqueries.HibernatealsosupportsnativeSQLstatements.Italso selects an effective way to perform a database manipulation task for an application. Step1:Createhibernatenativesqlforinsertingdataintodatabase. HibernateNativeusesonlytheHibernateCoreforallitsfunctions.The codeforaclassthatwillbesavedtothedatabaseisdisplayedbelow: packagehibernateexample importjavax.transaction.* importorg.hibernate.Transaction importorg.hibernate.* importorg.hibernate.criterion.* importorg.hibernate.cfg.* importjava.util.*

publicclassHibernateNativeInsert{ publicstaticvoidmain(String args[]){ Session sess= null try{ sess=HibernateUtil.currentSession() Transaction tx =sess.beginTransaction() Studentdetail student=new Studentdetail() student.setStudentName("AmardeepPatel") student.setStudentAddress("rohini,sec2,delhi85")
59

student.setEmail("amar@rediffmail.com") sess.save(student) System.out.println("Successfully datainsertin database") tx.commit() } catch(Exception e){ System.out.println(e.getMessage()) } finally{ sess.close() } } }

Step2:Createsessionfactory'HibernateUtil.java'. codeofsessionFactory: packagehibernateexample importjava.sql.* importorg.hibernate.HibernateException importorg.hibernate.Session importorg.hibernate.SessionFactory importorg.hibernate.cfg.Configuration importjava.io.* publicclassHibernateUtil { publicstaticfinalSessionFactory sessionFact static{ try{ //CreatetheSessionFactoryfromhibernate.cfg.xml sessionFact=new Configuration().configure().buildSessionFactory() } catch(Throwablee){ System.out.println("SessionFactory creationfailed." +e) thrownewExceptionInInitializerError(e) } } publicstaticfinalThreadLocal session =newThreadLocal()
60

publicstaticSession currentSession()throwsHibernateException { Session sess= (Session)session.get() //Open anewSession,if thisthreadhasnoneyet if(sess== null){ sess= sessionFact.openSession() //Storeitin theThreadLocalvariable session.set(sess) } return sess } publicstaticvoidSessionClose()throwsException { Session s=(Session)session.get() if(s!=null) s.close() session.set(null) } }

Step3:HibernatenativeusesthePlainOldJavaObjects(POJOs)classesto maptothedatabasetable.Wecanconfigurethevariablestomaptothe databasecolumn "Studenetdetail.java":

packagehibernateexample publicclassStudentdetail { privateString studentName privateString studentAddress privateString email privateintid publicStringgetStudentName(){ return studentName } publicvoidsetStudentName(String studentName){ this.studentName=studentName
61

} publicStringgetStudentAddress(){ return studentAddress } publicvoidsetStudentAddress(String studentAddress){ this.studentAddress=studentAddress } publicStringgetEmail(){ return email } publicvoidsetEmail(Stringemail){ this.email =email } publicintgetId(){ returnid } publicvoidsetId(intid){ this.id=id } }

62

Output:

2) DeleteRecordFromDatabase Todeletetherecordfromthedatabasewritethequery deletefromProductwherename=:name 3)Update Record From Database Toupdatetherecordfromthedatabasewritethequery update"nameoftable" set"columnname"="newvalue"wherecolumnname=""

Conclusion: Thus,westudiedhowtoperformdifferentdatabaseoperation usinghibernate

63

10. WebServices

Aim: Programtocreatesimplewebservice. Theory: WebServices: Webservicesconstituteadistributedcomputerarchitecture madeupofmanydifferentcomputerstryingtocommunicateoverthe networktoformonesystem.Theyconsistofasetofstandardsthatallow developerstoimplementdistributedapplicationsusingradicallydifferent toolsprovidedbymanydifferentvendorstocreateapplicationsthatusea combinationof softwaremodulescalledfromsystemsindisparate departmentsorfromothercompanies. AWebservicecontainssomenumberofclasses,interfaces,enumerations andstructuresthatprovideblackboxfunctionalitytoremoteclients.Web servicestypicallydefinebusinessobjectsthatexecuteaunitofwork(e.g., performacalculation,readadatasource,etc.)fortheconsumerandwait forthenextrequest.Webserviceconsumerdoesnotnecessarilyneedto beabrowserbasedclient.ConsolebaedandWindowsFormsbased clientscanconsumeaWebservice.Ineachcase,theclientindirectly interactswiththeWebservicethroughaninterveningproxy.Theproxy looksandfeelsliketherealremotetypeandexposesthesamesetof methods.Underthehood,theproxycodereallyforwardstherequesttothe WebserviceusingstandardHTTPoroptionallySOAPmessages. AWebServiceExample:HelloServiceBean Thisexampledemonstratesasimplewebservicethatgeneratesaresponse basedoninformationreceivedfromtheclient.HelloServiceBeanisa statelesssessionbeanthatimplementsasinglemethod,sayHello.This methodmatchesthesayHellomethodinvokedbytheclientsdescribedin StaticStubClient.

64

WebServiceEndpointInterface HelloService isthebean'swebserviceendpointinterface.Itprovidesthe client'sviewofthewebservice,hidingthestatelesssessionbeanfromthe client.AwebserviceendpointinterfacemustconformtotherulesofaJAX RPCservicedefinitioninterface. HelloServiceinterface: packagehelloservice importjava.rmi.RemoteException importjava.rmi.Remote publicinterfaceHelloServiceextendsRemote{ publicStringsayHello(Stringname)throwsRemoteException }

StatelessSessionBeanImplementationClass TheHelloServiceBean classimplementsthesayHellomethoddefinedbythe HelloServiceinterface.Theinterfacedecouplestheimplementationclass fromthetypeofclientaccess.Forexample,ifyouaddedremoteandhome interfacestoHelloServiceBean,themethodsoftheHelloServiceBean class couldalsobeaccessedbyremoteclients.Nochangestothe HelloServiceBean classwouldbenecessary.Thesourcecodeforthe HelloServiceBean classfollows: packagehelloservice importjava.rmi.RemoteException importjavax.ejb.SessionBean importjavax.ejb.SessionContext publicclassHelloServiceBeanimplementsSessionBean{ publicStringsayHello(Stringname){ return"Hello"+name+"fromHelloServiceBean" } publicHelloServiceBean(){} publicvoidejbCreate(){}
65

publicvoidejbRemove(){} publicvoidejbActivate(){} publicvoidejbPassivate(){} publicvoidsetSessionContext(SessionContextsc){} }

BuildingHelloServiceBean

Inaterminalwindow,gotothe <INSTALL>/j2eetutorial14/examples/ejb/helloservice/directory.Tobuild HelloServiceBean,typethefollowingcommand: asantbuildservice Thiscommandperformsthefollowingtasks:


Compilesthebean'ssourcecodefiles CreatestheMyHelloService.wsdlfilebyrunningthefollowing wscompilecommand: wscompiledefinedbuild/outputndbuildclasspathbuildmapping build/mapping.xmlconfiginterface.xml

ThewscompiletoolwritestheMyHelloService.wsdlfiletothe <INSTALL>/j2eetutorial14/examples/ejb/helloservice/build/subdirectory. Formoreinformationaboutthewscompiletool,seeChapter8. Usedeploytool topackageanddeploythisexample

CreatingtheApplication Inthissection,you'llcreateaJ2EEapplicationnamedHelloService,storing itinthefileHelloService.ear. 1. In deploytool,selectFile New Application. 2. ClickBrowse.


66

3. Inthefilechooser,navigateto <INSTALL>/j2eetutorial14/examples/ejb/helloservice/. 4. IntheFileNamefield,enterHelloServiceApp. 5. ClickNewApplication. 6. ClickOK. 7. VerifythattheHelloServiceApp.earfileresidesin <INSTALL>/j2eetutorial14/examples/ejb/helloservice

PackagingtheEnterpriseBean StarttheEditEnterpriseBeanwizardbyselectingFile New Enterprise Bean.Thewizarddisplaysthefollowingdialogboxes. 1. Introductiondialogbox a. Readtheexplanatorytextforanoverviewofthewizard's features. b. ClickNext. 2. EJBJARdialogbox a. SelectthebuttonlabeledCreateNewJARModulein Application. b. Inthecomboboxbelowthisbutton,selectHelloService. c. IntheJARDisplayNamefield,enterHelloServiceJAR. d. ClickEditContents. e. InthetreeunderAvailableFiles,locatethe <INSTALL>/j2eetutorial14/examples/ejb/helloservice/build/ directory. f. IntheAvailableFilestreeselectthehelloservicedirectoryand mapping.xmlandMyHelloService.wsdl. g. ClickAdd. h. ClickOK. i. ClickNext. 3. Generaldialogbox a. IntheEnterpriseBeanClasscombobox,select helloservice.HelloServiceBean. b. UnderEnterpriseBeanType,selectStatelessSession. c. IntheEnterpriseBeanNamefield,enterHelloServiceBean. d. ClickNext. 4. IntheConfigurationOptionsdialogbox,clickNext.Thewizardwill automaticallyselecttheYesbuttonforExposeBeanasWebService Endpoint. 5. IntheChooseServicedialogbox:
67

a. SelectMETAINF/wsdl/MyHelloService.wsdlintheWSDL Filecombobox. b. Selectmapping.xmlfromtheMappingFilecombobox. c. MakesurethatMyHelloServiceisintheServiceNameand ServiceDisplayNameeditboxes. 6. IntheWebServiceEndpointdialogbox: a. Selecthelloservice.HelloIFintheServiceEndpointInterface combobox. b. IntheWSDLPortsection,settheNamespacetourn:Foo,and theLocalParttoHelloIFPort. c. IntheSunspecificSettingssection,settheEndpointAddressto helloejb/hello. d. ClickNext. 7. ClickFinish. 8. SelectFile Save.

DeployingtheEnterpriseApplication NowthattheJ2EEapplicationcontainstheenterprisebean,itisreadyfor deployment. 1. SelecttheHelloServiceapplication. 2. SelectTools Deploy. 3. UnderConnectionSettings,entertheusernameandpasswordforthe ApplicationServer. 4. ClickOK. 5. IntheDistributeModuledialogbox,clickClosewhenthedeployment completes. 6. Verifythedeployment. a. Inthetree,expandtheServersnodeandselectthehostthatis runningtheApplicationServer. b. IntheDeployedObjectstable,makesurethatHelloServiceis listedandthatitsstatusisRunning.

BuildingtheWebServiceClient

ToverifythatHelloServiceBean hasbeendeployed,clickonthetarget ApplicationServerintheServerstreein deploytool.IntheDeployed ObjectstreeyoushouldseeHelloServiceApp.


68

Tobuildthestaticstubclient,performthesesteps: 1. Inaterminalgotothe <INSTALL>/j2eetutorial14/examples/jaxrpc/helloservice/directory andtype asantbuild 2. Inaterminalgotothe <INSTALL>/j2eetutorial14/examples/jaxrpc/staticstub/directory. 3. Open configwsdl.xmlinatexteditorandchangethelinethatreads <wsdllocation="http://localhost:8080/hellojaxrpc/hello?WSDL" to <wsdllocation="http://localhost:8080/helloejb/hello?WSDL" 4. Type asantbuild 5. Editthebuild.propertiesfileandchangetheendpoint.addressproperty to http://localhost:8080/helloejb/hello

RunningtheWebServiceClient Toruntheclient,gotothe <INSTALL>/j2eetutorial14/examples/jaxrpc/staticstub/directoryandenter asantrun Theclientshoulddisplaythefollowingline:

69

Output:

HelloDuke!(fromHelloServiceBean)

Conclusion: Thus,welearnthowtocreatesimplewebservice.

70

71

72

73

Das könnte Ihnen auch gefallen