JSP高级技术怎样研发动态网站
发布时间:2023-06-02 13:24:46 所属栏目:教程 来源:
导读:近年来,jsp技术现在已经成为一种卓越的动态网站开发技术。java开发者出于各种理由喜爱使用jsp。有人喜爱其“一次开发,处处使用”的性能,另外的人觉得jsp使java成为一种易学的服务器端scripting语言。但
近年来,jsp技术现在已经成为一种卓越的动态网站开发技术。java开发者出于各种理由喜爱使用jsp。有人喜爱其“一次开发,处处使用”的性能,另外的人觉得jsp使java成为一种易学的服务器端scripting语言。但是,jsp最大的长处在它将页面的表现和页面的商业逻辑分开了。本章中,我们将深入地讨论如何使用jsp模式2体系结构来开发网站。这一模式可以被看作是通用模式浏览控制模式(popular model-view-controller,mvc)模式的服务器端实现。 servlets有何缺陷? 当jsp成为开发动态网站的主要技术时,可能有人会问为何在jsp技术中我们不强调servlets。servlets的应用是没有问题的。它们非常适于服务器端的处理和编程,并且它们会长期驻留在他们现在的位置。但是,从结构上说,我们可以将jsp看作是servlet的一个高层的抽象实现,特别是在servlet 2.2 api下。但是,你仍然不能无拘束地使用servlet;它们并不适合每一个人。例如,页面设计者可以方便地使用html或者xml工具开发jsp页面,但servlet却更适合于后端开发者使用,他们的工具是ide——一个需要更多编程训练的开发领域。当发布servlet时,每个开发者必须小心地确定在页面表现和页面逻辑之间没有紧密的关联出现。你可以使用第三方html包装工具,如htmlkona来混合html和servlet代码。即使如此,这点灵活性还不足以让你自由地改变风格本身。例如,你希望从html改变到dhtml,则包装本身需要被小心地测试,以确保新的格式可以正确使用。在最坏的情况下,包装不可用,你就需要应变马来表现动态内容。所以,需要一种新的解决方案。你将会看到,一种方案就是混合jsp和servlet的使用。 不同的方式 早期的jsp标准给出了两种使用jsp的方式。这些方式,都可以归纳为jsp模式1和jsp模式2,主要的差别在于处理大量请求的位置不同。在模式1中(图1),jsp页面独自响应请求并将处理结果返回客户。这里仍然有表现和内容的分离,因为所有的数据依靠bean来处理。尽管模式1 可以很好的满足小型应用的需要,但却不能满足大型应用的要求。大量使用模式1,常常会导致页面被嵌入大量的script或者java代码。特别是当需要处理的商业逻辑很复杂时,情况会变得严重。也许对于java程序员来说,这不算大的问题。但如果开发者是前端界面设计人员——在大型项目中,这非常常见,——则代码的开发和维护将出现困难。在任何项目中,这样的模式多少总会导致定义不清的响应和项目管理的困难。 在图2中显示的模式2 结构,是一种面向动态内容的实现,结合了servlet 和jsp技术。它利用了两种技术原有的优点,采用jsp来表现页面,采用servlets来完成大量的处理。这里,servlet扮演一个控制者的角色,并负责响应客户请求。接着,servlet创建jsp需要的bean和对象,再根据用户的行为,决定将那个jsp页面发送给用户。特别要注意,jsp页面中没有任何商业处理逻辑;它只是简单地检索servlet先前创建的bean 或者对象,再将动态内容插入预定义的模版。从开发的观点看,这一模式具有更清晰的页面表现,清楚的开发者角色划分,可以充分地利用开发小组中的界面设计人员。事实上,越是复杂的项目,采用模式2 的好处就越突出。 为了清楚地了解模式2 的开发过程,我们举一个网上音乐商店的例子。 我们创建一个叫”音乐无国界”的销售音乐制品的商店。“音乐无国界”在线商店的主界面,是一个叫“音乐无国界”的页面(代码1)。你会看到,这个页面完全着眼于用户界面,与处理逻辑无关。另外,注意另外一个jsp页面,cart.jsp(在代码2中),用<jsp:include page="cart.jsp" flush="true" />.嵌入eshop.jsp中。 listing 1: eshop.jsp <%@ page session="true" %> <html> <head> <title>music without borders</title> </head> <body bgcolor="#33ccff"> <font face="times new roman,times" size="+3"> music without borders </font> <hr><p> <center> <form name="shoppingform" action="/examples/servlet/shoppingservlet" method="post"> <b>cd:</b> <select name=cd> <option>yuan | the guo brothers | china | $14.95</option> <option>drums of passion | babatunde olatunji | nigeria | $16.95</option> <option>kaira | tounami diabate| mali | $16.95</option> <option>the lion is loose | eliades ochoa | cuba | $13.95</option> <option>dance the devil away | outback | australia | $14.95</option> <option>record of changes | samulnori | korea | $12.95</option> <option>djelika | tounami diabate | mali | $14.95</option> <option>rapture | nusrat fateh ali khan | pakistan | $12.95</option> <option>cesaria evora | cesaria evora | cape verde | $16.95</option> <option>ibuki | kodo | japan | $13.95</option> </select> <b>quantity: </b><input type="text" name="qty" size="3" value=1> <input type="hidden" name="action" value="add"> <input type="submit" name="submit" value="add to cart"> </form> </center> <p> <jsp:include page="cart.jsp" flush="true" /> </body> </html> listing 2: cart.jsp <%@ page session="true" import="java.util.*, shopping.cd" %> <% vector buylist = (vector) session.getvalue("shopping.shoppingcart"); if (buylist != null && (buylist.size() > 0)) { %> <center> <table border="0" cellpadding="0" width="100%" bgcolor="#ffffff"> <tr> <td><b>album</b></td> <td><b>artist</b></td> <td><b>country</b></td> <td><b>price</b></td> <td><b>quantity</b></td> <td></td> </tr> <% for (int index=0; index < buylist.size();index++) { cd anorder = (cd) buylist.elementat(index); %> <tr> <td><b><%= anorder.getalbum() %></b></td> <td><b><%= anorder.getartist() %></b></td> <td><b><%= anorder.getcountry() %></b></td> <td><b><%= anorder.getprice() %></b></td> <td><b><%= anorder.getquantity() %></b></td> <td> <form name="deleteform" action="/examples/servlet/shoppingservlet" method="post"> <input type="submit" value="delete"> <input type="hidden" name= "delindex" value='<%= index %>'> <input type="hidden" name="action" value="delete"> </form> </td> </tr> <% } %> </table> <p> <form name="checkoutform" action="/examples/servlet/shoppingservlet" method="post"> <input type="hidden" name="action" value="checkout"> <input type="submit" name="checkout" value="checkout"> </form> </center> <% } %> 这里,cart.jsp按照mvc的模式1处理基于session的购物车的表现。请看cart.jsp开始处的代码: <% vector buylist = (vector) session.getvalue("shopping.shoppingcart"); if (buylist != null && (buylist.size() > 0)) { %> 本质上,这段代码从session中取出“购物车”。如果“购物车”为空或者没有被创建,它就什么也不显示。所以,在用户第一次访问应用时,其界面如图: 如果“购物车”不为空,用户选择的商品从车中取出,依次显示在页面上: <% for (int index=0; index < buylist.size(); index++) { cd anorder = (cd) buylist.elementat(index); %> 一旦生成一个物品的说明,就使用jsp按照事先设定的模板将其插入静态html页面。下图显示了用户选购一些物品后的界面: 需要注意的一个重要的地方是所有关于eshop.jsp,cart.jsp的处理有一个控制servlet,shoppingservlet.java,代码在源程序3中: listing 3: shoppingservlet.java import java.util.*; import java.io.*; import javax.servlet.*; import javax.servlet.http.*; import shopping.cd; public class shoppingservlet extends httpservlet { public void init(servletconfig conf) throws servletexception { super.init(conf); } public void dopost (httpservletrequest req, httpservletresponse res) throws servletexception, ioexception { httpsession session = req.getsession(false); if (session == null) { res.sendredirect("http://localhost:8080/error.html"); } vector buylist= (vector)session.getvalue("shopping.shoppingcart"); string action = req.getparameter("action"); if (!action.equals("checkout")) { if (action.equals("delete")) { string del = req.getparameter("delindex"); int d = (new integer(del)).intvalue(); buylist.removeelementat(d); } else if (action.equals("add")) { //any previous buys of same cd? boolean match=false; cd acd = getcd(req); if (buylist==null) { //add first cd to the cart buylist = new vector(); //first order buylist.addelement(acd); } else { // not first buy for (int i=0; i< buylist.size(); i++) { cd cd = (cd) buylist.elementat(i); if (cd.getalbum().equals(acd.getalbum())) { cd.setquantity(cd.getquantity()+acd.getquantity()); buylist.setelementat(cd,i); match = true; } //end of if name matches } // end of for if (!match) buylist.addelement(acd); } } session.putvalue("shopping.shoppingcart", buylist); string url="/jsp/shopping/eshop.jsp"; servletcontext sc = getservletcontext(); requestdispatcher rd = sc.getrequestdispatcher(url); rd.forward(req, res); } else if (action.equals("checkout")) { float total =0; for (int i=0; i< buylist.size();i++) { cd anorder = (cd) buylist.elementat(i); float price= anorder.getprice(); int qty = anorder.getquantity(); total += (price * qty); } total += 0.005; string amount = new float(total).tostring(); int n = amount.indexof('.'); amount = amount.substring(0,n+3); req.setattribute("amount",amount); string url="/jsp/shopping/checkout.jsp"; servletcontext sc = getservletcontext(); requestdispatcher rd = sc.getrequestdispatcher(url); rd.forward(req,res); } } private cd getcd(httpservletrequest req) { //imagine if all this was in a scriptlet...ugly, eh? string mycd = req.getparameter("cd"); string qty = req.getparameter("qty"); stringtokenizer t = new stringtokenizer(mycd,"|"); string album= t.nexttoken(); string artist = t.nexttoken(); string country = t.nexttoken(); string price = t.nexttoken(); price = price.replace('$',' ').trim(); cd cd = new cd(); cd.setalbum(album); cd.setartist(artist); cd.setcountry(country); cd.setprice((new float(price)).floatvalue()); cd.setquantity((new integer(qty)).intvalue()); return cd; } } 每次用户用eshop.jsp增加一个商品,页面就请求控制servlet。控制servlet决定进一步的行动,并处理增加的商品。接着,控制servlet实例化一个新的bean cd代表选定的商品,并在返回session前更新购物车对象。 listing 4: cd.java package shopping; public class cd { string album; string artist; string country; float price; int quantity; public cd() { album=""; artist=""; country=""; price=0; quantity=0; } public void setalbum(string title) { album=title; } public string getalbum() { return album; } public void setartist(string group) { artist=group; } public string getartist() { return artist; } public void setcountry(string cty) { country=cty; } public string getcountry() { return country; } public void setprice(float p) { price=p; } public float getprice() { return price; } public void setquantity(int q) { quantity=q; } public int getquantity() { return quantity; } } 注意,我们的servlet中具有附加的智能,如果一个物品被重复选择,不会增加新的记录,而是在以前的记录上更新计数。控制servlet也响应cart.jsp中的行为,如修改数量,删除商品,还有结帐。如果结帐,控制通过下述语句转向checkout.jsp页面(源程序5): string url="/jsp/shopping/checkout.jsp"; servletcontext sc = getservletcontext(); requestdispatcher rd = sc.getrequestdispatcher(url); rd.forward(req,res); listing 5: checkout.jsp <%@ page session="true" import="java.util.*, shopping.cd" %> <html> <head> <title>music without borders checkout</title> </head> <body bgcolor="#33ccff"> <font face="times new roman,times" size=+3> music without borders checkout </font> <hr><p> <center> <table border="0" cellpadding="0" width="100%" bgcolor="#ffffff"> <tr> <td><b>album</b></td> <td><b>artist</b></td> <td><b>country</b></td> <td><b>price</b></td> <td><b>quantity</b></td> <td></td> </tr> <% vector buylist = (vector) session.getvalue("shopping.shoppingcart"); string amount = (string) request.getattribute("amount"); for (int i=0; i < buylist.size();i++) { cd anorder = (cd) buylist.elementat(i); %> <tr> <td><b><%= anorder.getalbum() %></b></td> <td><b><%= anorder.getartist() %></b></td> <td><b><%= anorder.getcountry() %></b></td> <td><b><%= anorder.getprice() %></b></td> <td><b><%= anorder.getquantity() %></b></td> </tr> <% } session.invalidate(); %> <tr> <td> </td> <td> </td> <td><b>total</b></td> <td><b>$<%= amount %></b></td> <td> </td> </tr> </table> <p> <a href="/examples/jsp/shopping/eshop.jsp">shop some more!</a> </center> </body> </html> 结帐页面简单地从session中取出购物车,然后显示每个物品和总金额。这里的关键是要结束session,因此在页面中有一个session.invalidate()调用。这一处理有两个原因。首先,如果不结束session,用户的购物车不会被初始化,如果用户要继续购买,车中会保留他已经支付过的商品。另外,如果用户不结帐就离开了,则session会继续占用有效的资源直到过期。过期时间一般是30分钟,在一个大的站点上,这样的情况会很快导致资源耗尽。当然,这是我们不愿看到的。 注意,所有的资源分配在这个例子中是基于session的。所以,你必须确保控制servlet不被用户访问,即使是意外的访问也不允许。这可以在控制检查到一个非法访问时用一个简单的重定向错误页面来处理。见源代码6。 listing 6: error.html <html> <body> <h1> sorry, there was an unrecoverable error! please try <a href="/examples/jsp/shopping/eshop.jsp">again</a>. </h1> </body> </html> (编辑:聊城站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
站长推荐