Java basic custom control layer framework

Custom control layer framework core file

The core file of the control layer framework is xml file, and almost all frameworks use xml file as configuration file. web. As the core file of Java Web, xml will parse the web when the server tomcat starts xml file, read the information of servlet and servlet mapping node, store it in a map set to form the form of key:value, store the value of url in key and the value of class in value. The custom framework is a similar method. First, it parses the custom xml file (definition request name - processing object - processing result), and then stores the result in the map set (forming the corresponding mapping relationship).

Basic principles of custom control layer framework

1.web.xml file is the core file of Web project, which is responsible for the interaction between front and back ends (xml file is responsible for storing data)
2. Every time you create a servlet class, you need to go to the web Create a new pair of servlet and servlet mapping nodes in XML. This pair of nodes has the same name, url - > class
3. After the Tomcat server starts, it will XML, so in the web Configure servlet. XML Controller: load on startup = 0, that is, load upon startup. At this time, the controller will be initialized.
4. Working principle: the front end sends a request, the server receives the request name sent by the front end, and controls forwarding through the controller (get the class corresponding to the request name from the mapping relationship of the Map set, and call the reflection mechanism to instantiate POJO (traditional ordinary Java object)).

Process of customizing control layer framework

1. Define the node information of the xml file
2. Design the corresponding entity class according to the node information in the custom xml file
3. Parse the custom xml file to get the map set of entity class (bean.Action) corresponding to the "name" in the node information (such as the login request name in the following project) and the node information
4. The controller is designed to process the requests that need business processing at the front end (the interception request is handed over to the controller for processing, the request name sent by the front end matches the element information in the map, and the reflection mechanism is used to call the corresponding module to process the request.

Overall directory structure of the project

As shown in the figure

action

Each business processing module

LoginAction

package action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import framework.ActionSupport;

public class LoginAction implements ActionSupport {
	
	public String execute(HttpServletRequest request, HttpServletResponse response) {
		return "success";//login
	}
}

RegisterAction

package action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import framework.ActionSupport;

public class RegisterAction implements ActionSupport {

	@Override
	public String execute(HttpServletRequest request, HttpServletResponse response) {
		return "success";
	}

}

bean

Node information corresponding to CustomFrame

Result

package bean;

public class Result {
	private String name;
	private String path;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getPath() {
		return path;
	}
	public void setPath(String path) {
		this.path = path;
	}
}

Action

package bean;

import java.util.ArrayList;
import java.util.List;

public class Action {
	private String name;
	private String className;
	private List<Result> lr=new ArrayList<Result>();
	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 List<Result> getLr() {
		return lr;
	}
	public void setLr(List<Result> lr) {
		this.lr = lr;
	}
}

demo

For testing

framework

Define the method for action to process user requests, which is also convenient for the controller to generate class objects

ActionSupport

package framework;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public interface ActionSupport {
	String execute(HttpServletRequest request, HttpServletResponse response);
}

servlet

Using servlet to implement controller

Controller

package servlet;

import java.io.IOException;
import java.util.List;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import bean.Action;
import bean.Result;
import framework.ActionSupport;
import util.DisExecute;

public class Controller extends HttpServlet {
	/*
	 * servlet Life cycle:
	 * init--Initialization, that is, servlet class instantiation. It is initialized once and used many times
	 * For the servlet class, its initialization is accompanied by the first access
	 * service--Service. The service method can respond to the request submitted by the front end in the form of get or post
	 * detroy--end
	 */


	private static final long serialVersionUID = 1L;
    Map<String,Action> map=null;
    DisExecute de=null;
    
	@Override
	public void init(ServletConfig config) throws ServletException {
		//Initialize the method and execute it automatically when instantiating
		String path=config.getInitParameter("mvc");
		de=new DisExecute();
		map=de.execute(path);
	}
    
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String rq=request.getServletPath();					//Get the request name of the front end
		rq=rq.substring(rq.lastIndexOf("/")+1,rq.length()-3);//Here: go / go.do
		Action action=map.get(rq);							//The bean.Action class is used to store the node information of the Map collection
		try {
			ActionSupport as=(ActionSupport)Class.forName(action.getClassName()).newInstance();//Get the information in the bean.Action and generate the corresponding action.*Action object by reflection. / / because the action to be generated is not known before reflection, the action inherits ActionSupport 
			String flag=as.execute(request, response);		//Submit the processing request and get the processing result of the action
			String path=null;
			List<Result> lr=action.getLr();					//Get and return the Result set
			for(Result r:lr) {
				if(r.getName().equals(flag)) {				//Processing returned results
					path=r.getPath();						//r. Path returned by getpath() (page)
					break;
				}
			}
			request.getRequestDispatcher(path).forward(request, response);	//forward
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		this.doGet(request, response);
	}
	
}

util

DisExecute

Used to parse CustomFrame.xml

package util;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import bean.Action;
import bean.Result;

public class DisExecute {
	@SuppressWarnings("unchecked")
	public Map<String,Action> execute(String path) {
		Map<String,Action> map=new HashMap<String,Action>();		//Collection is used to store node information
		InputStream is=this.getClass().getResourceAsStream(path);//Path is the path of the configuration file to be resolved
		try {
			Document doc=new SAXReader().read(is);
			Element root=doc.getRootElement();				//Get root node
			List<Element> le=root.elements();				//Gets the child node under the root node
			for(Element e:le) {								//Each e represents a child node of the root node struts. Here, the node information is read through a loop and stored in the Map collection
				List<Element> lm=e.elements();
				for(Element m:lm) {							//Each m represents a child node of action s
					Action action=new Action();
					action.setName(m.attributeValue("name"));
					action.setClassName(m.attributeValue("className"));
					List<Element> lt=m.elements();
					for(Element t:lt) {						//Each t represents a child node result of the action
						Result r=new Result();
						r.setName(t.attributeValue("name"));
						r.setPath(t.getText());
						action.getLr().add(r);
					}
					map.put(action.getName(),action);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;
	}
}

CustomFrame.xml file

Custom xml file

<?xml version="1.0" encoding="UTF-8"?>
<custom>
  <actions>
    <action name="lg" className="action.LoginAction">
      <result name="success">index.html</result>
      <result name="login">login.html</result>
    </action>
    <action name="rg" className="action.RegisterAction">
      <result name="success">login.html</result>
      <result name="input">register.html</result>
    </action>
  </actions>
</custom>

web.xml file

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>Day1115</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  <servlet>
    <servlet-name>controller</servlet-name>
    <servlet-class>servlet.Controller</servlet-class>
    <init-param><!-- Design of initialization parameters -->
      <param-name>mvc</param-name>
      <param-value>/CustomFrame.xml</param-value>
    </init-param>
    <!-- Load on startup -->
    <load-on-startup>0</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>controller</servlet-name>
     <!-- All with.do The end requests are forwarded by the controller-->
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

register.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>register</title>
</head>
<body>
	<h4>Register</h4>
	<form action="rg.do" method="post">
                  username:<input type="text" name="user.name"/><br/>
                  password:<input type="text" name="user.password"/><br/>
                  <input type="submit" value="register"/>
                  <input type="reset" value="cancel"/><br/>
         <a href="login.html">Existing account</a>
    </form>
</body>
</html>

login.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<center>
    <h4>User Login</h4>
    <form action="lg.do" method="post">
                  username:<input type="text" name="user.name"/><br/>
                  password:<input type="text" name="user.password"/><br/>
                  <input type="submit" value="login"/>
                  <input type="reset" value="cancel"/>
    </form>
  </center>
</body>
</html>

index.html file

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Index</title>
</head>
<body>
	<form action="" method="post">
		<h4>You are welcome!</h4>
	</form>
</body>
</html>

Keywords: Java Eclipse Tomcat Java framework

Added by jeevan_y21 on Fri, 10 Dec 2021 13:49:46 +0200