Customizing the MVC framework with IntelliJ idea

Source: Internet
Author: User
Tags cdata

Today I learned to customize a simple MVC framework, the first thing we need to know is the MVC framework!

MVC framework: The full name of MVC is the Model View controller, which is the abbreviation of 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.

Our own definition of the MVC framework today is a simple imitation of Struts2 's

Then we will use two common skill points, one is to parse the XML file using DOM4J, and the other is the Java reflection mechanism.

Let's take a look at the overall architecture

We're using IntelliJ idea, the tool. We will create a MAVEN project and then import the two jar packages we need in the Pom file, one is dom4j and the other is Java EE.

Here are two nodes:

We want to define our own configuration file, Frame.xml.

We want to define our own DTD file constraints and configuration information:

<?xml version= ' 1.0 ' encoding= ' UTF-8 '? ><! DOCTYPE myframe[        <! ELEMENT myframe (Actions) >        <! ELEMENT actions (action*) >        <! ELEMENT Action (result*) >        <! Attlist Action                Name CDATA #REQUIRED                class CDATA #REQUIRED >        <! ELEMENT result (#PCDATA) >        <! Attlist result                name CDATA #IMPLIED                Redirect (True|false) "false" >        ]><myframe>    < actions>        <action name= "Login" class= "cn.curry.action.LoginAction" >            <result name= "Success" >/success.jsp</result>            <result name= "Login" >login.jsp</result>        </action>    </actions></myframe>

Then build the package and start creating the classes and interfaces we need.

First we define our own action interface, in which we simply define two string constants, and an abstract execute method, which we end up with, and we don't say much at this time.

Then we define a ActionManager management class, and we get the object through the class name using the reflection mechanism.
 Package cn.curry.action;/** * Created by Curry on 2017/3/15. */public class ActionManager {public static action G        Etactionclass (String className) throws exception{Class Clazz=null;        Action Action=null;        Clazz=thread.currentthread (). Getcontextclassloader (). LoadClass (ClassName);        if (clazz==null) {clazz=class.forname (className);        } if (Action==null) {action= (action) clazz.newinstance ();    } return action; }} 
We then define a actionmapping class, which defines several properties, similar to the action of the entity class.
 Package Cn.curry.action;import java.util.hashmap;import java.util.map;/** * Created by ZL on 2017/3/15. */public CLA    SS Actionmapping {private String name;    Private String ClassName;    Private map<string,string> map=new hashmap<string, string> ();    Public String GetName () {return name;    } public void SetName (String name) {this.name = name;    } public String GetClassName () {return className;    } public void Setclassname (String className) {this.classname = ClassName;    public string GetValue (string key) {return map.get (key);    } public void Addtomap (String key,string value) {map.put (key,value); }} 
then we're going to do the parsing of the XML class, our class Actionmappingmanager, we read the XML by reading with JDOM4J, and then add the data to the collection.
Package Cn.curry.action;import Org.dom4j.document;import Org.dom4j.element;import org.dom4j.io.saxreader;import Java.io.inputstream;import java.util.hashmap;import java.util.iterator;import java.util.Map;/** * Created by ZL on 2017 /3/15. */public class Actionmappingmanager {private map<string,actionmapping> map=new hashmap<string, ActionMapping    > ();    Public actionmapping GetValue (String key) {return map.get (key);    } public void Addtomaps (String key,actionmapping value) {map.put (key,value);        Public Actionmappingmanager (string [] files) throws exception{for (string item:files) {init (item); }} public void init (String path) throws exception{InputStream Is=this.getclass (). getResourceAsStream (        "/" +path);        Document doc=new Saxreader (). read (IS);        Element root=doc.getrootelement ();        Element actions= (Element) root.elements ("actions"). Iterator (). Next (); for (iterator<element> action=aCtions.elementiterator ("Action"), Action.hasnext ();) {Element actionnext=action.next ();            Actionmapping am=new actionmapping ();            Am.setname (Actionnext.attributevalue ("name"));            Am.setclassname (Actionnext.attributevalue ("class")); For (iterator<element> result=actionnext.elementiterator ("result"), Result.hasnext ();) {Element result                Next=result.next ();                String name=resultnext.attributevalue ("name");                String Value=resultnext.gettext (); if (name==null| | "".                Equals (name)) {name= "success";            } am.addtomap (Name,value);        } map.put (Am.getname (), AM); }    }}
Next we'll define a servlet to get the request, Loginservlet. The frame.xml is found primarily by obtaining a request.
Package Cn.curry.servlet;import Cn.curry.action.action;import Cn.curry.action.actionmanager;import Cn.curry.action.actionmapping;import Cn.curry.action.actionmappingmanager;import Org.omg.portableinterceptor.active;import Javax.servlet.servletconfig;import javax.servlet.ServletException; Import Javax.servlet.http.httpservlet;import Javax.servlet.http.httpservletrequest;import Javax.servlet.http.httpservletresponse;import java.io.ioexception;/** * Created by ZL on 2017/3/15.    */public class Loginservlet extends HttpServlet {private Actionmappingmanager manager=null;        Private String GetClassName (HttpServletRequest request) {String Uri=request.getrequesturi ();        System.out.println (uri+ "uri");        String Context=request.getcontextpath ();        System.out.println (context+ "context");        String result=uri.substring (Context.length ());        System.out.println (result+ "result"); Return result.substring (1,result.lastindexof ("."));    } protected void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept        Ion {String key=getclassname (request);        System.out.println (key+ "key");            try {actionmapping actionmapping=manager.getvalue (key);            System.out.println (Actionmapping.getclassname () + "classname");            Action action= Actionmanager.getactionclass (Actionmapping.getclassname ());            String Result=action.execute (Request,response);            System.out.println (result+ "result");            String Path=actionmapping.getvalue (Result);            System.out.println (path+ "path");        Request.getrequestdispatcher (Path). Forward (Request,response);        } catch (Exception e) {e.printstacktrace (); }} protected void Doget (HttpServletRequest request, httpservletresponse response) throws Servletexception, ioexcept Ion {DoPost (request,reSponse); } @Override public void init (ServletConfig config) throws servletexception {String filename=config.getinitpa        Rameter ("config");        String File[]=null;        if (filename==null) {file=new string[]{"Myframe.xml"};        }else {filename.split (",");        } try {manager=new actionmappingmanager (file);        } catch (Exception e) {e.printstacktrace (); }    }}
Finally, we configure Web. XML and then write the page:
<! DOCTYPE Web-app Public "-//sun Microsystems, INC.//DTD Web Application 2.3//en" "Http://java.sun.com/dtd/web-app_2_3. DTD "><web-app>  <display-name>archetype Created web application</display-name>    < servlet>        <servlet-name>LoginServlet</servlet-name>        <servlet-class> cn.curry.servlet.loginservlet</servlet-class>    </servlet>    <servlet-mapping>        < servlet-name>loginservlet</servlet-name>        <url-pattern>*.action</url-pattern>    < /servlet-mapping>    <welcome-file-list>        <welcome-file>login.jsp</welcome-file>    </welcome-file-list></web-app>

Writing page, we have prepared two pages, one login.jsp. A success.jsp.

First Look at login.jsp

<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>and watch success.jsp.
<%@ page contenttype= "Text/html;charset=utf-8" language= "java"%>

Finally let's look at the effect of the operation

People want to better understand, need to debug their own look at each step how to go.

There are all sorts of problems with IntelliJ idea. If you have questions about using idea, you can also discuss it together.

Customizing the MVC framework with IntelliJ idea

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.