Technical basket with Java technology (1)

zhaozj2021-02-16  59

I. Overview

It is not easy to construct a web site that meets business activities. Existing Java technology - JSP, Servlet and Javabean have their own advantages, usually, we need to combine these technologies to achieve the best results. Although only JSP technology we can also construct a simple shopping basket, complex business applications require mutual supplements of all three technologies. Let's take a look at how to combine these technologies to get the best results.

The JSP (JavaServer Pages) provides an alternative to 100% pure Java with respect to Microsoft private ASP technology. JSP technology is extended from Java Servlet technology. In fact, the JSP framework will convert the JSP page to servlet when running. Servlet is welcomed compared to the CGI script. The servlet can also generate a dynamic web page that combines static HTML content and database queries and dynamic content provided by other business services. JSP constructs the idea of ​​dynamic web pages just in contrast to the servlet, it is embedded in the HTML. This ability to embed Java code in the HTML page provides more flexibility to construct a Java-based web application system.

To output HTML, servlet must provide a formatted string in the Println () call. Since a large number of HTMLs embedded in the Java code, this processing makes the Java code look more confusing. In addition, when generating HTML with a servlet, the design of the web page also requires the programmer's participation. JSP has separated HTML from Java code, making full-time HTML design easier to achieve, making website development more easily into two separate parts - Java design and HTML design, thus improving the efficiency of constructing websites. JSP technology can also promote business logic components to the relaxation of the performance components, which is convenient for the use of these two components. This article explores the role of JSP, Servlet, JavaBean in web applications through a shopping basket application, providing a practical example of structured design business applications.

Second, shopping basket profile

We envisage the shopping basket for simple online stores. Customers choose the product to join the shopping basket, and then purchase the product through a series of forms. Figure 1 shows our application consists of JSP, Servlet, and JavaBean. Although only JSP can also construct a simple web application, the application of business logic is complicated to the three collaborations.

Figure 2 shows the Model-View-Controller (MVC) mode. The MVC mode divides applications into three separate parts: Data Management Section (Model), Available, and Controller. MVC mode is the basis for many modern GUI applications. This segmentation is conducive to the application of each part of independent development and reuse. The MVC mode can also be used in web applications, including this application. JSP is best suited to implement the performance part of the web application; JavaBean package provides dynamic content for the website, simplifies data transfer between the applications; servlet is the most appropriate, controlling the delivery of user requests, and application messages, updating application data, Control the application process.

Although techniques such as JSP encourage specific design ideas, it is not forced to use. For example, all code to put servlet and beans can also place a single JSP page, although this will cause the code of the JSP page very confusing, but the JSP specification allows this design. On the other hand, any JSP page can do, the servlet can also do, that is, we can construct a web application system that do not have JSP. However, design patterns mean that specific design ideas and strategies are used. The design model is the crystallization of many developers collective wisdom, which is a long-term exploration of many developers. If we use MVC mode, this mode requires that we should not mix the application's performance and control, and data parts. Specifically, we should not output HTML from the control component, nor should it be mixed into the Control Logic in the Periodic Component (JSP). We should limit the JAVA feature in the JSP page to and control, data components. Finally, if the application's data model is very complex (in any real business application, the situation is like this), then we should not mix data and computational logic in the performance component and control components; instead, we should put data and compute Logic is encapsulated into JavaBean. Third, the control section

After determining the design idea of ​​the shopping basket application, let's take a look at the design details of this application. Listing 1 shows the dopost () method of the CustomerServlet class. CustomerServlets workflow through two work control applications: Maintaining the status of shopping basket assemblies (implemented by BasketBean class), delivering customers between a series of JSP pages. Since the shopping basket is always associated with a particular customer session, we save the customer's BasketBean instance in the HTTPSession object. The HttpSession session object provides easy ways to save and extract any type of Java object with unique key values.

[Listing 1: Control section is implemented in the form of servlet]

// handle customer requests public void doPost (HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {// extract the session object of the request HttpSession session = request.getSession (true); BasketBean basket = null; / * create a new or Shopping basket, or update existing shopping basket * / Basket = (Basketbean) session.getattribute (BasketBean.basket); if (Basket == null) {// New shopper, create a shopping basket Basket = New Basketbean (); Session.SetaTRibute (BasketBean.basket, Basket);} else {// Existing shoppers, saving the status information of the shopping basket Basket.savePurchases (} // Get the current status of the workflow requestdispatcher rd = NULL; STRING NextPAGE = Request.getParameter (BasketBean.page); / * Tightly combined version: Determine the next JSP page according to the status of the customer, or end the current shopping session. Servlet knows the specific situation of each JSP page in the workflow / * if (NextPage == Null || NextPage.Equals (BasketBean.Update))) {// From the inventory directory Select RD = getServletConfig (). GetServletContext () .getRequestDispatcher "/jsp/INventory.jsp");} else if (nextpage.equals (basketbeals (basketbeals)) {// Provides purchase information RD = getServletConfig (). GetServletContext () .getRequestDispatcher ("/ jsp / purchase.jsp") } Else if (nextPagetBean.Receipt) {// Provides purchase information RD = getServletConfig (). GetServletContext () .getRequestDispatcher ("/ jsp / receipt.jsp");} // Pause the request to the right JSP page if (rd! = Null) {rd.forward (request, response);}}

In the CustomerServlet, we first call the Request.GetSession () method with the True parameter value, get a session object from the Servlet Framework. The True parameter value indicates that if the session object does not exist, we ask the servlet framework to create one. Next, we try to get a shopping basket from the session object. If you can't get a shopping basket, we have just started a shopping session, you must create a shopping basket and save it to a session object; if we get a shopping basket, it indicates that we are in the intermediate process of a session, you should save the shopping basket. Status information. After handling the status of the shopping basket, we pass our client's request to the appropriate JSP page. The request itself contains a parameter indicating the state (BasketBean.page), this parameter tells the customerservlet to pass the request to where. The controller extracts this parameter and then passes the request to the next JSP page with a RequestDispatcher object.

Fourth, MODEL section

Listing 2 shows how BasketBean implements a simple data manager for the apps for this article. The BasketBean class provides a method of purchasing the total product price of our customers, as well as a method of updating shopping basket. It maintains a list of products purchased by a customer in a hash table products_, and the hash table is used as the SKU number. An InventoryBean object manages the directory of the PRODUCT instance of the array. Each Product instance saves four properties: product name, SKU number, price of each unit product, purchase of products. Product will only be added only when the quantity is greater than 0.

Listing 2: Implemented models in the form of JavaBean

public class BasketBean {final static public String BASKET = "Basket"; final static public String PAGE = "Page"; / * workflow status * / final static public String UPDATE = "Update"; final static public String PURCHASE = "Purchase "Final static public string receipt =" receipt "; / * Product key in the current shopping basket: SKU # Value: Product * / Private HashTable Products_ = new hashtable (); public barTbean () {} / * Calculate shopping basket Total price * / public double gettotal () {double totalprice = 0.0; enumeration E = Products_.Elements (); while (E.hasMoreElements ()) {Product product () E.NEXTELEMENT (); TotalPrice = Product.getPounds () * product.getPrice ();} return totalprice;} / * Number of specific products in the shopping basket * / public double getpounds (Product p_in_inv) {int SKU = p_in_inv.getsku (); Product P = ( Products_.Get (Integer.Tostring (SKU)); if (p == null) Return 0.0; Else Return P.GetPounds (); } / * Update with the current selection basket state * / public void savePurchases (HttpServletRequest request) {Product [] products = InventoryBean.getCatalogue (); String [] lbValues ​​= request.getParameterValues ​​( "pounds"); if (lbValues ! = null) {Products_.clear (); for (int i = 0; i 0) {Product P = NULL; P = (Product) Products [i] .clone (); P.SETPOUNDS (LBS); Products_.Put (Integer.Tostring (p.getsku ()), P);

Auxiliary method. Generate two decimal strings according to Double value * / public static string getStringifiedValue (double value) {string subval = "0.00"; if (value> 0.0) {Subval = double.toString (value); int decimal_len = Subval.length () - (Subval.lastIndexOf ('.') 1); if (Decimal_len> 1) Subval = SubVal.Substring (0, Subval.lastIndexof ('.') 3); Else Subval = "0"; Return Subval;} / * Clear Shopping Basket * / Public Void Clear () {Products_.clear ();}} 5.

In our way, the purchase process is divided into four steps, a total of three JSP pages: Inventory.jsp, Purchase.jsp, and Receipt.jsp. See Figure 3. Apply inventory.jsp displays the new visit to the new visit. The client selects the product by updating the product for the Inventory.jsp page. After choosing the products you want to buy, the customer purchases the product, and the application shows Purchase.jsp. Finally, the customer confirms the purchase operation and the application shows Receipt.jsp.

The JSP page is composed of standard HTML elements and JSP elements. The JSP specification refers to the static HTML in the page as a template. In fact, the static template will be written directly to the HTTP response stream (appropriate conversion according to the reference and escape rules). For example, the servlet framework writes the mark directly to the response stream. In addition to the static template, the JSP page can also include instructions, scripting elements, and actions. This article is to use all of these elements. The role of the instruction is to publish commands to the JSP framework, the syntax is as follows:

<% @ 指%%>

The Page instruction tells the JSP framework to configure the environment in a specified manner. For example, the inventory.jsp page is used with a PAGE instruction:

<% @ Page Buffer = "5KB" Language = "Java" IMPORT = "JSP_PAper. *" ErrorPage = "Error.jsp"%>

This instruction tells the JSP framework to buffer 5k content before sending the contents of the output stream. In addition, this instruction also tells the JSP framework, the scripting language in this page is Java. This page directive also requires the JSP framework to import all classes from the JSP_PAPER package. Finally, this PAGE command command JSP framework redirects all unprocessed exceptions to Error.jsp.

The include directive requires the JSP framework to insert the specified content into the output result of the page during the conversion. Inventory.jsp page is used in the following INCLUDE directive:

<% @ include file = "Header.html"%> <% @ include file = "footer.html"%>

The first instruction above inserted the standard page, and the second instruction inserted the standard footer. We use the include directives to implement the unified appearance and style of each JSP page. Script elements are embedded in the JSP page. The script elements used herein include: declaration, scriptlet, expression. As follows:

<%! Statement;%> <% scriptlet%> <% = expression%>

The Inventory.jsp page demonstrates the usage of all these three elements. The following JSP code snippet declares local variables to save the current shopping basket (BasketBean instance) and product directory:

<%! BasketBean Basket; Product [] Catalog;%>

The JSP statement must end with the semicolon. The scope of the JSP declaration is the JSP page.

After declaring these local variables, the Inventory.jsp page uses a scripTlet to get a shopping basket object from the session object, get the product catalog from InventoryBean.

<% BASKET = (BasketBean) session.gettribute (BasketBean.basket); catalog = inventoryBean.getCatalog ();%>

JSP declarations and JSP Scriptlets are Java code within a special JSP tag. When the JSP frame converts the JSP page into a servlet, it will merge these Java code into the new servlet.

We used the session object of the shopping basket as an implicit object. The JSP framework allows us to access certain Java objects directly, without prior declaration, these objects are so-called implied objects. The JSP specification lists all these implied objects. In the CustomerServlet, we returns a session object when calling request.getSession (True), which is the same object here. Another object that belongs to this class is an HTTPSERVLETREQUEST object (Request), which is passed to the dopost () method in the CustomerServlet. Therefore, the Inventory.jsp page can call Request.GetSession (TRUE) .GetaTribute (BasketBean.basket) extracts the shopping basket.

Combined with the Scriptlet and JSP expressions provide a powerful tool for our writing dynamic web pages. In the following INVENTORY.JSP page, we use the loop to access each product in the list, and dynamically generate HTML tables for each product (see Listing 3). We use Scriptlet to declare loops and their boundaries, mix the HTML and JSP expressions to generate a row of HTML tables.

Listing 3: Dynamic Generate HTML Form

<% For (int i = 0; i <% = product.getsku ()%> <% = Product.getname ()%> > <% = product.getPrice ()%> <%}%> JSP framework The Java code declared within the Scriptlet tag directly into the later generated servlet code. But for JSP expressions, the JSP framework is handled in different ways. When converting the JSP page to servlet, the JSP framework first converts the JSP expression into a string and then embeds them into out.println () calls. ScriptleTlet supports conditional judgment and iteration, while JSP expressions support data extraction and formatting.

In addition to the instructions and script elements, JSP actions further improve the JSP page language. The Receipt.jsp page utilizes JSP actions to manage the parameter values ​​sent by the client request. The action has the following two basic syntax forms:

Body

If there is a body in action, you must use the following form. The basic function of the action is to associate the "marker handle" to a specific JSP tag, which performs some operations with some operations in a marked basis. The JSP framework provides several standards, all of which have the name of "JSP:" prefix. For example, in this paper, online stores utilize an assisted bean to simplify the analysis of the request parameters, and we use the element to create this auxiliary bean:

The above code creates an object variable called ReceipTbean, which is an instance of the ReceipTbean class, and the scope is the current request.

The main advantage of ReceipTbean this class bean is to simplify the analysis and extraction of HTML request parameters. After declaring the bean, we use the elements to set its attribute value to the value of the corresponding HTML request parameter. The attribute value can be set separately, an explicitly specify the name of the attribute and the name of the HTML parameter. For example, the following line from the code from the ReceT.jsp page sets the Name property of the ReceTBean instance:

Because all the names of all bean properties in this example are the same as the corresponding parameter name, we can also set all the properties with a single JSP element:

The above element tells the JSP framework, matching the names of all parameter names and JavabEan properties to the name of all parameter names and JavaBeaBean properties, and set the JavaBean properties value to the corresponding HTML Request parameter value.

We use elements to extract properties from the auxiliary bean. For example, the following code extracts the NAME attribute:

Similar to the front, the Java image mechanism matches the JSP element and the JavaBean method name. In order to make the image operation, JavaBean must comply with a specific coding specification. In the ReceipTbean class, each of the properties used in Receipt.jsp has associated set methods and get methods (see ReceTBean Source Codes).

For example, the following JSP code:

There is a corresponding set method:

Void setName (String phone);

Another example, JSP code:

There is a corresponding GET method:

String getName ();

6. Model for improved application

The application of this paper is very simple, obviously only a test product. Despite this, the actual application can also sample the MVC mode as the simple application of this article. Let's take a look at how to expand this paper, construct a more practical e-commerce application.

This article implements the Model section through the BasketBean class. BasketBean class has a significant test property: First, its data is provided in "hard coded"; second, there is no standardized interface. These disadvantages limit the maintenanceability, scalability, and scalableability of the application.

A formal application should provide a standard interface for the MODEL section of the access application. Defining the interface helps establish a standardized access convention, allowing different implementations to run in "insert" as needed. This "plug-and-play" is an example of Bridge mode. The goal of the Bridge mode is the specific implementation and abstract function of the separation function. For example, inventory information for this article is initially embedded in the Java code in the form of static data. In order to improve flexibility, we should separate these data from the code, saved to the file system in the form of a file. As the scale increases, the data is usually transferred to the relational database system (RDBMS). If the BasketBean implements a standard interface, then we can use the file system or RDBMS with a re-implement interface, and do not need to rewrite the CustomerServlet.

The applications in the real world will also request the separation of data and code. The changes in data are very frequent, but the code should be as little as possible. Therefore, the application of this article is suitable for a realistic environment, at least the MODEL portion should be separated into data access and data management two levels. This two hierarchical structure makes the growth of data scale do not affect the code. Figure 4 shows a new design that separates the data from the data access logic and defines a standard interface.

Many times, scalable and data processing transactional requirement to introduce a third layer in the data management system. Now, providing data management services through CORBA or EJB interfaces is already very common. If the BasketBean implements a standard interface, we can rewrite it as a distributed service. Figure 5 shows such a three-layer implementation of the Model of this article. Seven, loose combination between components

One of the reasons for constructing JSP applications with a MVC mode is that the MVC mode is convenient for Model, View, and Controller to define a clear separation role. We should make the combination between these components to relax as possible. However, we did not keep CustomerServlet's loose integration because it included specific workflow status in the code, and the specific JSP page name is specified directly.

The close combination between Controller and View means that if one of the components is modified, another component is also likely to do corresponding modifications. In the examples of this article, if we add additional JSP pages in the shopping workflow, you must add additional criteria to the program logic of the CustomerServlet. On the other hand, CustomerServlet also enforces us to name the JSP page in a specific way.

If we can reduce the tightness of the CustomerServlet and JSP pages, the application will have better maintainability and scalability. To reduce the tightness of this combination, one of the methods is to create an auxiliary bean for each JSP page. We have access to these auxiliary beans in a CustomerServlet, manage all requests for associated JSP pages. This approach to encapsulates each request to a request handle object belongs to Command mode. As the Bridge mode, the key to implementing the Command mode is to define a common interface, each interface handle must implement the interface. The simplest form of this interface can only contain one method, for example, REDIRECT (), and we pass the request parameters to the method. This method is supported by each of the specific implementations of the interface, and the CustomerServlet can call the interface definition of the interface on any given handle without having to know any specific implementation details (see Figure 6).

We customize each auxiliary bean class based on the corresponding JSP page, and put the business logic into the auxiliary Bean class as much as possible. For example, the auxiliary bean class can verify the legality of the parameters that requests the incoming parameters, or simply secure the input parameters non-empty, or to verify the credit card.

A JSP page has only one entry, but it can have multiple outputs, each of which can be associated with different JSP pages. For example, inventory.jsp has two outputs, one is purchase.jsp, and the other is inventory.jsp yourself. We can use hidden tags to associate an auxiliary bean to each output point. In Inventory.jsp, put the following code:

value = <% = BASKETBEAN.UPDATE% >>

Replace with:

value = "jsp_paper.UpdateHandler"> value = <% = BasketBean .UPDATE% >> javabean "jsp_paper.updatehandler" should be able to be instantiated or positioned by CustomerServlet, which should include a redirection method for CustomerServlet calls. UpdateHandler should know how to verify the legality of the parameters, how to update MODEL, how to pass the request to the appropriate JSP page. Improved solution avoids hard coding of the JSP page call path to avoid writing conditional logic in the CustomerServlet.

JSP technology has practical significance for the extension of servlet technology. JSP does not replace servlet, during web application development, servlet, JSP, and JavaBean play a complementary role. According to the MVC mode, the JSP page can be extended independently or by extending the scalability requirements of the actual application by extending the servlet, JSP page, and the application of the MODEL. The application of Model can be extended to two or three-layer structures, and we can also add auxiliary bean management JSP workflow to implement loose binding between components.

转载请注明原文地址:https://www.9cbs.com/read-18366.html

New Post(0)