当前位置:网站首页>Simple custom MVC optimization
Simple custom MVC optimization
2022-06-30 03:05:00 【An Li Jiu Ge】
Preface
This article follows an article , The last article shared a simple customization MVC. This article is about sharing customization MVC Optimize .
One 、 The central controller dynamically loads and stores the sub controller
We customize MVC Finally, export it to jar package , What if we add a sub controller , Du Daocheng jar package .
Here we will use the content shared before XML.
Through the previous modeling, we can know ,configModel The object will contain config.xml All sub controller information in
At the same time, in order to solve the problem that the central controller can dynamically load and save the information of sub controllers , We just need to introduce configModel Object can
DispatcherServlet
package com.zhw.framework;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhw.web.BookAction;
import com.zhw.xml.ActionModel;
import com.zhw.xml.ConfigModel;
import com.zhw.xml.ConfigModelFactory;
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet{
// private Map<String,Action> actions = new HashMap<String,Action>();
private ConfigModel configModel;
/*
* Through the previous modeling, we can know ,configModel The object will contain config.xml All sub controller information in
* At the same time, in order to solve the problem that the central controller can dynamically load and save the information of sub controllers , We just need to introduce configModel Object can
*/
@Override
public void init() throws ServletException {
// actions.put("/book",new BookAction());
// actions.put("/order",new BookAction());
try {
configModel = ConfigModelFactory.bulid();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//http://localhost:8080/mvc/book.action?methodName=list
String uri = req.getRequestURI();
uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
// Action action = actions.get(uri);
// action.execute(req, resp);
//
ActionModel actionModel = configModel.pop(uri);
if(actionModel == null) {
throw new RuntimeException("action Configuration error ");
}
// yes action Full pathname of the sub controller
String type = actionModel.getType();
try {
// Class class is the beginning of reflection , Through the full pathname of the sub controller, use newInstance Method to get the sub controller .
Action action = (Action) Class.forName(type).newInstance();
} catch (Exception e) {
e.printStackTrace();
}
}
}
config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.zhw.web.BookAction">
<forward name="failed" path="/login.jsp" redirect="false" />
<forward name="success" path="/main.jsp" redirect="true" />
</action>
</config>ConfigModel
package com.zhw.xml;
import java.util.HashMap;
import java.util.Map;
/**
* Corresponding label
* @author zhw
*
*/
public class ConfigModel {
private Map<String,ActionModel> aMap = new HashMap<String,ActionModel>();
public void push(ActionModel actionModel) {
aMap.put(actionModel.getPath(), actionModel);
}
public ActionModel pop(String path) {
return aMap.get(path);
}
}
ConfigModelFactory
package com.zhw.xml;
import java.io.InputStream;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
/**
* 23 Factory mode of design mode
* sessionfactory
*
* @author zhw
*
*/
public class ConfigModelFactory {
public static ConfigModel bulid() throws Exception {
String defaultPath = "/config.xml";
InputStream in = ConfigModelFactory.class.getResourceAsStream(defaultPath);
SAXReader s = new SAXReader();
Document doc = s.read(in);
ConfigModel configModel = new ConfigModel();
List<Element> actionEles = doc.selectNodes("/config/action");
for (Element ele : actionEles) {
ActionModel actionModel = new ActionModel();
actionModel.setPath(ele.attributeValue("path"));
actionModel.setType(ele.attributeValue("type"));
// take forwardModel Assign and add to ActionModel
List<Element> forwardEles = ele.selectNodes("forward");
for (Element fele : forwardEles) {
ForwardModel forwardModel = new ForwardModel();
forwardModel.setName(fele.attributeValue("name"));
forwardModel.setPath(fele.attributeValue("path"));
forwardModel.setRedirect("true".equals(fele.attributeValue("redirect")));
actionModel.push(forwardModel);
}
configModel.push(actionModel);
}
return configModel;
}
}
Run after optimization :


Two 、 Parameter passing encapsulation
Suppose we need to add a new book , What needs to be transferred is the book number , Book name , Book price . Three parameters , Very convenient , But if you need to pass 30 parameters ? For this question , Encapsulate parameter passing
Before optimization :
Demo
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3> At present, the method of adding, deleting, modifying and checking </h3>
<a href="${pageContext.request.contextPath }/book/add"> increase </a>
<a href="${pageContext.request.contextPath }/book/del"> Delete </a>
<a href="${pageContext.request.contextPath }/book/edit"> modify </a>
<a href="${pageContext.request.contextPath }/book/list"> Inquire about </a>
<!-- r
The above problems :
1、 About a single entity / The more table operation scenarios , The more classes you need to create , As a result, the number of classes in the project is too large
2、 When new business is added , In addition to adding the method corresponding to the business (load), At the same time, the original method should be changed
3、 Reflection related code 、 In each entity class corresponding to Servlet There's always
4、 every last Servlets There are doget、dopost
-->
<h3> Optimization of problems with too many classes </h3>
<a href="${pageContext.request.contextPath }/book.action?methodName=add"> increase </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del"> Delete </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=edit"> modify </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=list"> Inquire about </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=load"> The echo </a>
<h3> Order class CRUD</h3>
<a href="${pageContext.request.contextPath }/order.action?methodName=add"> increase </a>
<a href="${pageContext.request.contextPath }/order.action?methodName=del"> Delete </a>
<a href="${pageContext.request.contextPath }/order.action?methodName=edit"> modify </a>
<a href="${pageContext.request.contextPath }/order.action?methodName=list"> Inquire about </a>
<a href="${pageContext.request.contextPath }/order.action?methodName=load"> The echo </a>
<h3>xx</h3>
<a href="${pageContext.request.contextPath }/book.action?methodName=add&bid=123&bname=logo&price=99"> increase </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del"> Delete </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=edit"> modify </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=list"> Inquire about </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=load"> The echo </a>
</body>
</html>BookAction
package com.zhw.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhw.entity.Book;
import com.zhw.framework.ActionSupport;
public class BookAction extends ActionSupport{
private void list(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in list Method ");
}
private void edit(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in edit Method ");
}
private void del(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in del Method ");
}
private void add(HttpServletRequest req, HttpServletResponse resp) {
String bid = req.getParameter("bid");
String bname = req.getParameter("bname");
String price = req.getParameter("price");
Book book = new Book();
book.setBid(Integer.valueOf(bid));
book.setBname(bname);
book.setPrice(Float.valueOf(price));
System.out.println(" In the same Servlet Call in add Method ");
}
private void load(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in load Method ");
}
}
Book
package com.zhw.entity;
public class Book {
private int bid;
private String bname;
private float price;
public int getBid() {
return bid;
}
public void setBid(int bid) {
this.bid = bid;
}
public String getBname() {
return bname;
}
public void setBname(String bname) {
this.bname = bname;
}
public float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public Book() {
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
}
}
After optimization :
DispatcherServlet
package com.zhw.framework;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.zhw.web.BookAction;
import com.zhw.xml.ActionModel;
import com.zhw.xml.ConfigModel;
import com.zhw.xml.ConfigModelFactory;
import com.zhw.xml.ForwardModel;
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet{
// private Map<String,Action> actions = new HashMap<String,Action>();
private ConfigModel configModel;
/*
* Through the previous modeling, we can know ,configModel The object will contain config.xml All sub controller information in
* At the same time, in order to solve the problem that the central controller can dynamically load and save the information of sub controllers , We just need to introduce configModel Object can
*/
@Override
public void init() throws ServletException {
// actions.put("/book",new BookAction());
// actions.put("/order",new BookAction());
try {
String configLocation = this.getInitParameter("configLocation");
if(configLocation == null ||"".equals(configLocation)) {
}
configModel = ConfigModelFactory.bulid();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//http://localhost:8080/mvc/book.action?methodName=list
String uri = req.getRequestURI();
uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
// Action action = actions.get(uri);
// action.execute(req, resp);
//
ActionModel actionModel = configModel.pop(uri);
if(actionModel == null) {
throw new RuntimeException("action Configuration error ");
}
// yes action Full pathname of the sub controller
String type = actionModel.getType();
try {
// Class class is the beginning of reflection , Through the full pathname of the sub controller, use newInstance Method to get the sub controller .
Action action = (Action) Class.forName(type).newInstance();
if(action instanceof ModelDriven) {
ModelDriven md = (ModelDriven)action;
Object model = md.getModel();
// Encapsulate all front-end parameter values into entity classes
BeanUtils.populate(model, req.getParameterMap());
}
// Formal call and release ,book The attributes in the are assigned
// action.execute(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Demo
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h3> Optimization of parameter passing encapsulation </h3>
<a href="${pageContext.request.contextPath }/book.action?methodName=add&bid=989898&bname=laoliu&price=89"> increase </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del"> Delete </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=edit"> modify </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=list"> Inquire about </a>
<a href="${pageContext.request.contextPath }/book.action?methodName=load"> The echo </a>
</body>
</html>BookAction
package com.zhw.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.zhw.entity.Book;
import com.zhw.framework.ActionSupport;
import com.zhw.framework.ModelDriven;
public class BookAction extends ActionSupport implements ModelDriven<Book>{
private Book book = new Book();
private String list(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in list Method ");
return "success";
}
private void edit(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in edit Method ");
}
private void del(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in del Method ");
}
private String add(HttpServletRequest req, HttpServletResponse resp) {
// String bid = req.getParameter("bid");
// String bname = req.getParameter("bname");
// String price = req.getParameter("price");
// Book book = new Book();
// book.setBid(Integer.valueOf(bid));
// book.setBname(bname);
// book.setPrice(Float.valueOf(price));
System.out.println(" In the same Servlet Call in add Method ");
return "failed";
}
private void load(HttpServletRequest req, HttpServletResponse resp) {
System.out.println(" In the same Servlet Call in load Method ");
}
@Override
public Book getModel() {
return book;
}
}
3、 ... and 、 Method to perform result optimization
Optimize the execution results of the method , If the addition is successful, use forwarding , If you fail, redirect .
DispatcherServlet
package com.zhw.framework;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.zhw.web.BookAction;
import com.zhw.xml.ActionModel;
import com.zhw.xml.ConfigModel;
import com.zhw.xml.ConfigModelFactory;
import com.zhw.xml.ForwardModel;
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet{
// private Map<String,Action> actions = new HashMap<String,Action>();
private ConfigModel configModel;
/*
* Through the previous modeling, we can know ,configModel The object will contain config.xml All sub controller information in
* At the same time, in order to solve the problem that the central controller can dynamically load and save the information of sub controllers , We just need to introduce configModel Object can
*/
@Override
public void init() throws ServletException {
// actions.put("/book",new BookAction());
// actions.put("/order",new BookAction());
try {
String configLocation = this.getInitParameter("configLocation");
if(configLocation == null ||"".equals(configLocation)) {
}
configModel = ConfigModelFactory.bulid();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//http://localhost:8080/mvc/book.action?methodName=list
String uri = req.getRequestURI();
uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
// Action action = actions.get(uri);
// action.execute(req, resp);
//
ActionModel actionModel = configModel.pop(uri);
if(actionModel == null) {
throw new RuntimeException("action Configuration error ");
}
// yes action Full pathname of the sub controller
String type = actionModel.getType();
try {
// Class class is the beginning of reflection , Through the full pathname of the sub controller, use newInstance Method to get the sub controller .
Action action = (Action) Class.forName(type).newInstance();
if(action instanceof ModelDriven) {
ModelDriven md = (ModelDriven)action;
Object model = md.getModel();
// Encapsulate all front-end parameter values into entity classes
BeanUtils.populate(model, req.getParameterMap());
}
// Formal call and release ,book The attributes in the are assigned
action.execute(req, resp);
String result = action.execute(req, resp);
ForwardModel forwardModel = actionModel.pop(result);
boolean redirect = forwardModel.isRedirect();
if(forwardModel == null) {
throw new RuntimeException("forward config error");
}
String path = forwardModel.getPath();
if(redirect)
resp.sendRedirect(req.getServletContext().getContextPath()+path);
else
req.getRequestDispatcher(path).forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.zhw.web.BookAction">
<forward name="success" path="/Demo2.jsp" redirect="false" />
<forward name="failed" path="/Demo3.jsp" redirect="true" />
</action>
</config>forwardModel
package com.zhw.xml;
/**
* @author zhw
*
*/
public class ForwardModel {
// <forward name="failed" path="/reg.jsp" redirect="false" />
private String name;
private String path;
private Boolean redirect;
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;
}
public Boolean getRedirect() {
return redirect;
}
public void setRedirect(Boolean redirect) {
this.redirect = redirect;
}
public boolean isRedirect() {
return redirect;
}
}


Four 、 The framework configuration file is variable
DispatcherServlet
package com.zhw.framework;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.beanutils.BeanUtils;
import com.zhw.web.BookAction;
import com.zhw.xml.ActionModel;
import com.zhw.xml.ConfigModel;
import com.zhw.xml.ConfigModelFactory;
import com.zhw.xml.ForwardModel;
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet{
// private Map<String,Action> actions = new HashMap<String,Action>();
private ConfigModel configModel;
/*
* Through the previous modeling, we can know ,configModel The object will contain config.xml All sub controller information in
* At the same time, in order to solve the problem that the central controller can dynamically load and save the information of sub controllers , We just need to introduce configModel Object can
*/
@Override
public void init() throws ServletException {
// actions.put("/book",new BookAction());
// actions.put("/order",new BookAction());
try {
String configLocation = this.getInitParameter("configLocation");
if(configLocation == null ||"".equals(configLocation)) {
}
configModel = ConfigModelFactory.bulid();
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//http://localhost:8080/mvc/book.action?methodName=list
String uri = req.getRequestURI();
uri = uri.substring(uri.lastIndexOf("/"), uri.lastIndexOf("."));
// Action action = actions.get(uri);
// action.execute(req, resp);
//
ActionModel actionModel = configModel.pop(uri);
if(actionModel == null) {
throw new RuntimeException("action Configuration error ");
}
// yes action Full pathname of the sub controller
String type = actionModel.getType();
try {
// Class class is the beginning of reflection , Through the full pathname of the sub controller, use newInstance Method to get the sub controller .
Action action = (Action) Class.forName(type).newInstance();
if(action instanceof ModelDriven) {
ModelDriven md = (ModelDriven)action;
Object model = md.getModel();
// Encapsulate all front-end parameter values into entity classes
BeanUtils.populate(model, req.getParameterMap());
}
// Formal call and release ,book The attributes in the are assigned
action.execute(req, resp);
String result = action.execute(req, resp);
ForwardModel forwardModel = actionModel.pop(result);
boolean redirect = forwardModel.isRedirect();
if(forwardModel == null) {
throw new RuntimeException("forward config error");
}
String path = forwardModel.getPath();
if(redirect)
resp.sendRedirect(req.getServletContext().getContextPath()+path);
else
req.getRequestDispatcher(path).forward(req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>ss</display-name>
<servlet>
<servlet-name>mvc</servlet-name>
<servlet-class>com.zhw.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>configLocation</param-name>
<param-value>laoliu</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>take config.xml Change it to laoliu.xml
summary
In the last simple customization mvc after , We optimized this , After optimization, the amount of code is reduced , Shorten development time .
The content of this time is shared here . If there is a mistake , I hope you can correct me. .
边栏推荐
- Simulate activity startup mode in compose
- golang bilibili直播彈幕姬
- How does native JS generate Jiugong lattice
- Three solutions to forced hibernation of corporate computers
- 广播模块代码在autojs4.1.1版本运行正常,但在pro7.0版本上运行报错(未解决)
- 怎样的外汇交易平台是有监管的,是安全的?
- How do I enable assembly binding logging- How can I enable Assembly binding logging?
- Template parameter package and function parameter package
- The rigorous judgment of ID number is accurate to the last place in the team
- How to realize remote collaborative office, keep this strategy!
猜你喜欢

Software testing skills, JMeter stress testing tutorial, transaction controller of logic controller (25)

中断操作:AbortController学习笔记

Interrupt operation: abortcontroller learning notes

福利抽奖 | 开源企业级监控Zabbix6.0都有哪些亮点

公司电脑强制休眠的3种解决方案

Raki's notes on reading paper: discontinuous named entity recognition as maximum clique discovery

Prompt learning a blood case caused by a space

Wechat applet page Jump and parameter transfer

通用分页(2)

The MariaDB database was found 12 hours late
随机推荐
如何实现远程协同办公,收好这份攻略!
公司电脑强制休眠的3种解决方案
华为面试题: 高矮个子排队
[oiclass] chess piece
The rigorous judgment of ID number is accurate to the last place in the team
发现mariadb数据库时间晚了12个小时
Heavy attack -- ue5's open source digital twin solution
Visual HTA form designer htamaker interface introduction and usage, Download | HTA VBS visual script writing
Call collections Sort() method, compare two person objects (by age ratio first, and by name ratio for the same age), and pass lambda expression as a parameter.
Interrupt operation: abortcontroller learning notes
在php中字符串的概念是什么
threejs 镜子案例Reflector 创建镜子+房子搭建+小球移动
mysql 主从数据库同步失败的原因
The MariaDB database was found 12 hours late
shell统计某个字符串最后一次出现的位置之前的所有字符串
Federal learning: dividing non IID samples by Dirichlet distribution
HTA入门基础教程 | VBS脚本的GUI界面 HTA简明教程 ,附带完整历程及界面美化
重磅来袭--UE5的开源数字孪生解决方案
可视化HTA窗体设计器-HtaMaker 界面介绍及使用方法,下载 | HTA VBS可视化脚本编写
通用分页(2)