1.1 新建DispatcherServlet

1.2 在src目录下,新建applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>

<beans id="b1">
<bean id="emp" class="xxx.controller.EmpController"/>
<bean id="dept" class="xxx.controller.DeptController"/>
</beans>

1.3 在DispatcherServlet的构造方法中解析applicationContext.xml配置文件

import java.io.IOException;

import java.io.InputStream;

import java.util.Map;

import java.util.concurrent.ConcurrentHashMap;

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 javax.xml.parsers.DocumentBuilder;

import javax.xml.parsers.DocumentBuilderFactory;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;

import org.w3c.dom.Element;

import org.w3c.dom.Node;

import org.w3c.dom.NodeList;

import org.xml.sax.SAXException;

@WebServlet("*.do")

public class DispatcherServlet extends HttpServlet {

private Map<String, Object> map = new ConcurrentHashMap<>();

public DispatcherServlet() {

try {

InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("applicationContext.xml");

// 1,通过工厂模式,创建documentBuilderFactory工厂对象

DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();

// 2,创建DocumentBuilder对象

DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();

// 3,得到Document对象( 注意导入org.w3c.dom包中的)

Document document = documentBuilder.parse(inputStream);

// 4,获得所有的bean标签

NodeList nodeList = document.getElementsByTagName("bean");

for (int i = 0; i < nodeList.getLength(); i++) {

Node node = nodeList.item(i);

if(node.getNodeType() == Node.ELEMENT_NODE) {

//(注意导入org.w3c.dom包中的)

//强转成Element类的对象,里面有比Node类更方便的方法

Element element = (Element)node;

String id = element.getAttribute("id");

String className = element.getAttribute("class");

boolean flag = map.containsKey(id);

if(flag == true)

return;

Object o = Class.forName(className).newInstance();

map.put(id, o);

}

}

} catch (ParserConfigurationException | SAXException | IOException | ClassNotFoundException | InstantiationException | IllegalAccessException e) {

e.printStackTrace();

}

}

@Override

protected void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 设置编码

request.setCharacterEncoding("UTF-8");

response.setCharacterEncoding("UTF-8");

response.setContentType("text/html;charset=UTF-8");

// 假设url是: http://localhost:8080/mymvc2/hello.do

// ServletPath是Servlet的访问路径: /hello.do

// 思路是:

// 第1步: /hello.do -> hello 或者 /book.do -> book

// 第2步: hello -> HelloController 或者 book -> BookController

String servletPath = request.getServletPath(); // /hello.do

int lastDotIndex = servletPath.lastIndexOf(".do");

servletPath = servletPath.substring(1, lastDotIndex); // hello

}

}

1.4 在DispatcherServlet的service方法中,通过ServletPath获取对应的Controller对象,优化反射的代码

@Override

protected void service(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// 设置编码

request.setCharacterEncoding("UTF-8");

response.setCharacterEncoding("UTF-8");

response.setContentType("text/html;charset=UTF-8");

// 假设url是: http://localhost:8080/mymvc2/hello.do

// ServletPath是Servlet的访问路径: /hello.do

// 思路是:

// 第1步: /hello.do -> hello 或者 /book.do -> book

// 第2步: hello -> HelloController 或者 book -> BookController

String servletPath = request.getServletPath(); // /hello.do

int lastDotIndex = servletPath.lastIndexOf(".do");

servletPath = servletPath.substring(1, lastDotIndex); // hello

// 通过ServletPath获取对应的Controller对象

Object xxxController = map.get(servletPath);

String ac = request.getParameter("ac");

System.out.println("=======" + ac + "======");

if (StringUtil.isEmpty(ac))

ac = "index";

try {

// 这里只能try...catch异常,因为在重写的方法里,不能抛出比父类更大的异常

Method method = xxxController.getClass().getDeclaredMethod(ac, HttpServletRequest.class,HttpServletResponse.class);

if (method != null) {

method.invoke(xxxController, request, response);

} else {

throw new RuntimeException("ac值违法");

}

} catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException

| InvocationTargetException e) {

e.printStackTrace();

}

}

1.5 写一个简单的EmpController

import javax.servlet.http.HttpServletRequest;

import javax.servlet.http.HttpServletResponse;

public class EmpController {

public void index(HttpServletRequest request,HttpServletResponse response) {

System.out.println("EmpController...index");

}

}

2. 第二次改进,每一个方法中都有获取参数的代码, 或者都有请求转发或是重定向的代码。解决跳转问题

(代码格式问题各位大佬别吐槽,复制过来的有时间改)

最新文章

  1. [连载]《C#通讯(串口和网络)框架的设计与实现》- 14.序列号的设计,不重复的实现一机一码
  2. MySQL学习笔记之MySQL安装详解
  3. MySQL之远程登录配置
  4. wamp 2.5 开放访问权限和设置虚拟域名
  5. jodaTime 的使用说明
  6. 各种主流数据库的比较(所以说我觉得Oracle这个keng?入的不错?)
  7. nodejs ctrl+B 快捷键设置
  8. ☀【组件】加载 load
  9. 通过ctypes获得python windows process的内存使用情况
  10. [置顶] linux学习之samba安装问题详解
  11. 可靠通信的保障 —— 使用ACK机制发送自定义信息——ESFramework 通信框架4.0 快速上手(12)
  12. linux 如何降低入向软中断占比
  13. 如何使用PowerDesigner建表
  14. window.onload 与 $(document).ready() 的区别
  15. Kafka如何删除topic?
  16. Docker 部署 elk + filebeat
  17. 【 HDU - 4456 】Crowd (二维树状数组、cdq分治)
  18. node.js 初学(一)—— http fs 服务器/文件/post get
  19. Python之路3【知识点】白话Python编码和文件操作(截载)
  20. java内存溢出的原因

热门文章

  1. php 23种设计模型 - 中介者模式
  2. 如何实现 UITabbarController 的 State Preservation?
  3. Gin 09 HTTP 重定向
  4. vue2版本中slot的基本使用详解
  5. 基于Kali的一次DDos攻击实践
  6. Django之 rest_framework (一基本组件)
  7. python练习册 每天一个小程序 第0002题
  8. 为什么 char 数组比 Java 中的 String 更适合存储密码?
  9. vue Cannot read property ‘tapPromise‘ of undefined
  10. 接口是否可继承(extends)接口?抽象类是否可实现 (implements)接口?抽象类是否可继承具体类(concrete class)?