|
马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。
您需要 登录 才可以下载或查看,没有帐号?立即注册
x
唉!都是钱闹的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)
自己的整个学习思路完全被老师的讲课思路所牵制,这样几节课听下来,恐怕自己的见解都应该是书里的知识点了,根本谈不上自身发现问题,分析问题,和解决问题能力的切实提高。 |
|