How to design an easy-to-use MVC framework

Source: Internet
Author: User

Introduction

It's easy to make a simple thing complicated, but it's not easy to do a complicated thing. In the world of computers,

Von Neumann simplifies the complex computer as: memory, controller, arithmetic and I/O devices;

Dennis Ritchie The obscure assembly language to 258 pages of "C programming languages";

James Gosling simplifies the tedious cross-platform coding to 256-byte code instructions;

For most of us, simply doing simple things is enough.

About the framework

Framework is a kind of common business package, the framework design should follow a few basic principles: 1 Ease of use 2 stability 3 extensibility, the framework is always for others to use

, the learning cost of the framework is proportional to his complexity, and if you design a powerful but complex interface framework, I think that few people are willing to use;

Stability is also necessary, the stable framework embodies the concept that the designer follows, the stable framework will become more and more mature; extensibility is the soul of the framework, no extensibility

The framework will only resemble the stereotyped writing of the Ming Dynasty, imprison the talented scholar, the business is always changing, the framework must have the ability to adapt to this change.

The Java web Framework has evolved in roughly the following stages:

Slash and burn period

Early Java Web technologies were implemented in SERVERLT, similar to CGI, except that the Serverlet was multithreaded rather than multi-process, and the server was not only dealing with business logic

Also responsible for the organization of the page, print HTML tags through printwirter, which brings endless trouble to the developers of the time, in order to modify a CSS style or a javacscript

Have to recompile serverlet, in order to output simple processing results, you have to use a lot of space to print HTML tags, here is a simple example:

Importjava.io.IOException;ImportJava.io.PrintWriter;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classSimpleservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L;  Public voiddoget (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {response.setcontenttype ("Text/html"); PrintWriter out=Response.getwriter (); String DocType= "<! DOCTYPE HTML public \ "-//W3C//DTD HTML 4.0 transitional//en\" >\n "; Out.println (DocType+ ");        Out.flush ();    Out.close (); }}

The only function of this code is to output HelloWorld. It's hard to imagine how much time programmers have to spend on this repetitive function in a complex business.

The preface is like the Neolithic people, with the most primitive tools to pioneer, of course, this period of the web is not what architecture. Sun, who was also aware of this, followed

Launched the Jsp,java into the next era.

The period of agricultural civilization

In order to solve the many problems encountered with Serverlet, Sun introduced JSP technology in 1999, JSP allows the insertion of Java code on the page for logical processing, but also provides

A lot of tag processing HTML tags, greatly improve the development efficiency, developers from the cumbersome OUT.PRINLT, with more energy to focus on business logic, in this

Based on the evolution of the Jsp+serverlet two-tier architecture and Jsp+serverlet+javabean three-tier architecture, in this framework, JSP focused on page presentation, Serverlet responsible for the industry

Business logic, JavaBean is responsible for the two data transfer, this is the embryonic form of MVC, follow-up web frameworks are mostly based on this model to develop, and some focus on one of the layers, such as

Freemarker, a bit concerned with the entire process, such as struct. This phase of programmer development gradually entered a fixed mode, like the era of agricultural civilization, the use of limited tools,

Promote the development of society. With the continuous use and development of similar architectures, the Java Web has entered another period of cross-domain development.

Period of industrial civilization

Just as the industrial Revolution marked the development of industry civilization, the era of the industrial civilization of Java web also has an iconic event, the structs framework released in May 2000,

This framework marks the advent of mechanized development, after adopting structs, we write similar codes in a fixed pattern, with similar configurations, if you take over this period

Project, you will find that they all have a general structure, which is a leap-forward development, and 20% of the market share also shows how the programmer was eager for the framework.

At the same time structs also reduced the requirements of programmers, find a novice for a simple training can be carried out project development, the stable framework of development also reduces the possibility of error,

Greatly reduces the cost of project development and maintenance. People are constantly repairing and innovating these frameworks in their use and thinking, and many good ideas continue to evolve, and the framework is constantly intelligent,

Lead the vast number of programmers into a new era.

The period of modern civilization

Now civilized pursuit of intelligence to let mankind from the heavy physical liberation, enjoy life, the same, into the modern civilization of the Web development also pursue the liberation of programmers, a large number of

Excellent framework emerges: webwork, Tapestry, Echo, spring, etc. not very enumerated, these frameworks are excellent, you can achieve a strong through simple configuration

function, but to choose a landmark, I will not hesitate to choose Spring, if Java let the programmer from the operating system constraints, then

Spring is to let programmers free from complex design patterns, IOC, DI, AOP, RMI, Proxy, genius Rod Johnson, a non-falling included in,

Bring new spring to the Java world, excellent ideas and simple API achievements spring irreplaceable status.

Re-create Wheels

Having discussed so many frameworks and designs that seem to have little to do with our headlines and have so many good frameworks, do we need to design them ourselves? The answer is yes,

The impetus of social development is innovation, and the motive of innovation is to keep thinking about the existing things, if all the status quo, then there is no progress, perhaps most people think

The web should be designed by MVC, coded, and, of course, I agree, but with the application of these frameworks, I can not help but think of many problems, with these problems,

With the idea of repeating wheels. With the study of structs, we also implement the "MVC" framework ourselves. The struct is excellent, he mainly implements the HTTP

The encapsulation of the requestor's user logic, in fact Serverlet has achieved this, but Serverlet can only do to map the request to a specific class, providing only

A few simple interfaces such as service and Dopost Doget process user requests, and in real development, in the face of disparate business, we have to

Serverlet Riga A large number of if else judgments:

 Public classSimpleservletextendsBaseservlet {Private Static Final LongSerialversionuid = 1L; @Overrideprotected voidService (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {Super. Service (request, response); String Command= Request.getparameter ("command"); if("Query". Equals (command) {            //Doxx}Else if("Add". Equals (command) {            //Doxx}Else if("Delete". Equals (command) {            //Doxx}Else if("Update". Equals (command) {            //Doxx}Else{            //Doxx        }     }}

Add a business, you have to add a if-else, write similar code, later maintenance will give you a headache, when you want to modify the function of a branch, you must not

Do not run all the branch use cases to ensure that there is no effect on the other logic, in fact, this code has a common logic: the dictionary lookup function, according to the request parameters found

To use the handler function, this is the typical table-driven pattern, also called Table lookup: Register the appropriate processing logic in advance, when the need to use these logic, give the logic of the keyword

Find the corresponding implementation, when your code is flooded with If-else or switch-case, you should consider this way, let us use table driver to reconstruct the above code.

Table drivers have three main elements: tables, interfaces, and management classes.

Let's start by extracting a simple interface:

 PackageCom.czp.opensource.mvc.service;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/*** * @description <p> * Service interface, each implementation class handles the corresponding request * </p> *@authorCZP *@version1.0 (2014-6-16) **/ Public InterfaceSERVICEITF {/*** * @desc: <p> * Processing HTTP requests * </p> *@paramRequest *@paramrespose*/     Public voidprocess (HttpServletRequest request, HttpServletResponse respose); /*** * @desc: * <p> processing Business Type </p> *@return     */     PublicString Processtype ();}

As you can see, this interface is nothing special, just a simple wrapper for Httpserverlet, but he provides the possibility for our next package.

Next we provide a management class that manages the implementation class of the interface, including registration and lookup:

 PackageCom.czp.opensource.mvc.service;ImportJava.util.concurrent.ConcurrentHashMap;/*** * @description <p> * Service Factory: Responsible for registering the deletion lookup service, the life of the entire application * Cycle class only need one factory, so implemented as a singleton * </p> *@authorCZP *@version1.0 (2014-6-16) *@sincejdk1.5+ **/ Public classServicefactory {Private volatile Staticservicefactory INSTANCE; PrivateConcurrenthashmap<string, serviceitf>services; PrivateServicefactory () {Services=NewConcurrenthashmap<string, serviceitf>(); }        /*** * @desc: * <p> * Double Check Lock mode delay initialization * can only be called at jdk1.5+ * & Lt;/p> *@return* INSTANCE*/     Publicservicefactory getinstance () {if(instance==NULL)        {            synchronized(Servicefactory.class) {               if(instance==NULL) {INSTANCE=Newservicefactory (); }            }        }        returnINSTANCE; }        /*** * @desc: * <p> Register Processor </p> *@paramService *@return     */     Public Booleanregist (SERVICEITF service) {SERVICEITF putifabsent=services.putifabsent (Service.processtype (), service); returnputifabsent!=NULL; }        /*** * @desc: * <p> Find processors by Business type </p> *@paramProccesstype *@return     */     PublicSERVICEITF GetService (String proccesstype) {returnServices.get (Proccesstype); }    /*** * @desc: * <p> Clear Table </p>*/     Public voidOnClose () {services.clear (); Services=NULL; }}

Next we need to register our implementation class at the appropriate point in time, which should be the best choice when the Web container is initialized before all requests arrive.

Therefore, we choose to register in listener

 PackageCom.czp.opensource.mvc.service;Importjavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener;/*** * @description * <p> Context, responsible for initializing the context of the MVC framework </p> *@author* CZP *@version* 1.0 (2014-6-16) **/ Public classContextlistenerImplementsServletcontextlistener {@Override Public voidcontextdestroyed (servletcontextevent arg0) {servicefactory.getinstance (). OnClose (); } @Override Public voidcontextinitialized (servletcontextevent arg0) {Servicefactory instance=servicefactory.getinstance (); Instance.regist (NewLoginservice ()); //Registration of other services, not to repeat here//instance.regist (New Loginservice ());    }}

Next, we can reconstruct the simpleservlet with this simple framework.

 PackageCom.czp.opensource.mvc.service;Importjava.io.IOException;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse; Public classSimpleservletextendsHttpServlet {Private Static Final LongSerialversionuid = 1L; @Overrideprotected voidService (HttpServletRequest request, httpservletresponse response)throwsservletexception, IOException {String command= Request.getparameter ("command"); SERVICEITF Service=servicefactory.getinstance (). GetService (command);    Service.process (request, response); }}

The code is simplified from our 6 if-else to just 3 lines of code, and most importantly, enhances the master, maintainability and extensibility, when you need to add any new business,

There is no need to modify and test the original logic. These are the essence of all MVC frameworks such as SPRING-MVC struct, except that their service is configured through XML.

There are many problems with this simple framework, and if you have found it, please leave a message stating that we will further refine the framework in the next article.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.