Understanding the Bss Learning: Understanding the JSP Mode 2 Architecture - MVC Design Mode Adventure

xiaoxiao2021-03-06  21

original

Understanding JSP mode 2 architecture

MVC design mode adventure

Summary: By developing a familiar web-based shopping store, you will learn how to toolize the MVC design mode and to separate the content and performance when using JSP. Govind Seshadri will show you how easy (2000 words (number of original words)). Author: Govind Seshadri aside despite the relatively recent introduction of related terms, jsp technology is good in its own way become a java technical excellence to create dynamic web content applications. Java developers love JSP because many different reasons. Some people like it brings the fact that "writing, running everywhere" is the fact that it is easy to use and help people use Java as a server-side script. But all recognizes one thing - using JSP's greatest benefits is to effectively separate content and performance. In this article, I will provide an in-depth view that gives the best content and the separation of the performance using the JSP mode 2 architecture. This mode can also be seen as a popular MVC design mode implementation in the server. Please note that you should be familiar with JSP and Servlet before starting, because I will not discuss grammar issues in this article.

So, what is the problem with servlet?

Since JSP is used to provide dynamic web content, some people may want to know why servlet is stripped with it from JSP. There is no problem with the function of servlet. It is well done well for the server, and it is suitable for this due to its important installation basis. In fact, from the structure, you can see JSP as an extension of the extended servlet with the servlet 2.1 API. Still should not use the servlet from which it should not be applied; it may not apply to everyone. For example, although the page designer can easily write JSP pages using regular HTML or XML tools, servlet is usually more suitable for background developers, they usually use some IDE - a specialized knowledge that usually requires high level programming the process of. When publishing a servlet, even if the developer must pay attention to and confirm that there is no tight coupling between content and performance. Typically, you can do this by adding a third-party HTML package such as HTMLKONA. Even though this, although there are some simple scalability for screen changes, it is still not impact on the impact of performance format itself. For example, if your performance is transformed from HTML to DHTML, you will still need to confirm that your package is compatible with this new format. In the worst case, if the package cannot be used, you may eventually pass the performance form internally internally. So, what is the solution? Just as you will see, a way will use JSP and servlet at the same time to create an application system.

Differential philosophy

Early JSP specification claims two philosophical ideas that use JSP technology to create applications. These two ideas, using terminology, JSP mode 1 and mode 2, essentially differentiated in the position where most requests occur. In the mode 1 architecture, as shown in Figure 1, the JSP page is independently responsible for processing requests and sending feedback to the client. There is still a separate content and the separation of performance, as all data access is done using beans. Although the mode 1 architecture should be very suitable for simple applications, it is not advisable to complex implementation. Any use of this structure usually results in a large number of scripts and Java code embedded in the JSP page, especially if there is a large number of requests to be processed. Although this may not be a big problem for Java developers, it is undoubtedly a problem. If your JSP page is created and maintained by the designer - this is usually in the big project. In the end, this problem will even lead to the confusion of role definitions and responsibility assignments, causing trouble that can be easily avoided.

Figure 1: JSP mode 1 structure

The pattern 2 architecture is shown in Figure 2, is a mixed scheme for dynamic content services because it uses servlet and JSP. It uses the advantages of two technologies, using JSP to generate a performance layer and servlet is responsible for performing sensitive tasks. Here, the servlet plays the role of the controller, responsible for requesting processing and generating the bean and objects to use by JSP, and determines which JSP page forwarded to the next step according to the customer's action. It is important to note that there is no processing logic within the JSP page; it is just simply responsible for acquiring objects and beans that may be created in advance, and inserting the dynamic content from the servlet in the static template. My point is that this approach generally forms the clean and thorough performance and content separation, making your developer and page designer's role and responsibility in your development team. In fact, your application is more complex, the more benefits brought by using mode 2. Figure 2: JSP mode 2 structure

In order to clarify the concept behind the mode 2, let's visit a detailed implementation of a refinement: a sample called music unbound online music store sample.

Understand the unbounded main view of the music, or the performance layer, is generated by the JSP page ESHOP.JSP for our music (see Listing 1). You will notice that this page only processes the main user interface of this app, and does not do anything to work - a best JSP script. Also note another JSP page, Cart.JSP (see Listing 2), by instruction is included within Eshop.jsp.

Listing 1 Eshop.jsp <% @ Page session = "true"%> 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 =" / example = ") > <b> cd: </ b> <select name = cd> <option> Yuan | The Guo Brothers | China | $ 14.95 </ option> <option> Drums of passi | 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 | $ 16.95 </ option> <option> iBuki | KODO | Japan | $ 13.95 </ option> </ select> <b> Quantity: </ b> <input t Ype = "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></p> <p>Listing 2 Cart.jsp <% @ Page session = "true" import = "java.util. *, Shop.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.eMentat (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 ()%> <form name = "deleteform" action = "/ example" 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"</p> <p>Action = "/ example / servlet / shoppingservlet" method = "post"> <input type = "hidden" name = "action" value = "checkout"> <input type = "submit" name = "checkout" value = "checkout "> </ Form> </ center> <%}%> Here, Cart.jsp processes the expression of Session-based shopping cart, which specifies the model in our MVC structure. Observing this feet of Cart.JSP: <% vector buylist = (vector) session.getValue ("Shopping.shoppingCart"); if (Buylist! = Null && (Buylist.size ()> 0)) {%> basically This script raised a shopping cart in Session. If the shopping cart is empty or not yet created, it will not display anything; therefore, when the user first accessed, the page he saw is shown in Figure 3.</p> <p>Figure 3: Music unbound, main view</p> <p>If the shopping cart is not empty, the selected item will be proposed from the shopping cart again, like the following script demonstration:</p> <p><% For (int index = 0; index <buylist.size (); index ) {cd anorder = (cd) Buylist.ementat (index);%> Once you describe the variables of the items have been created, they are simply expressed by JSP Insert it into a static HTML template. Figure 4 shows the case where the user has put some things to the shopping cart.</p> <p>Figure 4: Music unbound, shopping car view</p> <p>An important thing to pay attention to here is that all thections do neither in the Eshop.jsp or in Cart.JSP, but by the controller servlet, ShoppingServlet.java, see Listing 3:</p> <p>Listing 3 ShoppingServlet.javaimport 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 ("delete")) {string del = Req.getParameter ("delIndex"); int D = (New Integer (DEL)). INTVALUE (); Buylist.RemoveElementat (d);} else if ("add")) {// any previous Buys of Same CD? Boolean match = false; cd ACD = getcd (req); if (Buylis) T == 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.ementat (i); if (cd.getalbum (). Equals (acd.getalbum ())) {cd.setquantity () ACD .getquantity ()); Buylist.selementat (CD, I); match = true;} // end of if name matches} // end of for if (! match) Buylist.addelement (ACD);}} session.putValue ("</p> <p>shopping.shoppingcart ", buylist); String url =" / jsp / shopping / EShop.jsp "; ServletContext sc = getServletContext (); RequestDispatcher rd = sc.getRequestDispatcher (url); rd.forward (req, res);} else IF ("Checkout")) {float total = 0; for (int i = 0; i <buylist.size (); i ) {cd anorder = (cd) Buylist.ementat (i); float price = anORDER.GETPRICE (); int = 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.setttribute ("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 ()). FloatValue ()); cd.setquantity ((New Integer (Qty)). INTVALUE ()); Return Cd;}} Every time the user is in An item is added to the ESHOP.JSP, and the request is sent to this controller servlet.</p> <p>It determines the appropriate action in turn and then processes the request parameters of the items to be added. It instantiates a new CD BEAN (see Listing 4) representing this selected item, then putting this bean to the update of the shopping cart prior to session. Listing 4 CD.javaPackage 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;}}</p> <p>Note We also include additional intelligence in this servlet, so it can know if you have selected a CD in the shopping cart, then you should simply add the count of CD beans in the session. It also handles the action triggered from Cart.jsp, such as the user who removes items from the shopping cart, or continues to pay the bill of checklist. Note that the controller always has a complete control of a particular action to a particular action. For example, a change in the status of the shopping cart, an increase and delete, which causes the controller to forward the request to the Eshop.jsp page. This causes this page to restrict the main view in accordance with the updated shopping cart. If the user decides to check out, the request is processed to the Checkout.jsp (see Listing 5), through the rear request splitter, like the following:</p> <p>String url = "/ jsp / shopping / checkout.jsp"; servletcontext sc = getServletContext (); RequestDispatcher Rd = Sc.GetRequestDispatcher (URL); Rd.Forward (REQ, RES);</p> <p>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.getaTribute ("amount"); for (int i = 0; i <buylist) .size (); i ) {cd anorder = (cd) Buylist.ementat (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 = "</p> <p>/examples/jsp/shopping/eshop.jsp">Shop Some more! </a> </ center> </ body> </ html> Checkout.jsp Just raises your shopping cart in the session and extracts the total amount for this request Then display the selected items and their total price. Figure 5 shows the user view of the settlement. Once the user is checked, deleting the session object is equally important. This session.INVALIDATE () call is completed by the end of the page. There are two reasons to do this. First, if the session is invalid, the user's shopping cart will not reiniterate; if the user tries to start a new round of purchasing, her shopping cart will continue to save. Items of money. Second, if the user is only left the website, this session object will not be recycled by the garbage collection mechanism but continue to take up valuable system resources until the lease expires. Because the default session lease is approximately Thirty-minute, in a large-capacity system will soon lead to the system within the system. Of course, we all know what the application that exhausts the system's memory will happen.</p> <p>Figure 5: Checkout view</p> <p>Note that all resources for this app are session related, because the mode here is stored in the session. Therefore, you must ensure that users do not directly access the controller for some reason. You can automatically turn to an error page when the controller is missing to deficiency, and to avoid this happening.</p> <p>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></p> <p>Deploying Music I assume that you are using the latest version of JavaServer Web Development Kit (JSwDK) from Sun's latest version to run this example. If not, see where to see where the resource section goes. Suppose the server is installed in /jswdk-1.0.1, this is the default path under the Microsoft Windows system, which can be deployed below the music application:</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-60368.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="60368" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.035</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'Q7yPBzV_2FmpwdEQQeiru3Q6f_2F7GvDrjnV_2F6rLNfcNUDsHxr2esNcYKFn_2BeTjSqYBc90Yz50snuiR0L_2Bz5VyIlRQ_3D_3D'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>