一,中央控制器动态加载存储子控制器
分析:
1.通过之前的建模我们可以知道,configModel对象会包含config.xml中的所有子控制器信息
同时为了解决中央控制器能够动态的加载保存子控制器的信息,我们只需要引入configModel对象即可
DispatcherServlet
package com.ljj.framework;
import java.io.IOException;
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;
/**
* 中央控制器
* 主要职能:接收浏览器请求,找到对应的处理人
* @author Administrator 刘俊杰
*上午9:37:34
*/
@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet {
//private Map<String, Action> actions = new HashMap<String,Action>();
/**
* 通过建模我们可以知道,最终configModel对象会包含config.xml中的所有子控制器信息
*同时为了解决中央控制器能够动态加载保存子控制器的信息,那么我们只需要引入configModel对象即可
*/
private ConfigModel configModel;
//程序启动时,只会加载一次
@Override
public void init() throws ServletException {
// actions.put("/book", new BookAction());
// actions.put("/order", new BookAction());
try {
// 配置地址
// getInitParameter作用是 拿到web.xml中的servlet信息配置的参数
String configLocation = this.getInitParameter("configLocation");
if(configLocation == null || "".equals(configLocation)) {
configModel = ConfigModelFactory.bulid();
}else {
configModel = ConfigModelFactory.bulid(configLocation);
}
} catch (Exception e) {
// TODO Auto-generated catch block
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();
// 要拿到/book,就是最后一个/到最后一个.为止
uri=uri.substring(uri.lastIndexOf("/")
,uri.lastIndexOf("."));
// Action action = actions.get(uri);
// 相比于上一种从map集合获取子控制器,当前需要获取config.xml中的全路径名,然后反射实例化
ActionModel actionModel = configModel.pop(uri);
if(actionModel == null) {
throw new RuntimeException("action config error");
}
String type = actionModel.getType();//配置文件中的全路径名 action子控制器的全路径名
try {
Action action = (Action) Class.forName(type).newInstance();//action的实例
//因为action是bookAction而bookAction实现了ModelDriven接口
if(action instanceof ModelDriven) {
//所以可以将其进行向下转型
ModelDriven md = (ModelDriven)action;
//model指的是bookAction中的book类实例
Object model = md.getModel();
//给model中的属性赋值,要接受前端jsp传递的参数 req.getParameterMap()
//PropertyUtils.getIndexedProperty(bean, name) 从某个对象中取某个值
//将前端所有参数值封装进实体类
BeanUtils.populate(model, req.getParameterMap());
System.out.println(model);
}
// 正式调用方法前,book中的属性要被赋值
String result= action.execute(req, resp);
ForwardModel forwardModel = actionModel.pop(result);
// if(forwardModel == null) {
// throw new RuntimeException("forward config error");
// }
String path = forwardModel.getPath();
// 拿到是否需要转发的配置
boolean redirect = forwardModel.isReadirect();
if(redirect) {
// ${pageContext.request.contextPath}
resp.sendRedirect(req.getServletContext().getContextPath()+ path);
}else {
req.getRequestDispatcher(path).forward(req, resp);
}
//
} catch (Exception e) {
e.printStackTrace();
}
}
}
config.xml
<?xml version="1.0" encoding="UTF-8"?>
<config>
<action path="/book" type="com.ljj.web.BookAction">
<forward name="failed" path="/login.jsp" redirect="false" />
<forward name="success" path="/main.jsp" redirect="true" />
</action>
</config>
ConfigModel
package com.ljj.xml;
import java.util.HashMap;
import java.util.Map;
/**
* 对应标签
* @author ljj
*
*/
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.ljj.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种设计模式之工厂模式
* sessionfactory
*
* @author ljj
*
*/
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"));
//将forwardModel 赋值并添加到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;
}
}
优化后运行:
控制台打印结果:
二,参数传递封装
目前我们需要新增一个对象,需要传的参数很少只有两三个,很方便,但是如果后期需要传三十个参数,所以我们需要对属性传递封装
优化前的jsp页面
<%@ 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>目前增删改查的方法</h3>
<a href="${pageContext.request.contextPath }/book/add">增加</a>
<a href="${pageContext.request.contextPath }/book/del">删除</a>
<a href="${pageContext.request.contextPath }/book/edit">修改</a>
<a href="${pageContext.request.contextPath }/book/list">查询</a>
<!-- r
上述问题:
1、关于单个实体/表操作场景越多,需要新建的类也就越多,造成了项目中类的数量过于庞大
2、当新增了业务,除了要添加该业务对应的方法(load),同时还要改动原有的方法
3、反射相关代码、在每一个实体类对应的Servlet中都存在
4、每一个Servlets中都有doget、dopost
-->
<h3>类数量过多问题的优化</h3>
<a href="${pageContext.request.contextPath }/book.action?methodName=add">增加</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del">删除</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=edit">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=list">查询</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=load">回显</a>
<h3>订单类CRUD</h3>
<a href="${pageContext.request.contextPath }/order.action?methodName=add">增加</a>
<a href="${pageContext.request.contextPath }/order.action?methodName=del">删除</a>
<a href="${pageContext.request.contextPath }/order.action?methodName=edit">修改</a>
<a href="${pageContext.request.contextPath }/order.action?methodName=list">查询</a>
<a href="${pageContext.request.contextPath }/order.action?methodName=load">回显</a>
<h3>xx</h3>
<a href="${pageContext.request.contextPath }/book.action?methodName=add&bid=123&bname=logo&price=99">增加</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del">删除</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=edit">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=list">查询</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=load">回显</a>
</body>
</html>
BookAction
package com.ljj.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("在同样一个Servlet中调用list方法");
}
private void edit(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同样一个Servlet中调用edit方法");
}
private void del(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同样一个Servlet中调用del方法");
}
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("在同样一个Servlet中调用add方法");
}
private void load(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同样一个Servlet中调用load方法");
}
}
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 + "]";
}
}
优化后:
package com.ljj.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;
/*
* 通过之前的建模我们可以知道,configModel对象会包含config.xml中的所有子控制器信息
* 同时为了解决中央控制器能够动态的加载保存子控制器的信息,我们只需要引入configModel对象即可
*/
@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 配置错误 ");
}
//是action子控制器的全路径名
String type = actionModel.getType();
try {
//类类是反射的开始,通过子控制器的全路径名用newInstance方法得到子控制器。
Action action = (Action) Class.forName(type).newInstance();
if(action instanceof ModelDriven) {
ModelDriven md = (ModelDriven)action;
Object model = md.getModel();
//将前端所有参数值封装进实体类
BeanUtils.populate(model, req.getParameterMap());
}
// 正式调用放法,book中的属性要被赋值
// 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>参数传递封装的优化</h3>
<a href="${pageContext.request.contextPath }/book.action?methodName=add&bid=989898&bname=laoliu&price=89">增加</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=del">删除</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=edit">修改</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=list">查询</a>
<a href="${pageContext.request.contextPath }/book.action?methodName=load">回显</a>
</body>
</html>
BookAction
package com.ljj.web;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.ljj.entity.Book;
import com.ljj.framework.ActionSupport;
import com.ljj.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("在同样一个Servlet中调用list方法");
return "success";
}
private void edit(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同样一个Servlet中调用edit方法");
}
private void del(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同样一个Servlet中调用del方法");
}
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("在同样一个Servlet中调用add方法");
return "failed";
}
private void load(HttpServletRequest req, HttpServletResponse resp) {
System.out.println("在同样一个Servlet中调用load方法");
}
@Override
public Book getModel() {
return book;
}
}
三,方法执行结果优化
对方法的执行结果进行优化,如果增加成功就用转发,失败就用重定向。
DispatcherServlet
package com.ljj.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.ljj.web.BookAction;
import com.ljj.xml.ActionModel;
import com.ljj.xml.ConfigModel;
import com.ljj.xml.ConfigModelFactory;
import com.ljj.xml.ForwardModel;
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet{
// private Map<String,Action> actions = new HashMap<String,Action>();
private ConfigModel configModel;
/*
* 通过之前的建模我们可以知道,configModel对象会包含config.xml中的所有子控制器信息
* 同时为了解决中央控制器能够动态的加载保存子控制器的信息,我们只需要引入configModel对象即可
*/
@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 配置错误 ");
}
//是action子控制器的全路径名
String type = actionModel.getType();
try {
//类类是反射的开始,通过子控制器的全路径名用newInstance方法得到子控制器。
Action action = (Action) Class.forName(type).newInstance();
if(action instanceof ModelDriven) {
ModelDriven md = (ModelDriven)action;
Object model = md.getModel();
//将前端所有参数值封装进实体类
BeanUtils.populate(model, req.getParameterMap());
}
// 正式调用放法,book中的属性要被赋值
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();
}
}
}
config.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.ljj.xml;
/**
* @author ljj
*
*/
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;
}
}
执行结果
四,框架配置文件可变
DispatcherServlet
package com.ljj.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.ljj.web.BookAction;
import com.ljj.xml.ActionModel;
import com.ljj.xml.ConfigModel;
import com.ljj.xml.ConfigModelFactory;
import com.ljj.xml.ForwardModel;
//@WebServlet("*.action")
public class DispatcherServlet extends HttpServlet{
// private Map<String,Action> actions = new HashMap<String,Action>();
private ConfigModel configModel;
/*
* 通过之前的建模我们可以知道,configModel对象会包含config.xml中的所有子控制器信息
* 同时为了解决中央控制器能够动态的加载保存子控制器的信息,我们只需要引入configModel对象即可
*/
@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 配置错误 ");
}
//是action子控制器的全路径名
String type = actionModel.getType();
try {
//类类是反射的开始,通过子控制器的全路径名用newInstance方法得到子控制器。
Action action = (Action) Class.forName(type).newInstance();
if(action instanceof ModelDriven) {
ModelDriven md = (ModelDriven)action;
Object model = md.getModel();
//将前端所有参数值封装进实体类
BeanUtils.populate(model, req.getParameterMap());
}
// 正式调用放法,book中的属性要被赋值
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.ljj.framework.DispatcherServlet</servlet-class>
<init-param>
<param-name>configLocation</param-name>
<param-value>/wuyanzu.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>mvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
</web-app>
现在我们可以将config.xml配置文件改为wuyanzu.xml
总结: 经过这一期内容之后我们的代码就变得更加的灵活,减少了代码量 大大的缩短了开发事件
让我们继续加油吧!