仓酷云
标题:
JAVA网站制作之JSP - FAQ (2)
[打印本页]
作者:
老尸
时间:
2015-1-18 11:22
标题:
JAVA网站制作之JSP - FAQ (2)
先说优点,首先和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
一旦你有了思想,那你编的程序就有了灵魂,不管是什么语言到了你的手里都会是你的工具而已,他们的价值是能尽快帮助你实现你想要的目标。但是如果你没有了思想,那就像是海里的帆船失去了船帆,是很难到打海的另一边的。
作者:
不帅
时间:
2015-1-20 22:06
Jive的资料在很多网站上都有,大家可以找来研究一下。相信你读完代码后,会有脱胎换骨的感觉。遗憾的是Jive从2.5以后就不再无条件的开放源代码,同时有licence限制。不过幸好还有中国一流的Java程序员关注它,外国人不开源了,中国人就不能开源吗?这里向大家推荐一个汉化的Jive版本—J道。Jive(J道版)是由中国Java界大名 鼎鼎的banq在Jive 2.1版本基础上改编而成, 全中文,增加了一些实用功能,如贴图,用户头像和用户资料查询等,而且有一个开发团队在不断升级。你可以访问banq的网站
作者:
小女巫
时间:
2015-1-30 06:39
应用在电视机、电话、闹钟、烤面包机等家用电器的控制和通信。由于这些智能化家电的市场需求没有预期的高,Sun公司放弃了该项计划。随着1990年代互联网的发展
作者:
爱飞
时间:
2015-1-31 19:05
你就该学一学Servlet了。Servlet就是服务器端小程序,他负责生成发送给客户端的HTML文件。JSP在执行时,也是先转换成Servlet再运行的。虽说JSP理论上可以完全取代Servlet,这也是SUN推出JSP的本意,可是Servlet用来控制流程跳转还是挺方便的,也令程序更清晰。接下来你应该学习一下Javabean了,可能你早就看不管JSP在HTML中嵌Java代码的混乱方式了,这种方式跟ASP又有什么区别呢?
作者:
冷月葬花魂
时间:
2015-2-2 19:24
学Java必读的两个开源程序就是Jive和Pet Store.。 Jive是国外一个非常著名的BBS程序,完全开放源码。论坛的设计采用了很多先进的技术,如Cache、用户认证、Filter、XML等,而且论坛完全屏蔽了对数据库的访问,可以很轻易的在不同数据库中移植。论坛还有方便的安装和管理程序,这是我们平时编程时容易忽略的一部份(中国程序员一般只注重编程的技术含量,却完全不考虑用户的感受,这就是我们与国外软件的差距所在)。
作者:
仓酷云
时间:
2015-2-8 04:22
多重继承(以接口取代)等特性,增加了垃圾回收器功能用于回收不再被引用的对象所占据的内存空间,使得程序员不用再为内存管理而担忧。在 Java 1.5 版本中,Java 又引入了泛型编程(Generic Programming)、类型安全的枚举、不定长参数和自动装/拆箱等语言特性。
作者:
第二个灵魂
时间:
2015-2-24 04:17
接着就是EJB了,EJB就是Enterprise JavaBean, 看名字好象它是Javabean,可是它和Javabean还是有区别的。它是一个体系结构,你可以搭建更安全、更稳定的企业应用。它的大量代码已由中间件(也就是我们常听到的 Weblogic,Websphere这些J2EE服务器)完成了,所以我们要做的程序代码量很少,大部分工作都在设计和配置中间件上。
作者:
灵魂腐蚀
时间:
2015-3-7 10:49
Sun公司看见Oak在互联网上应用的前景,于是改造了Oak,于1995年5月以Java的名称正式发布。Java伴随着互联网的迅猛发展而发展,逐渐成为重要的网络编程语言。
作者:
小妖女
时间:
2015-3-7 23:10
[url]http://www.jdon.com/[/url]去下载,或到同济技术论坛的服务器[url]ftp://nro.shtdu.edu.cn[/url]去下,安装上有什么问题,可以到论坛上去提问。
作者:
山那边是海
时间:
2015-3-22 02:07
是一种为 Internet发展的计算机语言
欢迎光临 仓酷云 (http://ckuyun.com/)
Powered by Discuz! X3.2