打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Understanding JavaServer Pages Model 2 architecture part2

Understanding JavaServer Pages Model 2 architecture

Exploring the MVC design pattern

Page 2 of 2

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;            }            }            


Noticethat we have also included additional intelligence within the servlet,so that it understands that, if a previously added CD is reselected, itshould simply increase the count for that CD bean within the shoppingcart. The controller servlet also processes actions triggered fromwithin Cart.jsp,such as the user deleting items from the shopping cart, or proceedingto the checkout counter. Observe that the controller always hascomplete control over which resources should be invoked in response tospecific actions. For example, changes made to the state of theshopping cart, such as additions or deletions, cause the controllerservlet to forward the request after processing to the Eshop.jsp page. This in turn causes the page to redisplay the main view, along with the updated contents of the shopping cart. If theuser decides to check out, the request is forwarded after processing to the Checkout.jsp page (shown in Listing 5) by means of the following request dispatcher, as shown below:

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>            


Checkout.jspsimply extracts the shopping cart from the session and the total amountfor the request, and then displays the selected items and their totalcost. Figure 5 shows the client view upon checkout. Once the user goesto the checkout counter, it is equally important to get rid of thesession object. That is taken care of by having a session.invalidate()invocation at the end of the page. This process is necessary for tworeasons. First, if the session is not invalidated, the user‘s shoppingcart is not reinitialized; if the user then attempts to commenceanother round of shopping upon checkout, her shopping cart willcontinue to hold items that she has already purchased. The secondreason is that if the user simply left the site upon checkout, thesession object will not be garbage collected and will continue to takeup valuable system resources until its lease period expires. Since thedefault session-lease period is about 30 minutes, this can quickly leadto the system running out of memory in a high-volume system. Of course,we all know what happens to an application that runs out of systemresources!

Figure 5: Music Without Borders, checkout view

Noticethat all the resources for this application are session aware, sincethe model here is stored within the session. Consequently, you mustensure that the user does not somehow access the controller directly,even by mistake. You can take care of this by implementing theautomatic client redirection to the error page (shown in Listing 6)when the controller detects the absence of a valid session.

Author Bio

Govind Seshadri is an Enterprise Java Guru forjGuru.com, and the author of Enterprise Java Computing --Applications and Architecture from Cambridge University Press(1999). Learn more about Govind at jGuru.com.JavaWorld and jGuru have formed a partnership to help thecommunity better understand server-side Java technology. Together,JavaWorld and jGuru are jointly producing articles, freeeducational Web events, and working together on theJavaWorld bookstore and Web-based training.
Listing 6:
error.html
<html>            <body>            <h1>            Sorry, there was an unrecoverable error! <br>            Please try <a href="/examples/jsp/shopping/EShop.jsp">again</a>.            </h1>            </body>            </html>            


Deploying Music Without Borders

I will assume that you are using the latest version of JavaServer Web Development Kit (JSWDK) from Sun for running the example.If not, see the Resources section to find out where to get it. Assuming that the server is installed in \jswdk-1.0.1, its default location in Microsoft Windows, deploy the Music Without Borders application files as follows:

  • Create shopping directory under \jswdk-1.0.1\examples\jsp
  • Copy EShop.jsp to \jswdk-1.0.1\examples\jsp\shopping
  • Copy Cart.jsp to \jswdk-1.0.1\examples\jsp\shopping
  • Copy Checkout.jsp to \jswdk-1.0.1\examples\jsp\shopping
  • Compile the .java files by typing javac *.java
  • Copy ShoppingServlet.class to \jswdk-1.0.1\webpages\Web-Inf\servlets
  • Create shopping directory under \jswdk-1.0.1\examples\Web-Inf\jsp\beans
  • Copy CD.class to \jswdk-1.0.1\examples\Web-Inf\jsp\beans\shopping
  • Copy error.html to \jswdk-1.0.1\webpages
  • Once your server has been started, you should be able to access the application using http://localhost:8080/examples/jsp/shopping/EShop.jsp as the URL


Leveraging JSP and servlets

Inthis example, we have examined in detail the level of control andflexibility provided by the Model 2 architecture. In particular, we‘veseen how the best features of servlets and JSP pages can be exploitedto maximize the separation of presentation from content. Properlyapplied, the Model 2 architecture should result in the concentration ofall of the processing logic in the hands of the controller servlet,with the JSP pages responsible only for the view or presentation.However, the downside of using the Model 2 approach is its complexity.Consequently, it may be desirable to use the Model 1 approach forsimpler applications.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
Java面试题集
JSP与Servlet之间传值
servlet、jsp跳转(传值)总结及URL传参数
韩顺平j2ee学习笔记与心得
JSP内置对象
70个JAVA问答--xbasen的博客
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服