Use Intellij Idea to customize the MVC Framework, intellijmvc

Source: Internet
Author: User
Tags cdata

Use Intellij Idea to customize the MVC Framework, intellijmvc

--- Restore content start ---

Today, I learned how to customize a simple MVC Framework. First, we need to know what the MVC framework is!

MVC framework: the full name of MVC is Model View Controller, short for model-view-controller. It is a software design Model, organize Code by means of separation of business logic, data, and interface display, and integrate the business logic into a component to improve and personalize the custom interface and user interaction, you do not need to rewrite the business logic. MVC is uniquely developed to map traditional input, processing, and output functions in a logical graphical user interface structure.

The MVC framework we have defined today is a simple imitation of struts2.

Then we will use two common skill points: one is to use dom4j to parse xml files, and the other is the java reflection mechanism.

Let's take a look at the overall architecture.

 

We use intellij idea. We will create a maven project, and then import the two jar packages we need in the pom file, one of which is dom4j and the other is javaee.

Below are two nodes

<!--dom4j-->

<dependency> <groupId>org.jvnet.hudson.dom4j</groupId> <artifactId>dom4j</artifactId> <version>1.6.1-hudson-3</version> </dependency>
<!--javaee--> <dependency> <groupId>javax.javaee</groupId> <artifactId>javaee</artifactId> <version>6.0-alpha-1</version> <classifier>sources</classifier> </dependency>

We need to define our own configuration file frame. xml.

We need 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, create the package and create the required classes and interfaces.

First, we define our own Action interface. In this interface, we have briefly defined two string constants and an abstract execute method. Let's finally look at the implementation.

package cn.curry.action;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;/** * Created by Curry on 2017/3/15. */public interface Action {    public static final String SUCCESS="success";    public static final String LOGIN="login";    public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;}

Then we define an ActionManager management class. We use the reflection mechanism to get the object through the class name.

package cn.curry.action;/** * Created by Curry on 2017/3/15. */public class ActionManager {    public static Action getActionClass(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;    }}

Then we define another ActionMapping class, which defines several attributes, similar to the role of the entity class.

package cn.curry.action;import java.util.HashMap;import java.util.Map;/** * Created by Curry on 2017/3/15. */public class 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 need to parse the XML class. Our class ActionMappingManager reads xml with jdom4j and then adds 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 Curry 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 resultnext=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 need to define a servlet to get the request. LoginServlet mainly finds frame. xml.

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 Curry 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, IOException {        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, IOException {        doPost(request,response);    }    @Override    public void init(ServletConfig config) throws ServletException {        String fileName=config.getInitParameter("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>

For writing pages, we have prepared two pages, one login. jsp. A success. jsp.

First, check login. jsp

<% @ Page contentType = "text/html; charset = UTF-8 "language =" java "%> 

See success. jsp.

<% @ Page contentType = "text/html; charset = UTF-8 "language =" java "%> 

Finally, let's take a look at the running effect.

For a better understanding, you need to debug and check how each step is taken.

Another problem is that intellij idea can be discussed together if you have any questions about idea.

 

Related 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.