This article has shared with you the method of customizing struts2 MVC framework for your reference. The specific content is as follows
Custom MVC: (First understand the concepts of Model1 and Model2)
Model1 and Model2:
Model1: It is a pure JSSP development technology that combines business logic code and view rendering code.
Model2: Model2 is based on Model1, separates the business logic code and forms a Servlet alone. Model2 is also developed based on MVC.
The characteristics of MVC are summarized as follows:
(1) Data acquisition and display separation
(2) The controller combines different models and views together
(3) The application is divided into three parts, loosely coupled and work together, thereby improving the scalability and maintainability of the application
(4) Each layer is responsible for different functions and performs its own duties. The components of each layer have the same characteristics, which facilitates the generation of program code through engineering and tooling.
MVC Thought and Its Advantages (Very Strong)
MVC is an architectural model, the purpose is to separate the model (business logic) and view (presentation layer), so that the model and view can be modified independently without affecting each other. Most software adopts this pattern when designing architectures. There are many ways to use the MVC mode. When a system browsing through a browser wants to develop a mobile version, you only need to redevelop the view, and the business logic of the model part can be reused. Many software needs to launch B/S and C/S versions at the same time, adopting the MVC mode, the model part can be reused, and only different views need to be developed. MVC idea divides an application into three basic parts: M (Model, Model) V (View, View) C (Controller, Controller). Where M represents the part that processes business logic, V represents the part that displays data and obtains user input, C is similar to an intermediary, ensuring that M and V do not interact directly.
The basic steps are as follows:
1. Create XML document Framework.xml
2. Define Action interface
3. Define an actionMapping class and treat it as an action node
4. Define ActionMappingManage class to manage ActionMapping classes (actions nodes)
5. Define the ActionManager class using reflection mechanism to obtain specific classes based on the class name of the string type (writing of web.xml tags)
6. Write servlets for running time control
7. Define LoginAction class for testing
1. Create XML document Framework.xml
<!--?xml version="1.0" encoding="UTF-8"?--><!-- Definition Constraint File--> (Note) <!-- ELEMENT Indicates Element--><!-- ATTLIST Indicates Attribute--><!-- CDATA Indicates String Type--><!-- REQUIRED Indicates This attribute must be written--><!-- *Represents Multiple--><!-- IMPLIED Indicates This attribute is writable--><!-- redirect or forwarding--> <!-- ELEMENT actions (action)--> <!-- ELEMENT action (result*)--> (* means multiple) <!-- ATTLIST action name CDATA #REQUIRED class CDATA #REQUIRED --> <!--ATTLIST RESULT name CDATA #IMPLIED redirect (true|false) "false" -->]><framework> <!-- Test--><actions> <action name="loginAction"> <result name="success">success.jsp</result> <result name="login">index.jsp</result> </action></actions></framework>
Note: The writing specifications of spaces and <>.
The hierarchy of the node.
2. Define Action interface
Note: Excute parameters are written, requested and responded.
3. Define an actionMapping class, treat it as an action node (write the label of the action node)
Encapsulates data to the fields and results collections.
Note: Add data to the writing. (Map collection)
4. Define ActionMappingManage class to manage ActionMapping classes (actions nodes)
/* * There is more than one action node* Used to manage ActionMapping class*/public class ActionMappingManager { // Collection of actionMapping classes private Map<String,ActionMapping> maps=new HashMap<String,ActionMapping>(); public ActionMapping getActionMapping(String name) { return maps.get(name); } //Parse all configuration files under the src project//Parse after instantiation public ActionMappingManager(String[] file){ for (String filename : file) { Init(filename); } } //init initialization method//parse the xml document public void Init(String path){ try { InputStream is=this.getClass().getResourceAsStream("/"+path); //parse xml Document doc=new SAXReader().read(is); //get the root node Element root = doc.getRootElement(); //get the actions node Element actions=(Element)root.elementIterator("actions").next(); //Use the for loop to traverse all action nodes under the actions node for(Iterator<Element> action=actions.elementIterator("action");action.hasNext();) { //Get the <action> node Element actionnext = action.next(); //Get the name attribute and class attribute in the action node respectively String name = actionnext.attributeValue("name"); String classname = actionnext.attributeValue("class"); //Save the above two attributes to the ActionMapping class ActionMapping map=new ActionMapping(); mapapp.setClassname(classname); mapapp.setName(name); //Because there are multiple result nodes under an action node traversing all result nodes under the action for(Iterator<Element> result=actionnext.elementIterator("result");result.hasNext();) { //Get the result node Element resultnext = result.next(); //Extract the name attribute value of the result node and the value in the result node String resultname = resultnext.attributeValue("name"); String resultvalue=resultnext.getText(); //Save them into the double-column set in actionMapping to facilitate calling the actionMapping class (there is data in the actionMapping class!) mapp.addResult(resultname, resultvalue); System.out.println(mapp.getName()); } //Get the collection of all action nodes maps.put(mapp.getName(), map); } } catch (Exception e) { // TODO: handle exception } } }Summary:
Parse the Framework.xml configuration file through dom4j. This will obtain the root node and the actions node, and then traverse the action nodes under the actions node for loop to get the attribute values of name and class. Since there are multiple result nodes under one action node and all result nodes under the action, they are stored in the double-column set in actionMapping, and finally get the set of all action nodes.
Note: The writing of the Init method, and the writing of the ActionMappingManager with parameter groups.
5. Define the ActionManager class using reflection mechanism to obtain specific classes based on the class name of the string type.
public class ActionManager { public static Action getActionClass(String classname) { Class clazz=null; Action action=null; //Get the class loader of the current thread try { //If there is a class in the thread, directly obtain the type of the class according to the class name clazz=Thread.currentThread().getContextClassLoader().loadClass(classname); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } if(clazz==null) { try { //If there is no in the thread, then use the class.forname method to get clazz=Class.forName(classname); } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if(action==null) { try { // Convert the obtained type to action and call the parameterless constructor, which is equivalent to new to some extent, but new needs to specify the type action=(Action)clazz.newInstance(); } catch (InstantiationException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IllegalAccessException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return action; }}Node configuration for web.xml:
6. Write servlets to control the runtime (servlets, initialize all classes)
public class MyServlet extends HttpServlet { /** *You are so naughty*/ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request, response); }<br> /** *Continue to work hard*/ ActionMappingManager man=null; public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //Get ActionMapping object ActionMapping actionMapping = man.getActionMapping(getPath(request)); //Get the reflection mechanism of action interface Action action = ActionManager.getActionManager(actionMapping.getClassname()); try { String message=action.execute(request, response); String results = actionMapping.getResults(message); response.sendRedirect(results); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } /* * Get the path name of the request*/ public String getPath(HttpServletRequest request){ //Project + Request address String requestURI = request.getRequestURI(); //Project name String contextPath = request.getContextPath(); //Specific request String path = requestURI.substring(contextPath.length()); String filename = path.substring(1,path.lastIndexOf(".")); return filename; } /* *Rewrite init, program runs and loads all classes* */ @Override public void init(ServletConfig config) throws ServletException { //config object is an object of javax.servlet.ServletConfig. The function is to obtain the initialization configuration information //config.getInitParameter is the initialization parameter content of the specified name String filename = config.getInitParameter("config"); String [] filenames=null; if(filename==null){ //If it is empty, filenames=new String[]{"Framework.xml"}; }else{ //If there is other configuration parameter information, then it is stored in the array by separating filenames=filename.split(","); } //Use the init method for initialization man=new ActionMappingManager(filenames); }}Note: the level and comments of the code.
7. Define LoginAction class for testing
public class LoginAction implements Action{ @Override public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception { String name = request.getParameter("name"); String pwd = request.getParameter("pwd"); if(name.equals("1")&&pwd.equals("1")){ return SUCCESS; }else{ return LOGIN; } }}jsp code:
Realize the effect:
No matter how long the road is, you can walk step by step, and no matter how short the road is, you cannot reach it without taking a step.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.