- Restore content to start
Today, I learned how to customize a simple MVC framework. First of all, we need to know what MVC framework is!
MVC Framework: The full name of MVC is Model View Controller, which is the abbreviation of Model-View-Controller. It is a model of software design. It organizes code with a method of separating business logic, data and interface display, and aggregates business logic into a component. It does not need to rewrite business while improving and personalizing customized interface and user interaction. Logic. MVC has been uniquely developed to map traditional input, processing and output functions in a logical graphical user interface structure.
The MVC framework we define today is a simple imitation of struts 2
Then we will use two commonly used skills, one is to parse xml files using dom4j, and the other is the java reflection mechanism.
Let's look at the overall architecture first.
We use the tool intellij idea. We will create a maven project and then import the two jar packages we need in the pom file, one for dom4j and one for javaee.
Here 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 build the package and start creating the classes and interfaces we need.
First, we define our own Action interface. In this interface, we simply define two string constants and an abstract execute method. Finally, let's look at the implementation. Now let's not talk more about it.
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, and we retrieve objects through the class name reflection mechanism.
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 an ActionMapping class, which defines several properties, similar to the role of entity classes.
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 class of XML, our class ActionMapping Manager, which reads XML with jdom4j and then adds 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 define a servlet to get the request, LoginServlet. We find the frame.xml mainly by getting the 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 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, let's configure web.xml and 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 prepared two pages, one login.jsp. A success.jsp.
First look at login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Sign in</title> </head> <body> <form action="login.action" method="post"> <input name="name"><br> <input type="submit" value="Land"/> </form> </body> </html>
Then look at success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Sign in</title> </head> <body> <h2>Login successfully</h2> </body> </html>
Finally, let's take a look at the results of the operation.
If you want a better understanding, you need to debug and see how each step goes.
There are also various problems encountered in the use of intellij idea. If you have problems related to the use of idea, you can also discuss them together.