Custom Framework (mymvc)

Source: Internet
Author: User
Tags cdata

Initial contact with the custom framework, simple login function Implementation process::

When we implement the login function, we will first create a login.jsp

Will write these login forms

  <form action= "loginaction.action" method= "post" >     name:<input type= "text" name= "name"/>< br/>     password:<input type= "text" name= "pwd"/><br/>    <input type= "submit" value= "login" >    </form>

of course, all we need to do right now is to write our own framework for successful deployment when the project starts

First we have to let the program start a servlet on its own and write its own Framework's process deployment in the Servlet.

Need to be configured in Web. XML

<!--a value of 0 or greater than 0 o'clock indicates that the container loads the servlet when the app is started;
<load-on-startup>0</load-on-startup>


<?xml version= "1.0" encoding= "UTF-8"?><!--define The constraint file--><!--element represents the elements--><!--attlist represents the property-->& lt;! --CDATA represents a string Type--><!--REQUIRED indicates that this property must be write--><!--* represents multiple--><!--implied indicates that this property can be written--><!DOCTYPE framework[<! ELEMENT Framework (actions) > <! ELEMENT Actions (action*) > <! ELEMENT Action (result*) > <!attlist action name CDATA #REQUIREDclassCDATA #REQUIRED> <!attlist RESULT name CDATA #IMPLIED Redirect (true|false) "false" >]><Framework><actions> <action name= "loginaction"class= "action.loginaction" > <result name= "success" >success.jsp</result> <result name= "login" > Index.jsp</result> </action></actions></Framework>

 public voidInit (servletconfig Config)throwsservletexception {//the Config object is an object of javax.servlet.ServletConfig, and the function is to obtain initialization configuration information//Config.getinitparameter is the content of the initialization parameter that obtains the specified nameString filename = Config.getinitparameter ("config"); System.out.println ("gg\t" +filename); String [] Filenames=NULL; if(filename==NULL)        {            //If there is no other parameter information, put it in an array that is already well-equippedfilenames=Newstring[]{"framework.xml"};  for(string string:filenames) {System.out.println (string); }        }        Else        {            //If there are additional configuration parameter information, then separate into the arrayFilenames=filename.split (",");  for(string string:filenames) {System.out.println (string+ "\ t"); }        }        //initializing using the Init method       man=new Actionmappingmanager (filenames); }

Because the code is red, he will execute the following code:

 packageAction;/*** Step three: * Because there are more than one action node, you need to configure a Actionmappingmanage class to manage the Actionmapping class*/Importjava.io.InputStream;Importjava.util.HashMap;Importjava.util.Iterator;Importjava.util.Map;Importorg.dom4j.Document;Importorg.dom4j.Element;Importorg.dom4j.io.SAXReader;/*** Because this class is an action * It contains a member variable that is customized to key value in the form of a name value, each of the actions in the?? each name represents a key * each action represents a A value *@authorSLEEP * Parse the node object in the resource file **/ public classActionmappingmanager {//collection of actionmapping classes  PrivateMap<string,actionmapping> maps=NewHashmap<string,actionmapping>();  publicactionmapping getactionmapping (String Name) {returnMaps.get (name); }  //get actions from an XML file that is assembled by Init   publicActionmappingmanager (string[] files) { for(String filename:files) {Init (filename); }  }  //Create an initialization method, use DOM4J to parse the configuration file   public voidInit (String Path) {System.out.println ("oh-----------------------------------------"); Try {         //getResourceAsStream Gets the reference to the resource input stream to ensure that the program can extract data from the correct location//Convert the Framework.xml resource object into a streamInputStream is= this. getclass (). getResourceAsStream ("/" +path); //parsing XML using the Saxreader object to read the streamDocument doc=NewSaxreader (). Read (is); //Get root nodeElement root =doc.getrootelement (); //get the first acitons node in a custom frameElement actions=( Element) root.elementiterator (). Next (); System.out.println ("root node" +Actions.getname ()); //use a For loop to traverse all action nodes under the Actions node           for(iterator<element> action=actions.elementiterator (); Action.hasnext ();) {              //get to <action> node action is a collection of actions, we want to take out the first itemElement Actionnext =Action.next (); System.out.println ("child nodes under root node" +Actionnext.getname ()); //get the Name property and class property in the action node, respectivelyString name = Actionnext.attributevalue ("name"); String ClassName= Actionnext.attributevalue ("class"); //Save the above two attributes to the Actionmapping classActionmapping mapp=Newactionmapping ();              Mapp.setclassname (classname);              Mapp.setname (name); //because there are multiple result nodes under an action node that traverse all the result nodes under Action               for(iterator<element> Result=actionnext.elementiterator ("result"); Result.hasnext ();) {                  //get to the result nodeElement Resultnext =Result.next (); //extracts the Name property value of the result node and the value in the result nodeString resultname = Resultnext.attributevalue ("name"); String Resultvalue=Resultnext.gettext (); //It is easy to call the Actionmapping class (there is data in the actionmapping Class) by depositing it into a Double-column collection in Actionmapping .Mapp.addresult (resultname, resultvalue);              System.out.println (mapp.getname ()); }              //get a collection of all action nodesmaps.put (mapp.getname (), mapp); }              } Catch(Exception E) {e.printstacktrace (); }        }}

After init execution in the Servlet method is complete, our Tomcat successfully opens

When we click Log in because it is a post request, the Dopost method in the servlet is automatically called as Follows:

Actionmappingmanager man=NULL;  public voiddoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//because index.jsp is the default request interface, the GetName method obtains the index.jsp corresponding to the key of the map in Actionmappingmanager//get to Actionmapping objectActionmapping actionmapping =man.getactionmapping (getname (request)); //get the action interface using the reflection mechanismAction action =Actionmanager.getactionclass (actionmapping.getclassname ()); Try {            //returns a logical view nameString message =Action.execute (request, response); String Results=Actionmapping.getresults (message);        Response.sendredirect (results); } Catch(Exception E) {//TODO auto-generated Catch blockE.printstacktrace (); }    }    //get the requested path name Example: day01_0100/index.jsp gets the index.jsp     publicString getname (httpservletrequest request) {//Item + Request addressString RequestUri =Request.getrequesturi ();        System.out.println (requesturi); //Project NameString ContextPath =Request.getcontextpath ();        System.out.println (contextpath); //a specific requestString path=requesturi.substring (contextpath.length ());        System.out.println (path); String filename=path.substring (1,path.lastindexof (".") . Trim ();        System.out.println (filename); returnfilename; }actionmappingmanager Mans=NULL;  public voiddoPost (httpservletrequest request, httpservletresponse response)throwsservletexception, IOException {//because index.jsp is the default request interface, the GetName method obtains the index.jsp corresponding to the key of the map in Actionmappingmanager//get to Actionmapping objectActionmapping actionmapping =man.getactionmapping (getname (request)); //get the action interface using the reflection mechanismAction action =Actionmanager.getactionclass (actionmapping.getclassname ()); Try {            //returns a logical view nameString message =Action.execute (request, response); String Results=Actionmapping.getresults (message);        Response.sendredirect (results); } Catch(Exception E) {//TODO auto-generated Catch blockE.printstacktrace (); }    }    //get the requested path name Example: day01_0100/index.jsp gets the index.jsp     publicString getname (httpservletrequest request) {//Item + Request addressString RequestUri =Request.getrequesturi ();        System.out.println (requesturi); //Project NameString ContextPath =Request.getcontextpath ();        System.out.println (contextpath); //a specific requestString path=requesturi.substring (contextpath.length ());        System.out.println (path); String filename=path.substring (1,path.lastindexof (".") . Trim ();        System.out.println (filename); returnfilename; }

Since custom MVC does not have interceptors, <url-pattern>*.action</url-pattern>

<servlet-mapping>
<servlet-name>myServlet</servlet-name>
<!--there is no filter like struts2, manually restricting all action---
<url-pattern>*.action</url-pattern>
</servlet-mapping>

Such a custom framework is done!

Custom Framework (mymvc)

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.