Jsp framework for understanding Mode 2: MVC design pattern Adventure

  Abstract: Understanding jsp Model 2 Architecture: MVC design pattern Adventure 

  <tr> <td> Abstract: The familiar with the development of a web-based shopping stores, you will learn how to mvc design of the tool and the use of real time from jsp content and performance.    Govind Seshadri will show you how easy it is (2000 characters (original words)). 

  Despite the relatively recent introductions aside, jsp technology is good to excellent in its own way as the creation of dynamic web content applications of java technology.    Java developers because many different reasons favorite jsp.    Some people like it to the interactive web pages brought "a preparation, run everywhere" change this fact; some other people appreciate it easy to learn and use java and help people to use as a server-side scripting.    But one thing is generally accepted - jsp use is the biggest benefit can be effectively isolated content and performance.    In this article, I provided an in-depth views on how to use jsp Model 2 framework of the contents and get the best performance of the separation.    This approach can also be seen as popular mvc design patterns in the service side of the realization.    Please note that you should be familiar with prior to the start of jsp and servlet programming, because I will not be discussed in this article grammatical problems. 

  Well, servlet What is the problem? 

  Since jsp used to provide dynamic web content and the presentation layer separated from the content is pretty good, some people may want to know why in from servlet from jsp tied up with it.    Servlet function no problem.    It has terminal handling services work very well, and, because it has an important installed base, and suitable for this.    In fact, the structure that you can achieve as jsp servlet 2.1 api for the expansion of the servlet High abstract.    Still should not be indiscriminate use of servlet; it may not be applicable to everyone.    For example, despite the page designers can easily use of conventional html or xml tools to prepare jsp pages, and usually more suitable background servlet developers, they usually use some kind of IDE - usually need a high-level series Cheng expertise in the process.    When released servlet, even if the developer must also pay attention to and recognition in the content and performance are not tightly coupled.    Usually, you can join the third-party package such as html htmlkona do this.    Even doing this, and despite brought to the screen some simple changes in scalability, it can not prevent you from the performance of its own format change.    For example, if you manifestations dhtml from html to change, you will still need to confirm your package is compatible with this new format.    In the worst case, if the package can not be used, you may end up in the dynamic content internal hard-coded forms.    Well, the solution is?    Like you, you will see, a solution will be used to create jsp and servlet applications. 

  Philosophical differences 

  Early jsp jsp norms advocated the use of technology to create two applications philosophical ideas.    These two ideas, using terminology that is jsp Mode 1 and Mode 2, in essence, the difference is that most of the requests for location.    In Mode 1 structure, as shown in Figure 1, jsp pages independently responsible for the handling of the request and sent back to the client.    Here there are still content and performance of the separation because all the data access is the use of bean completed.    Although the model for a framework should be very simple application, but the realization of the complex is undesirable.    The indiscriminate use of such a structure would normally lead to a lot of scripts and java code embedded in jsp pages, especially in a large number of requests to deal with the circumstances.    While this may java developer is not a big problem, but it is a problem, if your jsp pages by the designers to create and maintain it - usually in the case of large projects.    Ultimately, this issue could even lead role in the definition and allocation of responsibilities confusion caused this can easily avoid the trouble of project management. 


  Figure 1: jsp a model structure 

  Model 2 framework as shown in Figure 2, is a dynamic content services for the mixed programme, as it is used servlet and jsp.    It uses the advantages of the two technologies, the use of a performance-jsp servlet responsible for the implementation and sensitive task.    Here, the controller servlet play the role of a responsible and deal with the request to use the bean jsp and targets, according to the customer's action, as well as deciding on the next step forward where a jsp pages.    Special attention should be paid to the jsp pages and did not deal with the internal logic; it simply may be responsible for the creation of the object prior servelet and bean, as well as in the insertion of a static template from servlet release dynamic content.    My view is that this approach will generally formed the most thorough clean and content of the performance of the separation to make your development team in the development and page designers to the roles and responsibilities clear.    In fact, the more complex your application, the use of the benefits of Mode 2 the more. 


  Figure 2: jsp structure Mode 2 

  In order to understand the concept behind the Mode 2, we have to visit a concrete realization of a refinement: no one called the music industry's online music store samples. 

  Understand music unbounded 

  Main view, or that of performance for our music unbounded by the jsp pages EShop.jsp generated (see list).    You will note that this page almost exclusively deal with the application of the main user interface, and does not do any processing - the best jsp scripts.    Also pay attention to what the other jsp pages, cart.jsp (see list 2), adopted Directive    Included in the EShop.jsp within. 

  <table Align=center border=1> <tr> <td> 

  List 1 

  EShop.jsp 

  </ Td> </ tr> <tr> <td> <% @ page session = "true"%> 

<head>

  </ Head> 
  <body Bgcolor="#33CCFF"> 

  Music Without Borders 





  <Form name = "shoppingForm"    Method = "POST"> 
  CD: 
  <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> 
  Quantity: <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> 



  </ Body> 
  </ Td> </ tr> </ table> 

  <table Align=center border=1> <tr> <td> 

  List 2 

  Cart.jsp 

  </ Td> </ tr> <tr> <td> <% @ page session = "true" import = "java.util .*, shopping.CD"%> 
<%
  Vector buylist = (Vector) session.getValue ( "shopping.shoppingcart"); 
  If (buylist! = Null & & (buylist.size ()> 0)) ( 
%>

  <table Border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF"> 
<tr>
  <td> ALBUM </ td> 
  <td> ARTIST </ td> 
  <td> COUNTRY </ td> 
  <td> PRICE </ td> 
  <td> QUANTITY </ td> 
  <td> </ Td> 
  </ Tr> 
<%
  For (int index = 0; index <buylist.size (); index + +) ( 
  CD anOrder = (CD) buylist.elementAt (index); 
%>
<tr>
  <td> <% = AnOrder.getAlbum ()%> </ td> 
  <td> <% = AnOrder.getArtist ()%> </ td> 
  <td> <% = AnOrder.getCountry ()%> </ td> 
  <td> <% = AnOrder.getPrice ()%> </ td> 
  <td> <% = AnOrder.getQuantity ()%> </ td> 
<td>
  <Form name = "deleteForm"    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"    Method = "POST"> 
  <input Type="hidden" name="action" value="CHECKOUT"> 
  <input Type="submit" name="Checkout" value="Checkout"> 
  </ Form> 


  <%)%> </ Td> </ tr> </ table> 

  Here, based on Cart.jsp deal with the Cart session of the manifestations, it designated the MVC structure of the model.    Cart.jsp observe the beginning of this paragraph script: 
<%
  Vector buylist = (Vector) session.getValue ( "shopping.shoppingcart"); 
  If (buylist! = Null & & (buylist.size ()> 0)) ( 
%>
  Basically, this script from the session in the cart.    If the cart is empty or not created, it would not show anything, therefore, when a user first visit when he saw the page in Figure 3. 


  Figure 3: Music unbounded, the main view 

  If the cart is not empty, it has been selected items will be one at a time from the shopping cart was put forward, such as the following script, as the model: 

<%
  For (int index = 0; index <buylist.size (); index + +) ( 
  CD anOrder = (CD) buylist.elementAt (index); 
%>
  Once describe the item in the variable has been created, they would simply be inserted into JSP expressions static HTML template to.    Figure 4 shows the user a number of things have been put to cart go is the situation. 


  Figure 4: music unbounded, Cart view 

  Here we should pay attention to the important thing is not dealing with all the action took place in the Cart.jsp EShop.jsp not, but by the controller servlet, ShoppingServlet.java handling, see the list 3: 

  <table Style="WIDTH: 507px; HEIGHT: 1281px" border=1> <tr> <td> 

  List 3 

  ShoppingServlet.java 

  </ Td> </ tr> <tr> <td> 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); 
  AnOrder.getPrice float price = (); 
  AnOrder.getQuantity int qty = (); 
  Total + = (qty price *); 
  ) 
  Total + = 0.005; 
  String amount = new Float (total). ToString (); 
  Int n = amount.indexOf ('.'); 
  Amount.substring amount = (0, n +3); 
  Req.setAttribute (the "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; 
  ) 
  ) </ Td> </ tr> </ table> EShop.jsp each user to add an item, the request has been sent to the controller servlet.    It followed to determine the appropriate action, and then dealt with accordingly want to add items at the request of parameters.    It examples of a new CD bean (see list of 4), on behalf of the selected items, and then to the bean into the previous session Cart updates. 
  <table Style="WIDTH: 472px; HEIGHT: 693px" align=center border=1> <tr> <td> 

  List 4 

  CD.java 

  </ Td> </ tr> <tr> <td> 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; 
  ) 
  ) </ Td> </ tr> </ table> 

  We note in this servlet are included in the additional smart, it can know that if we chose a shopping cart in the CD, then it could be a simple increase in the session CD bean counting.    It also handles from Cart.jsp in triggering action, for example, users from shopping cart to delete items, or to continue to checkout checkout.    Always pay attention to the controller which resources should be a specific call to action on the feedback generated has full control.    For example, the state Cart changes, such as increasing and delete the request would be dealt with after the controller will be transmitted to EShop.jsp pages.    This caused the page has been updated in accordance with the shopping carts were the main re-view show.    If a user decided to checkout, the request is transmitted to Checkout.jsp after treatment (see list of 5), through the distributor behind the request, such as shown below: 

  String url = "/ jsp / shopping / Checkout.jsp"; 
  ServletContext sc = getServletContext (); 
  RequestDispatcher rd = sc.getRequestDispatcher (url); 
  Rd.forward (req, res); 

  <table Align=center border=1> <tr> <td> 

  5 list 

  Checkout.jsp 

  </ Td> </ tr> <tr> <td> <% @ page session = "true" import = "java.util .*, shopping.CD"%> 

<head>

  </ Head> 
  <body Bgcolor="#33CCFF"> 

  Music Without Borders Checkout 





  <table Border="0" cellpadding="0" width="100%" bgcolor="#FFFFFF"> 
<tr>
  <td> ALBUM </ td> 
  <td> ARTIST </ td> 
  <td> COUNTRY </ td> 
  <td> PRICE </ td> 
  <td> QUANTITY </ 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> <% = AnOrder.getAlbum ()%> </ td> 
  <td> <% = AnOrder.getArtist ()%> </ td> 
  <td> <% = AnOrder.getCountry ()%> </ td> 
  <td> <% = AnOrder.getPrice ()%> </ td> 
  <td> <% = AnOrder.getQuantity ()%> </ td> 
  </ Tr> 
<%
  ) 
  Session.invalidate (); 
%>
<tr>
  <td> </ Td> 
  <td> </ Td> 
  <td> TOTAL </ td> 
  <td> $ <= Amount%%> </ td> 
  <td> </ Td> 
  </ Tr> 
  </ Table> 


  Shop some more! 


  </ Body> 
  </ Td> </ tr> </ table> 

  Checkout.jsp only from the session in the Cart and request for the total amount extracted, and then display the selected items and their total value.    Figure 5 shows the user at the close of view.    Once the user to checkout, delete session object is equally important.    By the end of this page session.invalidate () call to complete.    There are two reasons to do so.    First, if the session did not invalid, the user will not be re-initialized Cart; after the closing if the user attempts to start a new round of procurement, she will continue to preserve Cart had already paid the money items.    Second, if the user is left alone after the closing of the site, the session will not be targets of refuse collection mechanism recovery but continue to occupy valuable system resources until the lease expires.    Session because of the default lease time is about 30 minutes, in a large-capacity system that will quickly lead to system memory depletion.    Of course, we all know that a depletion of the system's memory applications what will happen. 


  Figure 5: checkout view 

  Pay attention to the application of all the resources are in session relevant, because here in the mode of storage in the session.    Therefore, you must ensure that the user does not even due for some reason direct access controller errors.    You can detect the lack of an effective controller of the session so that when the client automatically shifted to a wrong page (see list 6), to prevent that from happening. 
  <table Align=center border=1> <tr> <td> 

  6 List 

  Error.html 

  </ Td> </ tr> <tr> <td> 
<body>


  Sorry, there was an unrecoverable error! 

  Please try again. 


  </ Body> 
  </ Td> </ tr> </ table> 

  Unbounded deployment music 

  I assume you are using sun from the latest version of the JavaServer Web Development Kit (JSWDK) to run this example.    If not, see the resources section to see where to see it made.    Assumptions server installed in the \ jswdk-1.0.1, which is under the Microsoft Windows system default path can be deployed as follows music unbounded applications: 

  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 
  If you start the server, you should be able to use to access this URL http://localhost:8080/examples/jsp/shopping/EShop.jsp applications. 

  Jsp and use servlet 

  In this case, we examined the details from the control of the level and pattern 2 architecture provides flexibility.    In fact, we have already seen a servlet and jsp pages of the best developed is how to maximize the performance of the content of the dissection.    If correctly applied, Model 2 framework will focus on all processing logic to the controller servlet hands, and jsp pages only view or performance of the work.    However, the use of Mode 2 the structure of the resistance lies in its complexity.    Therefore, a simple application usage pattern is acceptable. 

  </ Td> </ tr> </ table> 
  ↑ Back 

Share and Enjoy: These icons link to social bookmarking sites where readers can share and discover new web pages.
  • Digg
  • del.icio.us
  • Facebook
  • DotNetKicks
  • DZone
  • Netvouz
  • Propeller

Tags: , , , ,

Releated Java Articles

Comments

Leave a Reply