Java Write your own MVC Framework Learning notes

Source: Internet
Author: User

1. Introduction

The full name of MVC is the model View Controller, which is the abbreviation for the models-view-controller, a software design paradigm that organizes the code with a method of business logic, data, and interface display separation. Aggregating business logic into a single component does not require rewriting business logic while improving and personalizing the interface and user interaction. MVC is uniquely developed to map the traditional input, processing, and output functions in a logical graphical user interface structure.

We're going to build our own simple framework for accessing the Java controller from a URL.

2. Realization of Ideas
    • First, we're going to create a one by one correspondence between URL access requests and our back-end Java methods.
    • Then we need to get the one by one correspondence that was recorded in the previous step when the Tomcat container started the Web site load and record it.
    • Finally, complete the URL access to the background Java method jump.
3. Implementation: (1) The mapping of URLs to the background Java method is marked by annotations. A. Defining annotations: This annotation can be labeled on classes and methods.
/**@author*/@Target ({elementtype.method, elementtype.type}) @ Retention (retentionpolicy.runtime) @Documented public @Interface  urlmapping {      Public default "";}
B. The appropriate method for URIs in Java background:
 PackageMVC;/** * @author Wang*/@UrlMapping (URL= "/hellocontroller") Public classhellocontroller {@UrlMapping (URL= "/hello")     PublicString SayHello () {System.out.println ("HELLO_________________"); return"Hello"; } @UrlMapping (URL= "/hi")     PublicString Sayhi () {System.out.println ("HI_____________"); return"Hi"; }    }

With annotations, we can see that we have developed a URL that will be/say/*** in the future with the Saycontroller class. Where the SayHello method corresponds to the URL of the/say/hello,sayhi method, the corresponding URL is/say/hi.

In this way, we define the corresponding relationship between the URL and the Java backend method. Next we want to implement a jump if this correspondence is done

(2) Implement the URL to the Java background method of jump A. Define the underlying data types that we use to store URLs to Java backend methods:
 PackageMVC;/** * @author Wang*/ Public classMvcbase {PrivateString url;//Access PathPrivateString controller;//class namePrivateString method;//Method name PublicString GetUrl () {returnURL; }     Public voidseturl (String url) { This. url =URL; }     PublicString Getcontroller () {returnController; }     Public voidSetcontroller (String Controller) { This. Controller =Controller; }     PublicString GetMethod () {returnmethod; }     Public voidSetmethod (String method) { This. method =method; }    }
B. Collect the corresponding relationship of the URL to the Java backend method and store it by the listener when Tomcat boots up:
 PackageMVC;ImportJava.lang.reflect.Method;Importjava.util.ArrayList;Importjava.util.List;Importjavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener;/** * @author Wang*/ Public classUrlmappingcollectionImplementsServletcontextlistener {//a list of class methods that were annotated with Urlmapper    Private StaticList<mvcbase>mvcbases; //List of controllers we want to scan    Private FinalString[] controllerlist = {"MVC. Hellocontroller "};  Public voidcontextdestroyed (Servletcontextevent arg0) {} Public voidcontextinitialized (servletcontextevent arg0) {mvcbases=NewArraylist<mvcbase>(); Try {            //loop all controllers that need to be scanned             for(String controllername:controllerlist) {string Classurl= ""; String Methodurl= ""; //Get controller classClass<?> Clas =Class.forName (controllername); //class is marked with urlmapping annotations                if(Clas.isannotationpresent (urlmapping.class) ) {Classurl= Clas.getannotation (urlmapping.class). URL (); //get List of methodMethod[] Methods =Clas.getmethods ();  for(Method method:methods) {if(Method.isannotationpresent (urlmapping.class) ) {Methodurl= Method.getannotation (urlmapping.class). URL (); Mvcbase MVC=Newmvcbase (); Mvc.seturl (Classurl+Methodurl);                            Mvc.setcontroller (controllername);                                                        Mvc.setmethod (Method.getname ());                        Mvcbases.add (MVC); }                    }                                    }                                            }        } Catch(Exception e) {}} Public StaticList<mvcbase>getmvcbases () {returnmvcbases; }    }
      • Mvcbases is where we want to store the URL to the Java backend method correspondence. We define him as a static method so that we can follow our direct access to get it.
      • Controllerlist is used to tell the listener what classes we are going to get from the URL to the Java backend method's corresponding relationship. Because we already knew it during the programming period, we defined it as the final attribute.
      • Then, at the time of the listener initialization, the class in the loop Controllerlist, based on the information of the annotations, collects the corresponding relationship of the URL to the Java backend method and stores it in mvcbases.
C. Configuring servlet Access:

First we will prepare our servlet class, and all future URL requests will be redirected to this servlet.

 PackageMVC;Importjava.io.IOException;ImportJava.lang.reflect.Method;Importjavax.servlet.ServletException;ImportJavax.servlet.http.HttpServlet;Importjavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;/** * @author Wang*/ Public classServletcenterextendsHttpServlet {/**     *      */    Private Static Final LongSerialversionuid = 1L; @Overrideprotected voiddoget (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {Try{dotransfer (req, resp); } Catch(Exception e) {}} @Overrideprotected voidDoPost (httpservletrequest req, HttpServletResponse resp)throwsservletexception, IOException {Try{dotransfer (req, resp); } Catch(Exception e) {}}//execute the corresponding method via URL    Private voidDotransfer (httpservletrequest req, HttpServletResponse resp)throwsexception{//traversing the URL container         for(Mvcbase mvcBase:UrlMappingCollection.getMvcBases ()) {//Judging the annotation path            if(Req.getrequesturi (). Equals (Req.getcontextpath () +Mvcbase.geturl ())) {                //reflection gets ClassClass<?> Clas =Class.forName (Mvcbase.getcontroller ()); //Get MethodMethod method =Clas.getmethod (Mvcbase.getmethod ()); //Execution MethodMethod.invoke (Clas.newinstance ()); }        }            }}

As you can see, the Dotransfer method is executed in both Doget and Dopost. The corresponding Web. XML is configured as:

<?xml version= "1.0" encoding= "UTF-8"? ><web-app version= "2.5"xmlns= "Http://java.sun.com/xml/ns/javaee"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd "><display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</ Welcome-file> </welcome-file-list> <!--configuration Listener--<listener> <listener-class>mvc. urlmappingcollection</listener-class> </listener> <servlet> <servlet-name>hello</servlet-name> <servlet-class>mvc. servletcenter</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-p Attern>/*</url-pattern> </servlet-mapping> </web-app>

In Web. XML, we jump all the requests to com.mvc.servlet.ServletCenter.

5. Testing

Deploy MYMVC to the Tomcat container, start Tomcat, enter Http://127.0.0.1:8080/MyMVC/HelloController/Hello, and http://127.0.0.1:8080/MyMVC/ Hellocontroller/hi can see the hello and Hi in the background output.

Java Write your own MVC Framework Learning notes

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.