• 自定义MVC框架


    目录

    一,怎样让中央控制器动态加载存储空控制器

    二,参数传递封装优化

    三,对于方法执行结果转发重定向优化

    四,框架配置文件可变


    一,怎样让中央控制器动态加载存储空控制器

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

    1.《代码演示》


        提示: (1). 通过建模可以得知,最终configModel对象包含config.xml中所有的子控制器的信息
         (2). 同时为了解决中央控制器能动态加载保存控制器信息,那么我们值需要引入configModel对象即可(参考代码    private ConfigModel configModel;)

        

    1. package com.dengxiyan.framework;
    2. import java.io.IOException;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import org.apache.commons.beanutils.BeanUtils;
    11. import org.apache.commons.beanutils.PropertyUtils;
    12. import com.dengxiyan.servlet.BookAction;
    13. /**
    14. * 中央控制器
    15. * 主要职能:接收浏览器请求,找到对应的处理人
    16. * 不处理任何业务逻辑,只接收请求
    17. * @author DXY
    18. *2022年6月24日下午5:39:23
    19. */
    20. //只要以*.action结尾的都会被接收
    21. //@WebServlet("*.action")
    22. public class DispatcherServlet extends HttpServlet{
    23. private Map<String, Action> actions = new HashMap<String, Action>();
    24. private ConfigModel configModel;
    25. //程序启动时值加载一次
    26. @Override
    27. public void init() throws ServletException {
    28. actions.put("/book", new BookAction());
    29. //actions.put("/order", new BookAction());
    30. try {
    31. //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
    32. String configLocation = this.getInitParameter("configLocation");
    33. System.out.println(configLocation);
    34. if(configLocation == null || "".equals(configLocation)) {
    35. configModel = ConfirgModelFactory.bulid();
    36. }
    37. else {
    38. //相当于把所有值放到configModel里面
    39. configModel = ConfirgModelFactory.bulid(configLocation);
    40. }
    41. } catch (Exception e) {
    42. // TODO Auto-generated catch block
    43. e.printStackTrace();
    44. }
    45. }
    46. @Override
    47. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    48. doPost(req, resp);
    49. }
    50. @Override
    51. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    52. //http://location:8080/mvc/book.action?me....
    53. //获得请求路径
    54. String uri = req.getRequestURI();
    55. // 要拿到/book,就是最后一个/到最会一个.的位置
    56. uri = uri.substring(uri.lastIndexOf("/"),
    57. uri.lastIndexOf("."));
    58. //------------------------------------一,中央控制器动态加载存储空控制器-------------
    59. // Action action = actions.get(uri);
    60. //相比于上一种从Map集合获取子控制器,当前需要获取全路径名,然后反射实例化
    61. ActionModel actionModel = configModel.pop(uri);
    62. //判断
    63. if(actionModel ==null) {
    64. throw new RuntimeException("action 配置错误");
    65. }
    66. //type是Action子控制器的全路径名
    67. String type = actionModel.getType();
    68. try {
    69. //当下action为bookaction
    70. Action action = (Action) Class.forName(type).newInstance();
    71. //判断是否实现了接口,实现了就转型
    72. if(action instanceof ModelDriven) {
    73. //多态的使用将bookaction转换为ModelDriven
    74. ModelDriven md = (ModelDriven) action;
    75. //model指的是bookaction中的book实例
    76. Object model = md.getModel();
    77. //要给model中的属性赋值,要接受前端jsp传递过来的参数
    78. // PropertyUtils.getProperty(bean, name);//某一对象获取到值
    79. //将前端所有参数值封装进实体类
    80. BeanUtils.populate(model, req.getParameterMap());
    81. }
    82. //在正式调用方法前,book中的属性需要赋值
    83. // action.execute(req, resp);
    84. String result = action.execute(req, resp);
    85. //result里面拿的是配置文件里forwode里的值
    86. ForwodeModel forwodeModel = actionModel.pop(result);
    87. if(forwodeModel == null) {
    88. throw new RuntimeException("forwode配置错误");
    89. }
    90. //path相当于与以前/bookList...界面
    91. String path = forwodeModel.getPath();
    92. //拿到是否需要转发的配置
    93. boolean redirect = forwodeModel.isRedirect();
    94. if(redirect) {
    95. //重定向
    96. resp.sendRedirect(req.getServletContext().getContextPath() + path);
    97. }
    98. else {
    99. //转发
    100. req.getRequestDispatcher(path).forward(req, resp);
    101. }
    102. } catch (Exception e) {
    103. // TODO Auto-generated catch block
    104. e.printStackTrace();
    105. }
    106. }
    107. }

    2. xml配置文件

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <config>
    3. <action path="/book" type="com.dengxiyan.servlet.BookAction">
    4. <forward name="success" path="/demo2.jsp" redirect="false" />
    5. <forward name="failed" path="/demo3.jsp" redirect="true" />
    6. </action>
    7. </config>

    3.错误演示

     当type和path路径不对时

    action配置会抛异常 

     

    4.总结:

    1. 在不改动中央控制器任何代码的情况下,依旧可以动态加载存储控制器(子控制器加在了xml配置文件里面去,这样就可以不改动中央控制器的情况下也可以加载)
       

    2. config模型对象替代了Map集合,因为模型对象里面包含了所有的配置文件的信息,好处在于,只需要修改配置文件里的信息即可,可以不改变中央控制器的代码

    二,参数传递封装优化

    1.代码演示

    所谓传参,我们需要拿到属性的值,所以需要建立一个实体类(book为例)

    1. package com.dengxiyan.entity;
    2. public class Book {
    3. private int bid;
    4. private String bname;
    5. private float price;
    6. public int getBid() {
    7. return bid;
    8. }
    9. public void setBid(int bid) {
    10. this.bid = bid;
    11. }
    12. public String getBname() {
    13. return bname;
    14. }
    15. public void setBname(String bname) {
    16. this.bname = bname;
    17. }
    18. public float getPrice() {
    19. return price;
    20. }
    21. public void setPrice(float price) {
    22. this.price = price;
    23. }
    24. public Book() {
    25. // TODO Auto-generated constructor stub
    26. }
    27. public Book(int bid, String bname, float price) {
    28. super();
    29. this.bid = bid;
    30. this.bname = bname;
    31. this.price = price;
    32. }
    33. @Override
    34. public String toString() {
    35. return "Book [bid=" + bid + ", bname=" + bname + ", price=" + price + "]";
    36. }
    37. }

    此类为模型驱动接口

    作用:接收前台jsp传递的参数,并且封装到实体类中

    1. package com.dengxiyan.framework;
    2. /**
    3. * @author DXY
    4. *
    5. * @param <T>2022年6月27日下午6:00:53
    6. */
    7. public interface ModelDriven<T> {
    8. //拿到将要被封装的类实例
    9. T getModel();
    10. }

    前期代码演示:

            存在问题:在不能保证的情况下,当值过多的之后容易出错并且代码量过大

            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本身是没有值的,但我们是必须要拿到值的,所以我们需要实现模型驱动接口(接口里面放要处理的对象),并且实现里面的方法,实现方法后返回对象

    1. package com.dengxiyan.servlet;
    2. import javax.servlet.http.HttpServletRequest;
    3. import javax.servlet.http.HttpServletResponse;
    4. import com.dengxiyan.entity.Book;
    5. import com.dengxiyan.framework.ActionSupport;
    6. import com.dengxiyan.framework.ModelDriven;
    7. public class BookAction extends ActionSupport implements ModelDriven<Book>{
    8. private Book book = new Book();
    9. private void lod(HttpServletRequest req, HttpServletResponse resp) {
    10. System.out.println("在同一个servlet中调用 回显");
    11. }
    12. private String select(HttpServletRequest req, HttpServletResponse resp) {
    13. System.out.println("在同一个servlet中调用 增加");
    14. return "success";
    15. }
    16. private void update(HttpServletRequest req, HttpServletResponse resp) {
    17. System.out.println("在同一个servlet中调用 修改");
    18. }
    19. private void del(HttpServletRequest req, HttpServletResponse resp) {
    20. System.out.println("在同一个servlet中调用 删除");
    21. }
    22. private String add(HttpServletRequest req, HttpServletResponse resp) {
    23. System.out.println("在同一个servlet中调用 查看 ");
    24. return "failed";
    25. }
    26. @Override
    27. public Book getModel() {
    28. // TODO Auto-generated method stub
    29. return book;
    30. }
    31. }

    之后到中央控制器

    补充:需要拿到全路径名,以下type为子控制器action的全路径名

    代码解析:代码中的action为处理book的子控制器(bookAction)

    判断是否实现了模型驱动接口,实现了就转型将bookaction转换为ModelDriven。

    1. //当下action为bookaction
    2. Action action = (Action) Class.forName(type).newInstance();
    3. //判断是否实现了接口,实现了就转型
    4. if(action instanceof ModelDriven) {
    5. //多态的使用将bookaction转换为ModelDriven
    6. ModelDriven md = (ModelDriven) action;
    7. //model指的是bookaction中的book实例
    8. Object model = md.getModel();
    9. //要给model中的属性赋值,要接受前端jsp传递过来的参数
    10. // PropertyUtils.getProperty(bean, name);//某一对象获取到值
    11. //将前端所有参数值封装进实体类
    12. BeanUtils.populate(model, req.getParameterMap());
    13. }

    xml文件 

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <config>
    3. <action path="/book" type="com.dengxiyan.servlet.BookAction">
    4. <forward name="success" path="/demo2.jsp" redirect="false" />
    5. <forward name="failed" path="/demo3.jsp" redirect="true" />
    6. </action>
    7. </config>
    1. package com.dengxiyan.framework;
    2. import java.io.IOException;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import org.apache.commons.beanutils.BeanUtils;
    11. import org.apache.commons.beanutils.PropertyUtils;
    12. import com.dengxiyan.servlet.BookAction;
    13. /**
    14. * 中央控制器
    15. * 主要职能:接收浏览器请求,找到对应的处理人
    16. * 不处理任何业务逻辑,只接收请求
    17. * @author DXY
    18. *2022年6月24日下午5:39:23
    19. */
    20. //只要以*.action结尾的都会被接收
    21. //@WebServlet("*.action")
    22. public class DispatcherServlet extends HttpServlet{
    23. private Map<String, Action> actions = new HashMap<String, Action>();
    24. private ConfigModel configModel;
    25. //程序启动时值加载一次
    26. @Override
    27. public void init() throws ServletException {
    28. actions.put("/book", new BookAction());
    29. //actions.put("/order", new BookAction());
    30. try {
    31. //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
    32. String configLocation = this.getInitParameter("configLocation");
    33. System.out.println(configLocation);
    34. if(configLocation == null || "".equals(configLocation)) {
    35. configModel = ConfirgModelFactory.bulid();
    36. }
    37. else {
    38. //相当于把所有值放到configModel里面
    39. configModel = ConfirgModelFactory.bulid(configLocation);
    40. }
    41. } catch (Exception e) {
    42. // TODO Auto-generated catch block
    43. e.printStackTrace();
    44. }
    45. }
    46. @Override
    47. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    48. doPost(req, resp);
    49. }
    50. @Override
    51. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    52. //http://location:8080/mvc/book.action?me....
    53. //获得请求路径
    54. String uri = req.getRequestURI();
    55. // 要拿到/book,就是最后一个/到最会一个.的位置
    56. uri = uri.substring(uri.lastIndexOf("/"),
    57. uri.lastIndexOf("."));
    58. // Action action = actions.get(uri);
    59. //相比于上一种从Map集合获取子控制器,当前需要获取全路径名,然后反射实例化
    60. ActionModel actionModel = configModel.pop(uri);
    61. //判断
    62. if(actionModel ==null) {
    63. throw new RuntimeException("action 配置错误");
    64. }
    65. //-------------------------------------二,参数传递封装优化------------------------------
    66. //type是Action子控制器的全路径名
    67. String type = actionModel.getType();
    68. try {
    69. //当下action为bookaction
    70. Action action = (Action) Class.forName(type).newInstance();
    71. //判断是否实现了接口,实现了就转型
    72. if(action instanceof ModelDriven) {
    73. //多态的使用将bookaction转换为ModelDriven
    74. ModelDriven md = (ModelDriven) action;
    75. //model指的是bookaction中的book实例
    76. Object model = md.getModel();
    77. //要给model中的属性赋值,要接受前端jsp传递过来的参数
    78. // PropertyUtils.getProperty(bean, name);//某一对象获取到值
    79. //将前端所有参数值封装进实体类
    80. BeanUtils.populate(model, req.getParameterMap());
    81. }
    82. //在正式调用方法前,book中的属性需要赋值
    83. // action.execute(req, resp);
    84. String result = action.execute(req, resp);
    85. //result里面拿的是配置文件里forwode里的值
    86. ForwodeModel forwodeModel = actionModel.pop(result);
    87. if(forwodeModel == null) {
    88. throw new RuntimeException("forwode配置错误");
    89. }
    90. //path相当于与以前/bookList...界面
    91. String path = forwodeModel.getPath();
    92. //拿到是否需要转发的配置
    93. boolean redirect = forwodeModel.isRedirect();
    94. if(redirect) {
    95. //重定向
    96. resp.sendRedirect(req.getServletContext().getContextPath() + path);
    97. }
    98. else {
    99. //转发
    100. req.getRequestDispatcher(path).forward(req, resp);
    101. }
    102. } catch (Exception e) {
    103. // TODO Auto-generated catch block
    104. e.printStackTrace();
    105. }
    106. }
    107. }

    《jsp界面代码》

    1. <%@ page language="java" contentType="text/html; charset=UTF-8"
    2. pageEncoding="UTF-8"%>
    3. <!DOCTYPE html>
    4. <html>
    5. <head>
    6. <meta charset="UTF-8">
    7. <title>Insert title here</title>
    8. </head>
    9. <body>
    10. <h3>参数传递封装优化</h3>
    11. <a href="${pageContext.request.contextPath }/book.action?methodName=add&bid=9999&bname=admin&price=66">增加</a>
    12. <a href="${pageContext.request.contextPath }/book.action?methodName=del">删除</a>
    13. <a href="${pageContext.request.contextPath }/book.action?methodName=update">修改</a>
    14. <a href="${pageContext.request.contextPath }/book.action?methodName=select">查看</a>
    15. <a href="${pageContext.request.contextPath }/book.action?methodName=lod">回显</a>
    16. </body>
    17. </html>

    《效果图》

    《成功打印》

     

    总结: 减少了代码的封装步骤

    三,对于方法执行结果转发重定向优化

     xml文件

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <config>
    3. <action path="/book" type="com.dengxiyan.servlet.BookAction">
    4. <forward name="success" path="/demo2.jsp" redirect="false" />
    5. <forward name="failed" path="/demo3.jsp" redirect="true" />
    6. </action>
    7. </config>

    result里面拿的是配置文件里forwode里的值 

    1. package com.dengxiyan.framework;
    2. import java.io.IOException;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import org.apache.commons.beanutils.BeanUtils;
    11. import org.apache.commons.beanutils.PropertyUtils;
    12. import com.dengxiyan.servlet.BookAction;
    13. /**
    14. * 中央控制器
    15. * 主要职能:接收浏览器请求,找到对应的处理人
    16. * 不处理任何业务逻辑,只接收请求
    17. * @author DXY
    18. *2022年6月24日下午5:39:23
    19. */
    20. //只要以*.action结尾的都会被接收
    21. //@WebServlet("*.action")
    22. public class DispatcherServlet extends HttpServlet{
    23. private Map<String, Action> actions = new HashMap<String, Action>();
    24. private ConfigModel configModel;
    25. //程序启动时值加载一次
    26. @Override
    27. public void init() throws ServletException {
    28. actions.put("/book", new BookAction());
    29. //actions.put("/order", new BookAction());
    30. try {
    31. //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
    32. String configLocation = this.getInitParameter("configLocation");
    33. System.out.println(configLocation);
    34. if(configLocation == null || "".equals(configLocation)) {
    35. configModel = ConfirgModelFactory.bulid();
    36. }
    37. else {
    38. //相当于把所有值放到configModel里面
    39. configModel = ConfirgModelFactory.bulid(configLocation);
    40. }
    41. } catch (Exception e) {
    42. // TODO Auto-generated catch block
    43. e.printStackTrace();
    44. }
    45. }
    46. @Override
    47. protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    48. doPost(req, resp);
    49. }
    50. @Override
    51. protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    52. //http://location:8080/mvc/book.action?me....
    53. //获得请求路径
    54. String uri = req.getRequestURI();
    55. // 要拿到/book,就是最后一个/到最会一个.的位置
    56. uri = uri.substring(uri.lastIndexOf("/"),
    57. uri.lastIndexOf("."));
    58. //------------------------------------一,中央控制器动态加载存储空控制器-------------
    59. // Action action = actions.get(uri);
    60. //相比于上一种从Map集合获取子控制器,当前需要获取全路径名,然后反射实例化
    61. ActionModel actionModel = configModel.pop(uri);
    62. //判断
    63. if(actionModel ==null) {
    64. throw new RuntimeException("action 配置错误");
    65. }
    66. //-------------------------------------二,参数传递封装优化------------------------------
    67. //type是Action子控制器的全路径名
    68. String type = actionModel.getType();
    69. try {
    70. //当下action为bookaction
    71. Action action = (Action) Class.forName(type).newInstance();
    72. //判断是否实现了接口,实现了就转型
    73. if(action instanceof ModelDriven) {
    74. //多态的使用将bookaction转换为ModelDriven
    75. ModelDriven md = (ModelDriven) action;
    76. //model指的是bookaction中的book实例
    77. Object model = md.getModel();
    78. //要给model中的属性赋值,要接受前端jsp传递过来的参数
    79. // PropertyUtils.getProperty(bean, name);//某一对象获取到值
    80. //将前端所有参数值封装进实体类
    81. BeanUtils.populate(model, req.getParameterMap());
    82. }
    83. //-------------------------------------三,对于方法执行结果转发重定向优化-----------------
    84. //在正式调用方法前,book中的属性需要赋值
    85. // action.execute(req, resp);
    86. String result = action.execute(req, resp);
    87. //result里面拿的是配置文件里forwode里的值
    88. ForwodeModel forwodeModel = actionModel.pop(result);
    89. if(forwodeModel == null) {
    90. throw new RuntimeException("forwode配置错误");
    91. }
    92. //path相当于与以前/bookList...界面
    93. String path = forwodeModel.getPath();
    94. //拿到是否需要转发的配置
    95. boolean redirect = forwodeModel.isRedirect();
    96. if(redirect) {
    97. //重定向
    98. resp.sendRedirect(req.getServletContext().getContextPath() + path);
    99. }
    100. else {
    101. //转发
    102. req.getRequestDispatcher(path).forward(req, resp);
    103. }
    104. } catch (Exception e) {
    105. // TODO Auto-generated catch block
    106. e.printStackTrace();
    107. }
    108. }
    109. }

     在增加方法与查看方法里加上返回值,返回的值为xml里的name值

    1. private String select(HttpServletRequest req, HttpServletResponse resp) {
    2. System.out.println("在同一个servlet中调用 查看");
    3. return "success";
    4. }
    5. private String add(HttpServletRequest req, HttpServletResponse resp) {
    6. System.out.println("在同一个servlet中调用 增加 ");
    7. return "failed";
    8. }

    抛异常是因为代码中还需要优化 

    就是以下代码resp.sendRedirect(path);不能直接放path 导致路径缺失

    正确代码为:resp.sendRedirect(req.getServletContext().getContextPath() + path);

     

    四,框架配置文件可变

    将所有路径都放到,web.xml文件

    1. <?xml version="1.0" encoding="UTF-8"?>
    2. <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">
    3. <display-name>JE22-MVC</display-name>
    4. <servlet>
    5. <servlet-name>mvc</servlet-name>
    6. <servlet-class>com.dengxiyan.framework.DispatcherServlet</servlet-class>
    7. <init-param>
    8. <param-name>configLocation</param-name>
    9. <param-value>/dengxiyan.xml</param-value>
    10. </init-param>
    11. </servlet>
    12. <servlet-mapping>
    13. <servlet-name>mvc</servlet-name>
    14. <url-pattern>*.action</url-pattern>
    15. </servlet-mapping>
    16. </web-app>
    1. package com.dengxiyan.framework;
    2. import java.io.IOException;
    3. import java.util.HashMap;
    4. import java.util.Map;
    5. import javax.servlet.ServletException;
    6. import javax.servlet.annotation.WebServlet;
    7. import javax.servlet.http.HttpServlet;
    8. import javax.servlet.http.HttpServletRequest;
    9. import javax.servlet.http.HttpServletResponse;
    10. import org.apache.commons.beanutils.BeanUtils;
    11. import org.apache.commons.beanutils.PropertyUtils;
    12. import com.dengxiyan.servlet.BookAction;
    13. /**
    14. * 中央控制器
    15. * 主要职能:接收浏览器请求,找到对应的处理人
    16. * 不处理任何业务逻辑,只接收请求
    17. * @author DXY
    18. *2022年6月24日下午5:39:23
    19. */
    20. //只要以*.action结尾的都会被接收
    21. //@WebServlet("*.action")
    22. public class DispatcherServlet extends HttpServlet{
    23. private Map<String, Action> actions = new HashMap<String, Action>();
    24. private ConfigModel configModel;
    25. //程序启动时值加载一次
    26. @Override
    27. public void init() throws ServletException {
    28. actions.put("/book", new BookAction());
    29. //actions.put("/order", new BookAction());
    30. try {
    31. //getInitParameter作用是拿到web,xml中的servelet信息配置的参数
    32. String configLocation = this.getInitParameter("configLocation");
    33. System.out.println(configLocation);
    34. if(configLocation == null || "".equals(configLocation)) {
    35. configModel = ConfirgModelFactory.bulid();
    36. }
    37. else {
    38. //相当于把所有值放到configModel里面
    39. configModel = ConfirgModelFactory.bulid(configLocation);
    40. }
    41. } catch (Exception e) {
    42. // TODO Auto-generated catch block
    43. e.printStackTrace();
    44. }
    45. }

     判断时有一个带参数的和一个不带参数的方法,调用的是工厂模式里的方法

    1. package com.dengxiyan.framework;
    2. import java.io.InputStream;
    3. import java.rmi.activation.ActivationMonitor;
    4. import java.util.List;
    5. import org.dom4j.Document;
    6. import org.dom4j.DocumentException;
    7. import org.dom4j.Element;
    8. import org.dom4j.io.SAXReader;
    9. /**
    10. * 23中设计模式之工厂模式
    11. * ConfirgModelFactory就是用来生产对象的
    12. * 生产出来的ConfirgModel对象就包含了configxml中的配置内容
    13. *
    14. *
    15. * 此处生产ConfirgModel有配置信息?
    16. * 1.解析confirg.xml中的配置信息
    17. * 2.将对应的配置信息分别加载进行不同的模型对象中
    18. * @author DXY
    19. *2022年6月14日下午6:24:25
    20. */
    21. public class ConfirgModelFactory {
    22. //-------------------------------------带参数-------------------------------------------
    23. public static ConfigModel bulid(String path) throws Exception {
    24. //同包
    25. InputStream in = ConfirgModelFactory.class.getResourceAsStream(path);
    26. SAXReader sr = new SAXReader();
    27. //获得配置文件中的信息
    28. Document doc = sr.read(in);
    29. //获取所有action标签
    30. List<Element> actionEles = doc.selectNodes("/config/action");
    31. ConfigModel configModel = new ConfigModel();
    32. for (Element actionEle : actionEles) {
    33. ActionModel actionModel = new ActionModel();
    34. //将actionEle里的值存到actionModel
    35. actionModel.setPath(actionEle.attributeValue("path"));
    36. actionModel.setType(actionEle.attributeValue("type"));
    37. //将forwardModel赋值并添加到Actionmodel中
    38. List<Element> forwardEles = actionEle.selectNodes("forward");
    39. for (Element element : forwardEles) {
    40. ForwodeModel forwodeModel = new ForwodeModel();
    41. forwodeModel.setName(element.attributeValue("name"));
    42. forwodeModel.setPath(element.attributeValue("path"));
    43. //redirect:只能是false|true,允许空,默认值为false
    44. forwodeModel.setRedirect("true".equals(element.attributeValue("redirect")));
    45. actionModel.push(forwodeModel);
    46. }
    47. configModel.push(actionModel);
    48. }
    49. return configModel;
    50. }
    51. //---------------------------------不带参数---------------------------------------------
    52. public static ConfigModel bulid() throws Exception {
    53. String defaultPath = "/config.xml";
    54. return bulid(defaultPath);
    55. }
    56. }

    <效果图>

    将config.xml改为dengxiyan.xml同样是可以拿到xml文件的路径名并且可以跳到重定向界面

     

     总结:使代码更灵活

  • 相关阅读:
    xml转换成txt (VOC转换为YOLO)
    常用的国外邮箱服务有哪些?
    又一重磅利好来袭!Zebec Payroll 集成至 Nautilus Chain 主网
    Github又悄悄升级了,这次的变化是大文件的存储方式
    centos7 安装与卸载 Mysql 5.7.27(详细完整教程)
    【Swift 60秒】16 - Enumerations
    T1 小美的数组询问(15分) - 美团编程题 & 题解
    【模板】组合数取模
    GCC编译器生成库文件并编译
    【Nginx41】Nginx学习:Stream四层负载均衡浅尝及总结
  • 原文地址:https://blog.csdn.net/weixin_66202611/article/details/125491153