Understanding "music without borders"
The main interface of "music without borders" is Eshop. JSP on the jsp page (see Code List 1 ). You will notice that this page serves almost only as a dedicated user interface and does not undertake any processing tasks-it is an ideal JSP solution. In addition, pay attention to the other JSP page Cart. jsp (see Code List 2) is Eshop. jsp commands <jsp: include page = "Cart. jsp "flush =" true "/> is included in it.
Code List 1: EShop. jsp
<%@ page session="true" %>
Code List 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><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><% } %>
Here, Cart. jsp controls the expression of the session-based shopping Cart. In the MVC system, the shopping Cart acts as the Model.
Observe the script snippets starting with Cart. jsp:
<%Vector buylist = (Vector)session.getValue("shopping.shoppingcart");if (buylist != null && (buylist.size() > 0)) {%>
This script mainly extracts the shopping cart from the session. If the shopping cart is empty or has not been created, nothing is displayed. Therefore, when the user visits the application for the first time, view 3 is shown to him:
Figure 3: music without borders, main view
Button text in the figure: put in the shopping cart
If the shopping cart is not empty, the selected items are retrieved from the shopping cart in sequence, as shown in the following script snippet:
<%for (int index = 0; index< buylist.size(); index++) {CD anOrder = (CD)buylist.elementAt(index);%>
Once a variable describing an item is created, it is directly embedded into a static HTML Template Using JSP expressions. Figure 4 shows the view after the user adds some items to the shopping cart.
Figure 4: music without borders, shopping cart View
Text in the figure: Music Without Borders; Quantity: Quantity; ALBUM: recording; ARTIST: ARTIST; COUNTRY: COUNTRY; PRICE: PRICE; Delete: Delete; Checkout: Checkout.
Note that the processing of all actions implemented in Eshop. jsp and Cart. jsp is controlled by ShoppingServlet. java, as shown in code listing 3:
Code List 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 ("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") {// have you purchased the same CD before? Boolean match = false; cd acd = getcd (req); If (buylist = NULL) {// put the first CD in the shopping cart buylist = new vector (); // The first order buylist. addelement (ACD);} else {// not the first purchase for (INT I = 0; I <buylist. size (); I ++) {CD = (CD) buylist. elementat (I); If (CD. getalbum (). equals (ACD. getalbum () {CD. setquantity (CD. getquantity () + ACD. getquantity (); buylist. setelementat (Cd, I); match = true;} // If name matches end} // For Loop end 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 how ugly string mycd = req will be in a script snippet. 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 = 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 ;}}
Each time a user adds an item to the eshop. jsp page, the page sends a request to the control servlet. The servlet determines the appropriate actions in sequence, and then processes the Request Parameters of the items to be added. It then shows a new CD Bean (see code list 4) indicating the selected item and updating the shopping cart object in the session.
Code list 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;}}
Note: We include additional intelligence in the servlet so that it can understand that if a previously added Cd is selected again, it only needs to increase the count for the CD bean in the shopping cart. This control servlet can also handle the actions triggered in cart. jsp, such as deleting an item from the shopping cart or checking out the account. Note that the control servlet has always been fully aware of resource allocation and determines which resources are called in the response to specific actions. For example, if the shopping cart status changes, such as adding or deleting, the control servlet will send the processed requests to the eshop. jsp page. This prompted the page to re-display the main view, and the data displayed in the shopping cart has been updated. If the user decides to settle the bill, the request will be sent to the checkout. jsp page after processing (see Code List 5) and implemented through the following scheduling program:
String url = "/jsp/shopping/Checkout.jsp";ServletContext sc = getServletContext();RequestDispatcher rd = sc.getRequestDispatcher(url);rd.forward(req, res);
Code List 5: checkout. jsp
<%@ page session="true" import="java.util.*, shopping.CD" %>
Checkout. jsp only retrieves the total number of shopping cart and all requests from the session, and then displays the selected item and total price. Figure 5 shows the client view at checkout. Once the user settles the bill, it is important to remove the session object in time. Taking care of this, a session. invalidate () call is required at the end of the page. This process is necessary. There are two original items: first, if the session is not terminated, the user's shopping cart will not be reinitialized. When he tries to start a new round of shopping without checking out the account, his shopping cart will still keep the items he has purchased. Second, if the user leaves without checkout, the session object will not be voided and will still occupy valuable system resources until it expires. Because the default session is valid for 30 minutes, in high-load systems, this situation will quickly exhaust system resources. Of course, we know what an Application means to exhaust system resources!
Figure 5: music without borders, checkout View
The text in the figure is the same as that in Figure 4.
Note that all resource allocation in this example is based on sessions, because this model is stored in sessions. Therefore, you must make sure that the control Servlet is not accessed by users, even unexpected access is not allowed. To solve this problem, you can automatically redirect the error page when the control Servlet detects an illegal access. (See code listing 6)
Code List 6: error.html
Configure "music without borders"
I suppose you are using the latest version of JavaServer Web Development Kit (Java Server Web Development Kit-JSWDK) of Sun for example. Assuming that this server is installed under the \ jswdk-1.0.1 directory -- this is its default installation path in Windows, the file for the music without Borders application should be configured as follows:
- Create shopping directory under \ jswdk-1.0.1 \ examples \ jsp directory
- Copy Eshop. jsp to \ jswdk-1.0.1 \ examples \ jsp \ shopping
- Copy Cart. jsp to \ jswdk-1.0.1 \ examples \ jsp \ shopping
- Copy Check. jsp to \ jswdk-1.0.1 \ examples \ jsp \ shopping
- Type javac *. java to compile the. java file.
- Copy ShoppingServlet. class to \ jswdk-1.0.1 \ webpages \ Web-Inf \ servlets
- Create the Shopping directory under the \ jswdk-1.0.1 \ examples \ Web-INF \ JSP \ beans directory
- Copy CD. Class to \ jswdk-1.0.1 \ examples \ Web-INF \ JSP \ beans \ shopping
- Copy error.html to \ jswdk-1.0.1 \ webpages
- Once the server is started, you can use http: // localhost: 8080/examples/JSP/shopping/eshop. jsp to access this application.
Weigh JSP and servlets
In this example, we carefully examine the control level and flexibility provided by JSP Model 2. In particular, we have seen how to mine the best features of Servlets and JSP, to the greatest extent possible to separate content and expressions. Correct use of the Model 2 architecture allows you to centralize all processing logic in the control Servlet so that JSP pages are only responsible for expressing or viewing. However, the disadvantage of using Model 2 is that it is complicated. Therefore, Model 1 may be more suitable for simple applications.