JAVA编程:JSP 的模板
唉!都是钱闹的1.Swing和.net开发比较------从市场份额看.net开发主要占据大部分的中小型和中型的的桌面开发,原因是它封装了很多工具js|模板ByScottFerguson引论
榜样的框架:Hello,World
Servlet批评
展现留言板
留言板的形式
作为使用属性的留言板
留言板的逻辑
结论
引论
JSP的壮大上风在于把一种使用的商务逻辑和它的先容分别开来。用Smalltalk的面向对象的术语来讲,JSP勉励MVC(model-view-controller)的web使用。JSP的classes或beans是模子,JSP是这个视图,而Servlet是把持器。
这个例子是一个复杂的留言板。用户登录和留言。ItisalsoavailableintheResindemos
RoleImplementation
ModelAGuestBookofGuests.
Viewlogin.jspfornewusers
add.jspforlogged-inusers.
ControllerGuestJsp,aservlettomanagethestate.
榜样的框架:Hello,World
GuestJsp的框架把"Hello,World"这个字符串传给login.jsp页面。这个框架为留言板设立布局。详细细节将鄙人面增补。
这个例子被编译后能够扫瞄到:
http://localhost:8080/servlet/jsp.GuestJsp
你能够看到如许的页面:
Hello,world
JSP模板是以Servlet的处置入手下手然后把处置了局传给JSP页举行格局化。
ForwardingusesaServlet2.1featureoftheServletContext,getRequestDispatcher().Therequestdispatcherletsservletsforwardandincludeanysubrequestsontheserver.ItsamoreflexiblereplacementsforSSIincludes.TheRequestDispatchercanincludetheresultsofanypage,servlet,orJSPpageinaservletspage.GuestJspwillusedispatcher.forward()topasscontroltotheJSPpageforformatting.
GuestJsp.java:Skeletonpackagejsp.GuestJsp;
importjava.io.*;
importjava.util.*;
importjavax.servlet.*;
importjavax.servlet.http.*;
/**
*GuestJspisaservletcontrollinguser
*interactionwiththeguestbook.
*/
publicclassGuestJspextendsHttpServlet{
/**
*doGethandlesGETrequests
*/
publicvoiddoGet(HttpServletRequestreq,
HttpServletResponseres)
throwsServletException,IOException
{
//Savethemessageintherequestforlogin.jsp
req.setAttribute("message","Hello,world");
//gettheapplicationobject
ServletContextapp=getServletContext();
//selectlogin.jspasthetemplate
RequestDispatcherdisp;
disp=app.getRequestDispatcher("login.jsp");
//forwardtherequesttothetemplate
disp.forward(req,res);
}
}
TheservletandthejsppagecommunicatewithattributesintheHttpRequestobject.Theskeletonstores"Hello,World"inthe"message"attribute.Whenlogin.jspstarts,itwillgrabthestringandprintit.
SinceResinsJavaScriptunderstandsextendedBeanpatterns,ittranslatestherequest.getAttribute("message")intotheJavaScriptequivalentrequest.attribute.message.
login.jsp:Skeleton<%@pagelanguage=javascript%>
<head>
<title><%=request.attribute.message%></title>
</head>
<bodybgcolor=white>
<h1><%=request.attribute.message%></h1>
</body>
ServletReview
ForthosecomingtoJSPfromanASPorCGIbackground,ServletsreplaceCGIscriptstakingadvantageofJavasstrengthindynamicclassloading.AservletisjustaJavaclasswhichextendsServletorHttpServletandplacedintheproperdirectory.Resinwillautomaticallyloadtheservletandexecuteit.
doc
index.html
login.jsp
add.jsp
WEB-INF
classes
jsp
GuestJsp.class
GuestBook.class
Guest.class
Theurl/servlet/classnameforwardstherequesttotheServletInvoker.TheInvokerwilldynamicallyloadtheJavaclassclassnamefromdoc/WEB-INF/classesandtrytoexecutetheServletsservicemethod.
Resincheckstheclassfileperiodicallytoseeiftheclasshaschanged.Ifso,itwillreplacetheoldservletwiththenewservlet.
DisplayingtheGuestBook
Thenextstep,aftergettingthebasicframeworkrunning,istocreatethemodel.
TheGuestBookmodel
TheguestbookisstraightforwardsoIvejustincludedtheAPIhere.ItconformstoBeanpatternstosimplifytheJavaScript.ThesameAPIwillworkforHashMap,file-based,anddatabaseimplementations.
JSPfilesonlyhaveaccesstopublicmethods.SoaJSPfilecannotcreateanewGuestBookanditcantaddanewguest.ThatstheresponsibilityoftheGuestJspservlet.
jsp.Guest.javaAPIpackagejsp;
publicclassGuest{
Guest();
publicStringgetName();
publicStringgetComment();
}
ResinsJavaScriptrecognizesBeanpatterns.SoJSPpagesusingJavaScriptcanaccessgetName()andgetComment()asproperties.Forexample,youcansimplyuseguest.nameandguest.comment
jsp.GuestBook.javaAPIpackagejsp;
publicclassGuestBook{
GuestBook();
voidaddGuest(Stringname,Stringcomment);
publicIteratoriterator();
}
ResinsJavaScriptalsorecognizestheiterator()call,soyoucanuseaJavaScriptfor...eachtogettheguests:
for(varguestinguestBook){
...
}
GuestBookasapplicationattribute
Tokeeptheexamplesimple,GuestJspstorestheGuestBookintheapplication(ServletContext).Asanexample,storingdataintheapplicationisacceptablebutforfull-fledgedapplications,itsbetterjusttousetheapplicationtocachedatastoredelsewhere.
jsp.GuestJsp.java//gettheapplicationobject
ServletContextapp=getServletContext();
GuestBookguestBook;
//TheguestBookisstoredintheapplication
synchronized(app){
guestBook=(GuestBook)app.getAttribute("guest_book");
//Ifitdoesntexist,createit.
if(guestBook==null){
guestBook=newGuestBook();
guestBook.addGuest("HarryPotter","Griffindorrules");
guestBook.addGuest("DracoMalfoy","Slytherinrules");
app.setAttribute("guest_book",guestBook);
}
}
RequestDispatcherdisp;
disp=app.getRequestDispatcher("login.jsp");
//synchronizetheApplicationsotheJSPfile
//doesntneedtoworryaboutthreading
synchronized(app){
disp.forward(req,res);
}
TheJSPfileitselfissimple.Itgrabstheguestbookfromtheapplicationanddisplaysthecontentsinatable.Normally,applicationobjectsneedtobesynchronizedbecauseseveralclientsmaysimultaneouslybrowsethesamepage.GuestJsphastakencareofsynchronizationbeforetheJSPfilegetscalled.
login.jsp:DisplayGuestBook<%@pagelanguage=javascript%>
<head>
<title>HogwartsGuestBook</title>
</head>
<bodybgcolor=white>
<h1>HogwartsGuestBook</h1>
<table>
<tr><tdwidth=25%><em>Name</em><td><em>Comment</em>
<%
varguestBook=application.attribute.guest_book
for(varguestinguestBook){
out.writeln("<tr><td>"+guest.name+"<td>"+guest.comment);
}
%>
</table>
</body>
HogwartsGuestBook
NameComment
HarryPotterGriffindorRules
DracoMalfoySlytherinRules
Guestbooklogic
Theguestbooklogicissimple.Iftheuserhasnotloggedin,sheseescommentsandaformtologin.Afterlogin,shellseethecommentsandaformtoaddacomment.login.jspformatstheloginpageandadd.jspformatstheaddcommentpage.
GuestJspstoreslogininformationinthesessionvariable.
FormVariableMeaning
actionlogintologinoraddtoaddacomment
nameusername
passworduserpassword
commentcommentfortheguestbook
Guestbooklogic...
//namefromthesession
StringsessionName=session.getValue("name");
//actionfromtheforms
Stringaction=request.getParameter("action");
//namefromthelogin.jspform
StringuserName=request.getParameter("name");
//passwordfromthelogin.jspform
Stringpassword=request.getParameter("password");
//commentfromtheadd.jspform
Stringcomment=request.getParameter("comment");
//loginstorestheuserinthesession
if(action!=null&&action.equals("login")&&
userName!=null&&
password!=null&&password.equals("quidditch")){
session.putValue("name",userName);
}
//addsanewguest
if(action!=null&&action.equals("add")&&
sessionName!=null&&
comment!=null){
guestBook.addGuest(sessionName,comment);
}
Stringtemplate;
//ifnotloggedin,uselogin.jsp
if(session.getValue("name")==null)
template="login.jsp";
//ifloggedin,useadd.jsp
else
template="add.jsp";
RequestDispatcherdisp;
disp=app.getRequestDispatcher(template);
...
login.jspandadd.jspjustappenddifferentformstothedisplaycodeintheprevioussection.
login.jsp<%@pagelanguage=javascript%>
<head>
<title>HogwartsGuestBook:Login</title>
</head>
<bodybgcolor=white>
<h1>HogwartsGuestBook</h1>
<table>
<tr><tdwidth=25%><em>Name</em><td><em>Comment</em>
<%
varguestBook=application.attribute.guest_book
for(varguestinguestBook){
out.writeln("<tr><td>"+guest.name+"<td>"+guest.comment);
}
%>
</table>
<hr>
<formaction=GuestJspmethod=post>
<inputtype=hiddenname=actionvalue=login>
<table>
<tr><td>Name:<td><inputname=Name>
<tr><td>Password:<td><inputname=Passwordtype=password>
<tr><td><inputtype=submitvalue=Login>
</table>
</form>
</body>
Conclusion
TheResindemoshowsafewwaystoextendtheguestbook,includingaddingsomeintelligencetotheformprocessing.However,asformsgetmoreintelligent,evenJSPtemplatesbecomecomplicated.Thereisasolution:XTPtemplates.
--------------------------------------------------------------------------------
Home|Resin|Download|Sales|FAQ|SiteMap
Copyright?1998-2000CauchoTechnology.Allrightsreserved.
Lastmodified:Sat,11Mar200020:22:52-0800(PST)
自己的整个学习思路完全被老师的讲课思路所牵制,这样几节课听下来,恐怕自己的见解都应该是书里的知识点了,根本谈不上自身发现问题,分析问题,和解决问题能力的切实提高。 Pet Store.(宠物店)是SUN公司为了演示其J2EE编程规范而推出的开放源码的程序,应该很具有权威性,想学J2EE和EJB的朋友不要 错过了。 是一种使网页(Web Page)产生生动活泼画面的语言 你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。 你可以去承接一些项目做了,一开始可能有些困难,可是你有技术积累,又考虑周全,接下项目来可以迅速作完,相信大家以后都会来找你的,所以Money就哗啦啦的。。。。。。 自从Sun推出Java以来,就力图使之无所不包,所以Java发展到现在,按应用来分主要分为三大块:J2SE,J2ME和J2EE,这也就是Sun ONE(Open Net Environment)体系。J2SE就是Java2的标准版,主要用于桌面应用软件的编程;J2ME主要应用于嵌入是系统开发,如手机和PDA的编程;J2EE是Java2的企业版,主要用于分布式的网络程序的开发,如电子商务网站和ERP系统。 Pet Store.(宠物店)是SUN公司为了演示其J2EE编程规范而推出的开放源码的程序,应该很具有权威性,想学J2EE和EJB的朋友不要 错过了。 另外编写和运行Java程序需要JDK(包括JRE),在sun的官方网站上有下载,thinking in java第三版用的JDK版本是1.4,现在流行的版本1.5(sun称作J2SE 5.0,汗),不过听说Bruce的TIJ第四版国外已经出来了,是专门为J2SE 5.0而写的。
页:
[1]