View: Using MVC mode in web applications

zhaozj2021-02-16  50

View: Using MVC mode in web applications

Today's commercial world, manufacturers have made great efforts in their services and production lines. The display show and customer interaction becomes a model centered on Internet. The companies are gradually establishing a web display platform to attract more new customers and diversify. And simplifying the interaction of existing customer groups, making B2B-based communications, making it easier in old services. Now, in fact, each bank provides online savings; each financial institution and brokerage line re-written its own trading system to allow global access, can trade with any place that has been connected to the Internet. In aviation, defense, pharmaceutical, data management and other industrial areas, Web interfaces have been added to their business model.

As web-based services and applications are rapidly growing, the Web application development field has improved improvement and development. Existing programming methods, design patterns, and code libraries have been reused (or rewritten) such that they are associated with web-based applications. Even the entire framework is created to reduce the development time, shorten the maintenance cycle, and simplify the code of the online application. Because the main purpose of the Model-View-Controller (MVC) design is to separate business logic layers and representing logic layers, because it is more exciting in the integration of various web programs, so it is preferred for web-based applications and services. Apache's Struts is actually a MVC implementation framework in Java. Fusebox is an implementation of another MVC, which is technically implemented in multiple web technology, such as ColdFusion, PHP, Java, ASP, and Lasso.

In this article, I will tell you how to use MVC in a web-based project. My Controller will dynamically call the Action Method, and redirect to the appropriate view (view), adjust the data stream between the logic and model (Model).

Because it is a web project, I will use servlets to do server-side processing and controller (Controller), JavaBean is a model (MODEL) layer, JSP as a presentation layer. If you are not familiar with Servlets, JSP, and J2EE components, please read the reference tutorial at the end of this article.

If you want to test my project or want to use it as a core program in a large program, you need to configure the Application Server for J2EE. Here I use free Tomcat, but in a corporate environment, you may use IBM WebSphere or Bea WebLogic as a business J2EE application service and EJB / JSP container. The installation of the application server exceeds the scope of this article, but the project's source program is to package the J2EE application WAR (Web compression) file with XML configuration file; therefore, you want to run it on a configured server, you What you need is to do it DROP to an appropriate location. Moreover, if you want to invest more points, don't write your own controller layer (Controller Layer), then you may also need to consider the Apache Struts framework, which is accompanied by a huge JSP tag library, you can provide you need Various types of functions.

project

To demonstrate how to use MVC mode in web applications, I created a simple project that contains some JSP views (JSP views) ---- in any browser ---- Some Assistant Beans, behavior Action Classes, a servlet controller class. The purpose of the project is to display weather information based on the user's postal coding or city name. The architecture of this project is to make any type of large online application easier and more easily modified. Enterprise-class applications typically have a database in the background, taken out dynamic data in the view, which is composed of the so-called three-layer architecture ---- client application, server processing, corporate data service. I have to store all data information into a HashMap object. Architecture

Main controller

Any MVC designed primary controller is responsible for coordinating the data stream between the model and the view layer, responding to the request and behavioral management model data. This is the right reason for Model-View-Controller in Web applications. If the controller is written, it boots the request data, calling behavior for a variety of number and type view. Therefore, you can easily apply the same controller to any item, then add the view you need.

I called my controller servlet, and added its definition in an XML configuration description file, which in my application server is called WeatherappWeb. Under the new web application (webApp).

WeatherappWeb mainservlet mainservlet sys.mainservlet mainservlet / mainservlet ...

Servlet has standard doget and dopost methods. However, it also has HashMap, which is used to dynamically store behavior objects, which is created from the key value passed from the JSP view.

I didn't use a property file to match the key value of the execution behavior or the JSP view used to display. Instead, I put the behavior key as a hidden variable (Hidden Varivables) into the JSP itself, indicating what the controller will do next? .

When JSP submits its own data to the controller, the main "magic" happens in the dopost method. I use the reflection API to instantiate the Action class, (first I check if it already exists). Then call a method through a parameter key value. The ACTIO N class is used by the controller Controller to perform various types of behavior. All behavioral classes implements an empty Actionin Terface that can be used to use reflection and instantiate them through the parameter key values ​​returned by the JSP form. After the Action call returns, I will relocate to another view - this depends with the second key parameters passing through the Finally clause.

JSP view

This view is a simple HTML page that users can see in any web browser. They are generated by the JSP application server. The POST view has an HTML form where there is a submission behavior pointing to the controller servlet.

Two key parameters indicate what the controller indicates what the controller does and redirect.

In this example, a JSP view acquires Zip Code and submits it to the controller, instantiate the Action class using the first key value weatheraction, and calls the Viewbyzip method by passing to a request object. From the requested object, I got all the parameters and used the postal coding mode in the Data Store WeatherData object. Result BEAN's reference is placed back to the requested object. (Look at the Listing 1) After the method is complete, the controller Controller Servlet is redirected to "Weather_Data.jsp" through the second key value. (Look at Listing 2)

As you can see from the architecture chart above, I have two JSP views (one is to take Zip Code, a city string), they all have the second key value to point to the third JSP page ( Weather_data), we can see the search results. By complying with the rules of this mode, you can add any number of views and models using the appropriate keypad, and the controller will work hard to coordinate the data streams between them without knowing the specific details about the view or response model.

The last last JSP view is that I use the server-side JSP tag library (Tag Library) to verify the legality of the ZIP and City fields. code show as below:

<% @ Taglib Uri = "/ Web-INF / VALIDTAG.TLD" prefix = "Valtags"%>

If you are not familiar with the JSP tag, don't worry. I will describe how to use them to perform data verification in my next article "Using JSP Label Library Verification User Enter" in the MVC view.

In my Web MVC project, the Java Bean model layer contains the assistant Beans that accommodates data. They only have instance fields, getter and methods. They are located in the "Beans" package, under the Action class. When the controller performs a behavior method, behavior may put a bean or do some other operations. In a corporate project, behavior may do more things: connect to RDBMS, MainFrame, or other data sources to get data. Send data to the data source, update the data, do some security checks, and some other tasks. Behavior is actually a controller assistant class, but they also belong to the model layer because they control the model data status and response to the user's request. Conclusion As you can see, MVC is really suitable for the development of web applications. Once the controller is made, the programmer can create many views to respond to the model (Action Beans) for the user's situation and some special needs. Because the controller can be quickly reused in a new application, the development time is shortened, making it possible to spend more time to write business logic and model represented features. The view can be created as a prototype, and the entire creation process is completed with HTML, then converted to JSP or replaced by another technical code.

About any possible e-mail this article I: vlad_kofman@yahoo.com Code ListingsListing 1public void doPost (HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {res.setContentType ( "text / html"); String action = (String ) req.getParameter ( "ACTIONKEY"); String redirect = (String) req.getParameter ( "REDIRECTKEY"); actionInterface actionInterface = null; HttpSession session = req.getSession (); try {String classNameStr = action.substring (0, Action.indexof (".")); string methodname = action.substring (".") 1); // if action exists - get it, actioninterface = (actioninterface) ActionS.get (ClassNameStr); // if null - instantiate it if (actionInterface == null) {className = Class.forName ( "actions." classNameStr); actionInterface = (actionInterface) className.newInstance (); actions.put (classNameStr, actionInterface);} Method = ActionInterface.getClass (). getMethod (MethodName, New C LASS [] {o.getClass (), o.getClass ()}; method.invoke (actioninterface, new object [] {req, res});} catch (exception e) {session.setttribute ("msg", "Problem in MainController Servlet doPost / n" e); System.out.println ( "Problem in MainController Servlet doPost / n" e);} finally {this .getServletContext () .getRequestDispatcher ( "/ jsp /" redirect ".jsp") .include (req, res);}} listing 2public synchronized void Viewbyzip (Object Req, Object Reso) {httpservletRequest Req = (httpservletRequest) Reqo;

HttpservletResponse res = (httpservletResponse) reso; string zip = (string) Req.getParameter ("zip"); string data = (string) WeatherData.GetData (zip); if (data == null) Data = "sorry; no weather Data is available for zip: " zip; // Fill new bean weatherbean wb = new weatherbean (); wb.setzip (zip); wb.setdata (data); // put bean in to request user's object rec.setttribute ( "weather", wb);} listing 3 <% beans.WeatherBean WB = (Beans.WeatherBean) Request.GetaTRibute ("Weather");%>

weather information for <% = wb.getzip () %> <% = wb.getdata ()%>

<% IF (session.getattribute ("msg") == null) {session.settribute ("msg", "&");} %> <% = session.getattribute ("msg")%> <% session.setttribute ("msg", "&");%> < / Body>

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

New Post(0)