|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
先说优点,首先和C,C++这些语言比起来,java很简单,去掉指针的java,非常好理解,自动垃圾回收机制也很好,自从JDK1.5推出以后,性能上又有了很大提高。js10)HowdoyouinvokeaJSPpagefromaservlet?TOC
(Contributedby:Thomas-Bernhard.O-Hare@Dresdner-Bank.com)
AfterscanningthrougharchivesoftheJSPmailinglisttonoeffectIfinallyrememberedthatIdpastedthisexampleintoadocumentIwrote.ItwasoriginallysentbySatishDharmarajofSuntoshowthemodel2approach(asdescribedinthe0.92specification):howtopassdatafromaservlet
toaJSP.
Createadirectorycalledmodel1/underthesamples/directory.Placefoo.jspandFoo.javainsidethisdirectory.
CompileFooServlet.javaandplaceFooServlet.classinTOP/servlets/directory.
Theninvokeusinghttp://host:8080/servlet/FooServlet
Inthisexample,FooServletcreatesalistandthenstorestheresultinFoo.class.Foo.Classisthenpassedasadatasourcetofoo.jsp.
Thesourcesare:
1)FooServlet.java
importjava.io.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
importmodel1.Foo;
publicclassFooServletextendsHttpServlet
{
publicvoidservice(HttpServletRequestreq,HttpServletResponseres)
throwsServletException,IOException
{
Strings[]=newString[]{"blue","green","red"};
Foof=newFoo(s);
req.setAttribute("foo",f);
getServletContext().getRequestDispatcher("/samples/model1/foo.jsp").forward
(req,res);
}
}
2)foo.jsp
<html>
<usebeanname=footype=model1.Foolifespan=page>
</usebean>
<ul>
<loopproperty=foo:listpropertyelement=x>
<li><displayproperty=x>
</loop>
</ul>
</html>
3)Foo.java
packagemodel1;
publicclassFoo{
Strings[];
publicString[]getList(){returns;}
publicFoo(Strings[]){this.s=s;}
}
(from"OHare,ThomasBernhard"<Thomas-Bernhard.O-Hare@Dresdner-Bank.com>)
11)Howdoyoupassdata(includingbeans)toaJSPfromaservlet?TOC
Thereareactuallythreedifferentwaystodoit,dependingonhowlongthereferenceshouldlast,andwhichJSPpages(andservlets,forthatmatter)shouldbeabletoseeit.Ineachofthecases,assumethat"myBean"isareferencetothebeanyouwanttosend,andthat"theBean"isthekeyImgoingtousetostorethebeanunder(fromtheservletperspective),anduseastheidentityofthebeanintheJSPpage.
ThesetechniquesareportabletoanyenvironmentcompliantwiththeservletAPI2.1andJSP1.0specifications.Ineachcase,thepassing
worksfromservlet->JSP,servlet->servlet,JSP->JSP,orJSP->servlettransitions.
(1)RequestLifetime
Usethistechniquetopassbeansthatarerelevanttothisparticularrequesttoabeanyouarecallingthrougharequestdispatcher(usingeither"include"or"forward").Thisbeanwilldisappearafterprocessingthisrequesthasbeencompleted.
SERVLET:
request.setAttribute("theBean",myBean);
RequestDispatcherrd=
getServletContext().getRequestDispatcher(/thepage.jsp");
rd.forward(request,response);
JSPPAGE:
<jsp:useBeanid="theBean"scope="request"class="....."/>
(2)SessionLifetime
Usethistechniquetopassbeansthatarerelevanttoaparticularsession(suchasinindividualuserlogin)overanumberofrequests.Thisbeanwilldisappearwhenthesessionisinvalidatedorittimesout,orwhenyouremoveit.
SERVLET:
HttpSessionsession=request.getSession(true);
session.putValue("theBean",myBean);
/*Youcandoarequestdispatcherhere,
orjustletthebeanbevisibleonthe
nextrequest*/
JSPPAGE:
<jsp:useBeanid="theBean"scope="session"class="..."/>
(3)ApplicationLifetime
UsethistechniquetopassbeansthatarerelevanttoallservletsandJSPpagesinaparticularapp,forallusers.Forexample,IusethistomakeaJDBCconnectionpoolobjectavailabletothevariousservletsandJSPpagesinmyapps.Thisbeanwilldisappearwhentheservletengineisshutdown,orwhenyouremoveit.
SERVLET:
getServletContext().setAttribute("theBean",myBean);
JSPPAGE:
<jsp:useBeanid="theBean"scope="application"class="..."/>
CraigMcClanahan
12)HowcanIpoolconnectionstomydatabase?TOC
Controllingconnectionstothedatabaseisadesirablething-havingtoconnecttothedatabaseforeachpageisisexpensive,andkeepingaconnectioninasessionvariableisfartooexpensiveintermsofclientconnectionstothedatabase.Thus,peopleoftencreatepoolsforconnectionstothedatabasethattheclientcomesinandgetsandthenreturnswhencomplete(makingsureatry/catchisusedtoensuretheconnectionisreturned!).
MypersonalbiasindicatesthatyoushouldntpoolconnectionstoyourdatabaseinsideJSP,youshouldbeusingamiddlewarelayerandcommunicatingtoit(likeRMIorCORBA).However,peopledowriteentireapplicationsinJSPandbeansthatresideinthewebserver,sohowdoyoudoit?
From:BradleyWood<Brad@MARKETING.CO.UK>
probablyinstantiatethisasasingletonintheglobal.jsaandthencallit.
formoreonthisandhowitscalledcheckthedownloadablecodeexamplesforthisbookatwww.ora.com
importjava.sql.*;
importjava.util.*;
publicclassConnectionPool{
privateHashtableconnections;
privateintincrement;
privateStringdbURL,user,password;
publicConnectionPool(StringdbURL,
Stringuser,
Stringpassword,
StringdriverClassName,
intinitialConnections,
intincrement)
//intmax?
throwsSQLException,ClassNotFoundException{
//Loadthespecifieddriverclass
Class.forName(driverClassName);
this.dbURL=dbURL;
this.user=user;
this.password=password;
this.increment=increment;
connections=newHashtable();
//PutourpoolofConnectionsintheHashtable
//TheFALSEvalueindicatestheyreunused
for(inti=0;i<initialConnections;i++){
connections.put(DriverManager.getConnection(dbURL,user,password),
Boolean.FALSE);
}
}
publicConnectiongetConnection()throwsSQLException{
Connectioncon=null;
Enumerationcons=connections.keys();
synchronized(connections){
while(cons.hasMoreElements()){
con=(Connection)cons.nextElement();
Booleanb=(Boolean)connections.get(con);
if(b==Boolean.FALSE){
//Sowefoundanunusedconnection.
//TestitsintegritywithaquicksetAutoCommit(true)call.
//Forproductionuse,moretestingshouldbeperformed,
//suchasexecutingasimplequery.
try{
con.setAutoCommit(true);
}
catch(SQLExceptione){
//Problemwiththeconnection,replaceit.
con=DriverManager.getConnection(dbURL,user,password);
}
//UpdatetheHashtabletoshowthisonestaken
connections.put(con,Boolean.TRUE);
//Returntheconnection
returncon;
}//if
}//while
}//synchro
//Ifwegethere,therewerenofreeconnections.
//Wevegottomakemore.
for(inti=0;i<increment;i++){
connections.put(DriverManager.getConnection(dbURL,user,password),
Boolean.FALSE);
}
//Recursetogetoneofthenewconnections.
returngetConnection();
}
publicvoidreturnConnection(Connectionreturned){
Connectioncon;
Enumerationcons=connections.keys();
while(cons.hasMoreElements()){
con=(Connection)cons.nextElement();
if(con==returned){
connections.put(con,Boolean.FALSE);
break;
}
}
}//returnConnection
}//class
From:AndreRichards<AndreRic@mweb.co.za>
AverygoodexampleonconnectionpoolingwhenusingServletscanbefoundat:
http://webdevelopersjournal.com/columns/connection_pool.html
IsuccesfullyuseditinJSP0.91asfollows:
<scriptRUNAT="SERVER">
DBConnectionManagerconnMgr=DBConnectionManager.getInstance();
</script>
<%
Connectioncon=connMgr.getConnection("freetds");
if(con==null){
out.println("Cantgetconnection");
return;
}
try{
Statementstmt=con.createStatement();
ResultSetrs=stmt.executeQuery("SELECTHelloFROMWorld");
while(rs.next()){
out.println(rs.getString("Hello"));
}
stmt.close();
rs.close();}
catch(SQLExceptione){
e.printStackTrace(out)
}
connMgr.freeConnection("freetds",con);
%>
13)HowdoIuseotherlanguagesinmyJSP?TOC
JSPis*Java*ServerPages,andthetagsforotherlanguagesweretakenoutin0.92.Thatsaid,twoimplementations(asofwriting)supportotherlanguages:
-PolyJsp,0.92,http://www.plenix.org/polyjsp,free+opensource
-Resin.AJSP0.92implementationforcompiledJavaScript,http://www.caucho.com/,freeforpersonaluse
14)HowcanIsetacookieinJSP?TOC
Thisshouldwork:
response.setHeader("Set-Cookie","cookiestring");
Togivetheresponse-objecttoabean,writeamethodsetResponse
(HttpServletResponseresponse)
-tothebean,andinjsp-file:
<%
bean.setResponse(response);
%>
(fromAapoKyrl?<aapo.kyrola@SATAMA.COM>)
15)CanJSPandServletsharesameSessionandBeans?TOC
Example:IusedBeansandSessionwithmyservlet,JSPcanusesameBeansandSessionornot?
From:RobertHodges<hodges@TILDENPARK.COM>
Thiscanbedone,butyouarelikelytorunintoproblemswithclassloaders.Forinstance,wehaveApache/JServwhichusestheAdaptiveClassLoaderalongwithGNU-JSPwhichhasadifferentclassloader.IfyoujustcasuallyallocateobjectsinaservletandthenpickthemupinJSPpages,youllmostlikelygetthedreadedClassCastException,whichsignalstheVMspleasurewhenyoutrytocastaclassthatwasbroughtinbyadifferentclassloader.
NotethattherearesometimesproblemsevenwithinJSP,asGNU-JSPdropstheclassloadereverytimeyourecompileapage,soifyouallocatedaclassinstanceusingoneversionofthepage,thenrecompiledandtriedtofishthatinstancebackagain,youwouldeither(1)notfinditor(2)gettheClassCastException(butseepara#1above).
Ifyoureallyneedtopassinformationaround,thebestwayforApacheandGNU-JSPistodothefollowing:
Haveoneserverperpersonwhendeveloping.
MakesurethatallyourJavaclasses,includingservletcode,loadthroughthesystemclasspath.Thismeanstheyloadthroughtheprimordialloader,whichdoesnotgoawayorchange.
MakesurethatyourcompiledJSPpagesgotoanotherlocationthanyourregularJavaclasses.Thatway,theJSPloaderwilljustpickthemupthroughtheprimordialloader.
Inthisscheme,youwillneedtoreboottheWebservereachtimeyoumakeachangetotheregularJavaclassesorelsegreatconfusionwillensue.(Andpossiblyoutrageamongyourusers,Imightadd.)
IfyouneedtoshareaWebServerbetweenmultiplepeople,orcannotrebootwheneveryoumakeclasschanges,thesolutionismuchmorecomplex.Icanpostatreatiseononeapproachatalatertime(bigproject,deadlineFriday)ifthereisinterest.
16)HowdoIplugJSPintoMicrosoftsIISWebServer?TOC
IBMsWebSphere,LiveSoftwaresJRunandNewAtlantasServletExecallprovidepluginsforIIS4.0.
Tomcat,the"reference"implementationofJSP1.1fromtheJakartaProjectalsohasanISAPIplug-in.Tomcatdoesnot(asof3.1)supportmulti-homing.
Resinalsoprovidessupportformulti-homing(verywellatthat!)
17)ArethereanynewsgroupsthatdiscussJSP?TOC
LiveSoftwarehasanewnewsgroupforJSPdiscussionatnews://news.livesoftware.com/livesoftware.jsp
一旦你有了思想,那你编的程序就有了灵魂,不管是什么语言到了你的手里都会是你的工具而已,他们的价值是能尽快帮助你实现你想要的目标。但是如果你没有了思想,那就像是海里的帆船失去了船帆,是很难到打海的另一边的。 |
|