目录
首先我们需要一个xml配置文件以及将其里面的属性进行建模 (可以参考xml建模)

1.《代码演示》
提示: (1). 通过建模可以得知,最终configModel对象包含config.xml中所有的子控制器的信息
(2). 同时为了解决中央控制器能动态加载保存控制器信息,那么我们值需要引入configModel对象即可(参考代码 private ConfigModel configModel;)
- package com.dengxiyan.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 org.apache.commons.beanutils.PropertyUtils;
-
- import com.dengxiyan.servlet.BookAction;
-
- /**
- * 中央控制器
- * 主要职能:接收浏览器请求,找到对应的处理人
- * 不处理任何业务逻辑,只接收请求
- * @author DXY
- *2022年6月24日下午5:39:23
- */
- //只要以*.action结尾的都会被接收
- //@WebServlet("*.action")
- public class DispatcherServlet extends HttpServlet{
-
- private Map<String, Action> actions = new HashMap<String, Action>();
-
-
- private ConfigModel configModel;
-
- //程序启动时值加载一次
- @Override
- public void init() throws ServletException {
- actions.put("/book", new BookAction());
- //actions.put("/order", new BookAction());
- try {
- //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
- String configLocation = this.getInitParameter("configLocation");
- System.out.println(configLocation);
-
- if(configLocation == null || "".equals(configLocation)) {
- configModel = ConfirgModelFactory.bulid();
- }
- else {
- //相当于把所有值放到configModel里面
- configModel = ConfirgModelFactory.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://location:8080/mvc/book.action?me....
- //获得请求路径
- String uri = req.getRequestURI();
- // 要拿到/book,就是最后一个/到最会一个.的位置
- uri = uri.substring(uri.lastIndexOf("/"),
- uri.lastIndexOf("."));
-
-
- //------------------------------------一,中央控制器动态加载存储空控制器-------------
- // Action action = actions.get(uri);
-
- //相比于上一种从Map集合获取子控制器,当前需要获取全路径名,然后反射实例化
- ActionModel actionModel = configModel.pop(uri);
- //判断
- if(actionModel ==null) {
- throw new RuntimeException("action 配置错误");
- }
-
-
-
- //type是Action子控制器的全路径名
- String type = actionModel.getType();
- try {
- //当下action为bookaction
- Action action = (Action) Class.forName(type).newInstance();
- //判断是否实现了接口,实现了就转型
- if(action instanceof ModelDriven) {
- //多态的使用将bookaction转换为ModelDriven
- ModelDriven md = (ModelDriven) action;
- //model指的是bookaction中的book实例
- Object model = md.getModel();
- //要给model中的属性赋值,要接受前端jsp传递过来的参数
- // PropertyUtils.getProperty(bean, name);//某一对象获取到值
-
- //将前端所有参数值封装进实体类
- BeanUtils.populate(model, req.getParameterMap());
- }
-
-
-
- //在正式调用方法前,book中的属性需要赋值
- // action.execute(req, resp);
- String result = action.execute(req, resp);
- //result里面拿的是配置文件里forwode里的值
- ForwodeModel forwodeModel = actionModel.pop(result);
- if(forwodeModel == null) {
- throw new RuntimeException("forwode配置错误");
- }
-
- //path相当于与以前/bookList...界面
- String path = forwodeModel.getPath();
- //拿到是否需要转发的配置
- boolean redirect = forwodeModel.isRedirect();
- if(redirect) {
- //重定向
- resp.sendRedirect(req.getServletContext().getContextPath() + path);
- }
- else {
- //转发
- req.getRequestDispatcher(path).forward(req, resp);
- }
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
-
-
-
- }
2. xml配置文件
- <?xml version="1.0" encoding="UTF-8"?>
- <config>
- <action path="/book" type="com.dengxiyan.servlet.BookAction">
- <forward name="success" path="/demo2.jsp" redirect="false" />
- <forward name="failed" path="/demo3.jsp" redirect="true" />
- </action>
-
-
- </config>
3.错误演示
当type和path路径不对时

action配置会抛异常

4.总结:
1. 在不改动中央控制器任何代码的情况下,依旧可以动态加载存储控制器(子控制器加在了xml配置文件里面去,这样就可以不改动中央控制器的情况下也可以加载)
2. config模型对象替代了Map集合,因为模型对象里面包含了所有的配置文件的信息,好处在于,只需要修改配置文件里的信息即可,可以不改变中央控制器的代码
1.代码演示
所谓传参,我们需要拿到属性的值,所以需要建立一个实体类(book为例)
- package com.dengxiyan.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
- }
- public Book(int bid, String bname, float price) {
- super();
- this.bid = bid;
- this.bname = bname;
- this.price = price;
- }
- @Override
- public String toString() {
- return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
- }
-
-
- }
此类为模型驱动接口
作用:接收前台jsp传递的参数,并且封装到实体类中
- package com.dengxiyan.framework;
- /**
- * @author DXY
- *
- * @param <T>2022年6月27日下午6:00:53
- */
- public interface ModelDriven<T> {
-
- //拿到将要被封装的类实例
- T getModel();
- }
前期代码演示:
存在问题:在不能保证的情况下,当值过多的之后容易出错并且代码量过大
String bid = req.getParameter("bid");
String bname = req.getParameter("bname");
String price = req.getParameter("price");
Book b = new Book();
b.setBid(Integer.parseInt(bid));
b.setBname(bname);
b.setPrice(Float.parseFloat(price));
其次,进入处理book类的子控制器
提示:book本身是没有值的,但我们是必须要拿到值的,所以我们需要实现模型驱动接口(接口里面放要处理的对象),并且实现里面的方法,实现方法后返回对象
- package com.dengxiyan.servlet;
-
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpServletResponse;
-
- import com.dengxiyan.entity.Book;
- import com.dengxiyan.framework.ActionSupport;
- import com.dengxiyan.framework.ModelDriven;
-
- public class BookAction extends ActionSupport implements ModelDriven<Book>{
-
- private Book book = new Book();
-
- private void lod(HttpServletRequest req, HttpServletResponse resp) {
- System.out.println("在同一个servlet中调用 回显");
-
- }
-
-
- private String select(HttpServletRequest req, HttpServletResponse resp) {
- System.out.println("在同一个servlet中调用 增加");
- return "success";
- }
-
-
- private void update(HttpServletRequest req, HttpServletResponse resp) {
- System.out.println("在同一个servlet中调用 修改");
-
-
- }
-
-
- private void del(HttpServletRequest req, HttpServletResponse resp) {
- System.out.println("在同一个servlet中调用 删除");
-
- }
-
-
- private String add(HttpServletRequest req, HttpServletResponse resp) {
- System.out.println("在同一个servlet中调用 查看 ");
- return "failed";
- }
-
-
- @Override
- public Book getModel() {
- // TODO Auto-generated method stub
- return book;
- }
-
- }
之后到中央控制器
补充:需要拿到全路径名,以下type为子控制器action的全路径名
代码解析:代码中的action为处理book的子控制器(bookAction)
判断是否实现了模型驱动接口,实现了就转型将bookaction转换为ModelDriven。
- //当下action为bookaction
- Action action = (Action) Class.forName(type).newInstance();
- //判断是否实现了接口,实现了就转型
- if(action instanceof ModelDriven) {
- //多态的使用将bookaction转换为ModelDriven
- ModelDriven md = (ModelDriven) action;
- //model指的是bookaction中的book实例
- Object model = md.getModel();
- //要给model中的属性赋值,要接受前端jsp传递过来的参数
- // PropertyUtils.getProperty(bean, name);//某一对象获取到值
-
- //将前端所有参数值封装进实体类
- BeanUtils.populate(model, req.getParameterMap());
- }
xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <config>
- <action path="/book" type="com.dengxiyan.servlet.BookAction">
- <forward name="success" path="/demo2.jsp" redirect="false" />
- <forward name="failed" path="/demo3.jsp" redirect="true" />
- </action>
-
-
- </config>
- package com.dengxiyan.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 org.apache.commons.beanutils.PropertyUtils;
-
- import com.dengxiyan.servlet.BookAction;
-
- /**
- * 中央控制器
- * 主要职能:接收浏览器请求,找到对应的处理人
- * 不处理任何业务逻辑,只接收请求
- * @author DXY
- *2022年6月24日下午5:39:23
- */
- //只要以*.action结尾的都会被接收
- //@WebServlet("*.action")
- public class DispatcherServlet extends HttpServlet{
-
- private Map<String, Action> actions = new HashMap<String, Action>();
-
-
- private ConfigModel configModel;
-
- //程序启动时值加载一次
- @Override
- public void init() throws ServletException {
- actions.put("/book", new BookAction());
- //actions.put("/order", new BookAction());
- try {
- //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
- String configLocation = this.getInitParameter("configLocation");
- System.out.println(configLocation);
-
- if(configLocation == null || "".equals(configLocation)) {
- configModel = ConfirgModelFactory.bulid();
- }
- else {
- //相当于把所有值放到configModel里面
- configModel = ConfirgModelFactory.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://location:8080/mvc/book.action?me....
- //获得请求路径
- String uri = req.getRequestURI();
- // 要拿到/book,就是最后一个/到最会一个.的位置
- uri = uri.substring(uri.lastIndexOf("/"),
- uri.lastIndexOf("."));
-
- // Action action = actions.get(uri);
-
- //相比于上一种从Map集合获取子控制器,当前需要获取全路径名,然后反射实例化
- ActionModel actionModel = configModel.pop(uri);
- //判断
- if(actionModel ==null) {
- throw new RuntimeException("action 配置错误");
- }
-
-
- //-------------------------------------二,参数传递封装优化------------------------------
-
- //type是Action子控制器的全路径名
- String type = actionModel.getType();
- try {
- //当下action为bookaction
- Action action = (Action) Class.forName(type).newInstance();
- //判断是否实现了接口,实现了就转型
- if(action instanceof ModelDriven) {
- //多态的使用将bookaction转换为ModelDriven
- ModelDriven md = (ModelDriven) action;
- //model指的是bookaction中的book实例
- Object model = md.getModel();
- //要给model中的属性赋值,要接受前端jsp传递过来的参数
- // PropertyUtils.getProperty(bean, name);//某一对象获取到值
-
- //将前端所有参数值封装进实体类
- BeanUtils.populate(model, req.getParameterMap());
- }
-
-
- //在正式调用方法前,book中的属性需要赋值
- // action.execute(req, resp);
- String result = action.execute(req, resp);
- //result里面拿的是配置文件里forwode里的值
- ForwodeModel forwodeModel = actionModel.pop(result);
- if(forwodeModel == null) {
- throw new RuntimeException("forwode配置错误");
- }
-
- //path相当于与以前/bookList...界面
- String path = forwodeModel.getPath();
- //拿到是否需要转发的配置
- boolean redirect = forwodeModel.isRedirect();
- if(redirect) {
- //重定向
- resp.sendRedirect(req.getServletContext().getContextPath() + path);
- }
- else {
- //转发
- req.getRequestDispatcher(path).forward(req, resp);
- }
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
-
-
-
- }
《jsp界面代码》
- <%@ page language="java" contentType="text/html; charset=UTF-8"
- pageEncoding="UTF-8"%>
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="UTF-8">
- <title>Insert title here</title>
- </head>
- <body>
-
- <h3>参数传递封装优化</h3>
- <a href="${pageContext.request.contextPath }/book.action?methodName=add&bid=9999&bname=admin&price=66">增加</a>
- <a href="${pageContext.request.contextPath }/book.action?methodName=del">删除</a>
- <a href="${pageContext.request.contextPath }/book.action?methodName=update">修改</a>
- <a href="${pageContext.request.contextPath }/book.action?methodName=select">查看</a>
- <a href="${pageContext.request.contextPath }/book.action?methodName=lod">回显</a>
-
- </body>
- </html>
《效果图》

《成功打印》

总结: 减少了代码的封装步骤
xml文件
- <?xml version="1.0" encoding="UTF-8"?>
- <config>
- <action path="/book" type="com.dengxiyan.servlet.BookAction">
- <forward name="success" path="/demo2.jsp" redirect="false" />
- <forward name="failed" path="/demo3.jsp" redirect="true" />
- </action>
-
-
- </config>
result里面拿的是配置文件里forwode里的值
- package com.dengxiyan.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 org.apache.commons.beanutils.PropertyUtils;
-
- import com.dengxiyan.servlet.BookAction;
-
- /**
- * 中央控制器
- * 主要职能:接收浏览器请求,找到对应的处理人
- * 不处理任何业务逻辑,只接收请求
- * @author DXY
- *2022年6月24日下午5:39:23
- */
- //只要以*.action结尾的都会被接收
- //@WebServlet("*.action")
- public class DispatcherServlet extends HttpServlet{
-
- private Map<String, Action> actions = new HashMap<String, Action>();
-
-
- private ConfigModel configModel;
-
- //程序启动时值加载一次
- @Override
- public void init() throws ServletException {
- actions.put("/book", new BookAction());
- //actions.put("/order", new BookAction());
- try {
- //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
- String configLocation = this.getInitParameter("configLocation");
- System.out.println(configLocation);
-
- if(configLocation == null || "".equals(configLocation)) {
- configModel = ConfirgModelFactory.bulid();
- }
- else {
- //相当于把所有值放到configModel里面
- configModel = ConfirgModelFactory.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://location:8080/mvc/book.action?me....
- //获得请求路径
- String uri = req.getRequestURI();
- // 要拿到/book,就是最后一个/到最会一个.的位置
- uri = uri.substring(uri.lastIndexOf("/"),
- uri.lastIndexOf("."));
-
-
- //------------------------------------一,中央控制器动态加载存储空控制器-------------
- // Action action = actions.get(uri);
-
- //相比于上一种从Map集合获取子控制器,当前需要获取全路径名,然后反射实例化
- ActionModel actionModel = configModel.pop(uri);
- //判断
- if(actionModel ==null) {
- throw new RuntimeException("action 配置错误");
- }
-
-
- //-------------------------------------二,参数传递封装优化------------------------------
-
- //type是Action子控制器的全路径名
- String type = actionModel.getType();
- try {
- //当下action为bookaction
- Action action = (Action) Class.forName(type).newInstance();
- //判断是否实现了接口,实现了就转型
- if(action instanceof ModelDriven) {
- //多态的使用将bookaction转换为ModelDriven
- ModelDriven md = (ModelDriven) action;
- //model指的是bookaction中的book实例
- Object model = md.getModel();
- //要给model中的属性赋值,要接受前端jsp传递过来的参数
- // PropertyUtils.getProperty(bean, name);//某一对象获取到值
-
- //将前端所有参数值封装进实体类
- BeanUtils.populate(model, req.getParameterMap());
- }
-
-
-
-
- //-------------------------------------三,对于方法执行结果转发重定向优化-----------------
-
- //在正式调用方法前,book中的属性需要赋值
- // action.execute(req, resp);
- String result = action.execute(req, resp);
- //result里面拿的是配置文件里forwode里的值
- ForwodeModel forwodeModel = actionModel.pop(result);
- if(forwodeModel == null) {
- throw new RuntimeException("forwode配置错误");
- }
-
- //path相当于与以前/bookList...界面
- String path = forwodeModel.getPath();
- //拿到是否需要转发的配置
- boolean redirect = forwodeModel.isRedirect();
- if(redirect) {
- //重定向
- resp.sendRedirect(req.getServletContext().getContextPath() + path);
- }
- else {
- //转发
- req.getRequestDispatcher(path).forward(req, resp);
- }
-
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
-
-
-
- }
在增加方法与查看方法里加上返回值,返回的值为xml里的name值
- private String select(HttpServletRequest req, HttpServletResponse resp) {
- System.out.println("在同一个servlet中调用 查看");
- return "success";
- }
- private String add(HttpServletRequest req, HttpServletResponse resp) {
-
- System.out.println("在同一个servlet中调用 增加 ");
- return "failed";
- }
抛异常是因为代码中还需要优化
就是以下代码resp.sendRedirect(path);不能直接放path 导致路径缺失
正确代码为:resp.sendRedirect(req.getServletContext().getContextPath() + path);

将所有路径都放到,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>JE22-MVC</display-name>
- <servlet>
- <servlet-name>mvc</servlet-name>
- <servlet-class>com.dengxiyan.framework.DispatcherServlet</servlet-class>
- <init-param>
- <param-name>configLocation</param-name>
- <param-value>/dengxiyan.xml</param-value>
- </init-param>
- </servlet>
- <servlet-mapping>
- <servlet-name>mvc</servlet-name>
- <url-pattern>*.action</url-pattern>
- </servlet-mapping>
- </web-app>
- package com.dengxiyan.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 org.apache.commons.beanutils.PropertyUtils;
-
- import com.dengxiyan.servlet.BookAction;
-
- /**
- * 中央控制器
- * 主要职能:接收浏览器请求,找到对应的处理人
- * 不处理任何业务逻辑,只接收请求
- * @author DXY
- *2022年6月24日下午5:39:23
- */
- //只要以*.action结尾的都会被接收
- //@WebServlet("*.action")
- public class DispatcherServlet extends HttpServlet{
-
- private Map<String, Action> actions = new HashMap<String, Action>();
-
-
- private ConfigModel configModel;
-
- //程序启动时值加载一次
- @Override
- public void init() throws ServletException {
- actions.put("/book", new BookAction());
- //actions.put("/order", new BookAction());
- try {
- //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
- String configLocation = this.getInitParameter("configLocation");
- System.out.println(configLocation);
-
- if(configLocation == null || "".equals(configLocation)) {
- configModel = ConfirgModelFactory.bulid();
- }
- else {
- //相当于把所有值放到configModel里面
- configModel = ConfirgModelFactory.bulid(configLocation);
- }
- } catch (Exception e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
判断时有一个带参数的和一个不带参数的方法,调用的是工厂模式里的方法
- package com.dengxiyan.framework;
-
- import java.io.InputStream;
- import java.rmi.activation.ActivationMonitor;
- import java.util.List;
-
- import org.dom4j.Document;
- import org.dom4j.DocumentException;
- import org.dom4j.Element;
- import org.dom4j.io.SAXReader;
-
- /**
- * 23中设计模式之工厂模式
- * ConfirgModelFactory就是用来生产对象的
- * 生产出来的ConfirgModel对象就包含了configxml中的配置内容
- *
- *
- * 此处生产ConfirgModel有配置信息?
- * 1.解析confirg.xml中的配置信息
- * 2.将对应的配置信息分别加载进行不同的模型对象中
- * @author DXY
- *2022年6月14日下午6:24:25
- */
- public class ConfirgModelFactory {
-
-
- //-------------------------------------带参数-------------------------------------------
-
- public static ConfigModel bulid(String path) throws Exception {
- //同包
- InputStream in = ConfirgModelFactory.class.getResourceAsStream(path);
- SAXReader sr = new SAXReader();
- //获得配置文件中的信息
- Document doc = sr.read(in);
- //获取所有action标签
- List<Element> actionEles = doc.selectNodes("/config/action");
- ConfigModel configModel = new ConfigModel();
-
- for (Element actionEle : actionEles) {
- ActionModel actionModel = new ActionModel();
- //将actionEle里的值存到actionModel
- actionModel.setPath(actionEle.attributeValue("path"));
- actionModel.setType(actionEle.attributeValue("type"));
- //将forwardModel赋值并添加到Actionmodel中
- List<Element> forwardEles = actionEle.selectNodes("forward");
- for (Element element : forwardEles) {
- ForwodeModel forwodeModel = new ForwodeModel();
- forwodeModel.setName(element.attributeValue("name"));
- forwodeModel.setPath(element.attributeValue("path"));
- //redirect:只能是false|true,允许空,默认值为false
- forwodeModel.setRedirect("true".equals(element.attributeValue("redirect")));
- actionModel.push(forwodeModel);
- }
- configModel.push(actionModel);
- }
- return configModel;
-
- }
-
-
- //---------------------------------不带参数---------------------------------------------
-
- public static ConfigModel bulid() throws Exception {
- String defaultPath = "/config.xml";
- return bulid(defaultPath);
- }
- }
<效果图>
将config.xml改为dengxiyan.xml同样是可以拿到xml文件的路径名并且可以跳到重定向界面

总结:使代码更灵活