Javaweb to build your own MVC Framework (ii)

Source: Internet
Author: User

1. Preface

In Javaweb's own MVC framework (i) We completed the most basic jump to the URL to the Java backend approach. But the actual operation will find an inconvenient place, now there is only one Saycontroller class in the Com.mvc.controller package, if we want to add a new ***controller class, We also need to modify the Controllerlist attribute in Urlmappingcollection, which is unreasonable.

So we're going to lift this coupling off in this section. We're going to refer to controllerlist in urlmappingcollection in the XML configuration file.

2. Preparing the JAR Package

In this section we need to parse the XML file with dom4j. Of course you can also use other tools to parse the XML.

3. Implementation (1) First we will record in Web. XML The list of controllers we will need to scan in the future:
<?XML version= "1.0" encoding= "UTF-8"?><Web-appversion= "3.0"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_3_0.xsd">        <Listener>        <Listener-class>Com.mvc.listener.UrlMappingCollection</Listener-class>    </Listener>            <Mymvc>        <Controllers>            <Controller>Com.mvc.controller.SayController</Controller>
        </Controllers>    </Mymvc>                                                <servlet>        <Servlet-name>Main</Servlet-name>        <Servlet-class>Com.mvc.servlet.ServletCenter</Servlet-class>            </servlet>    <servlet-mapping>        <Servlet-name>Main</Servlet-name>        <Url-pattern>/</Url-pattern>    </servlet-mapping></Web-app>

Where the MYMVC node and its child nodes are the new nodes in this section.

(2) We then adjust the Urlmappingcollection class to read the new MYMVC node content in Web. Xml.
 PackageCom.mvc.listener;ImportJava.io.File;ImportJava.lang.reflect.Method;Importjava.util.ArrayList;Importjava.util.List;Importjavax.servlet.ServletContextEvent;ImportJavax.servlet.ServletContextListener;Importorg.dom4j.Document;Importorg.dom4j.DocumentException;Importorg.dom4j.Element;ImportOrg.dom4j.io.SAXReader;Importcom.mvc.annotation.URLMapping;Importcom.mvc.base.MVCBase; Public classUrlmappingcollectionImplementsServletcontextlistener {//a list of class methods that were annotated with Urlmapper    Private StaticList<mvcbase>mvcbases; Private FinalString mymvc_nodename = "Mymvc"; Private FinalString controllerlist_nodename = "Controllers"; Private FinalString Control_nodename = "Controller"; //List of controllers we want to scan@SuppressWarnings ("Unchecked")    PrivateList<string> getcontrollerlist (Servletcontextevent SCE)throwsdocumentexception{List<String> ctrllist =NewArraylist<string>(); String Webxml= Sce.getservletcontext (). Getrealpath ("Web-inf\\web.xml"); Saxreader Saxreader=NewSaxreader (); Document Document= Saxreader.read (NewFile (webxml)); Element rootelement=document.getrootelement (); List<Element> crtlnodelist =rootelement.element (mymvc_nodename).                                                 Element (Controllerlist_nodename).        Elements (Control_nodename);  for(Element element:crtlnodelist) {Ctrllist.add (Element.gettext ()); }        returnctrllist; } @Override Public voidcontextdestroyed (Servletcontextevent sce) {//TODO auto-generated Method Stub} @Override Public voidcontextinitialized (Servletcontextevent sce) {mvcbases=NewArraylist<mvcbase>(); Try{List<String> controllerlist =getcontrollerlist (SCE); //loop all controllers that need to be scanned             for(inti = 0; I < controllerlist.size (); i++) {String controllername=Controllerlist.get (i); String Classurl= ""; String Methodurl= ""; Class<?> clazz = Class.forName (controllername);//Get controller class                if(Clazz.isannotationpresent (urlmapping.class)) {//class is marked with urlmapping annotationsClassurl = ((urlmapping) clazz.getannotation (urlmapping.class) . URL (); }                //get List of methodMethod[] Methods =Clazz.getmethods ();  for(Method method:methods) {if(Method.isannotationpresent (urlmapping.class)) {//method is marked with urlmapping annotationMethodurl = ((urlmapping) method.getannotation (urlmapping.class) . URL (); Mvcbase Mvcbase=Newmvcbase (); Mvcbase.seturl (Classurl+Methodurl);                        Mvcbase.setcontroller (controllername);                                                Mvcbase.setmethod (Method.getname ());                    Mvcbases.add (mvcbase); }                }            }        }        Catch(Exception e) {}} Public StaticList<mvcbase>getmvcbases () {returnmvcbases; }}

We have added the Getcontrollerlist function to read the configuration information in Web. XML, then read the controller list and modify it elsewhere, reading the code in the previous section to see what changes were made.

4. Test results:

First, we need to add a new controller:

 PackageCom.mvc.controller;Importcom.mvc.annotation.URLMapping; @URLMapping (URL= "/eat") Public classeatcontroller {@URLMapping (URL= "/apple")     PublicString eatapple () {System.out.println ("I ' m Eating Apples"); return"Apple"; } @URLMapping (URL= "/banana")     PublicString Eatbanana () {System.out.println ("I ' m eating Banana"); return"Banana"; }}

Then, adjust the Web. Xml to add Com.mvc.controller.EatController:

<Mymvc>        <Controllers>            <Controller>Com.mvc.controller.SayController</Controller>            <Controller>Com.mvc.controller.EatController</Controller>        </Controllers>    </Mymvc>

Finally, we start Tomcat and enter it in the browser:

        • Http://127.0.0.1:8080/MyMVC/Eat/Apple
        • Http://127.0.0.1:8080/MyMVC/Eat/Banana
        • Http://127.0.0.1:8080/MyMVC/Say/Hello
        • Http://127.0.0.1:8080/MyMVC/Say/Hi

See if we can print out the results we want.

Javaweb to build your own MVC Framework (ii)

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.