思路整理
SpringMVC原理简单回顾 核心:靠的就是DispatcherServlet拦截客户端所有请求实现转发到具体的请求方法执行。
SpringMVC思路:
控制层和 url 映射关联定义好存放到Map集合中 肯定在项目启动时候
1.扫包获取cLass中的方法有加上RequestMapping 如果有有该注解的话存放到map集合
2.key: urL: value方法
访问这个请求根据url查找对应的执行的方法在通过java反射执行该方法。
高仿 SpringMVC 框架
适配器模式
定义:将一个系统的接口转换成另外一种形式,从而使原来不能直接调用的接口变得可以调用。
SpringMVC适配器模式源码分析
- 使用getHandlerAdapter 获取对应的 hanlder 的具体 HandlerAdapter
- HandlerAdapter接口有如下的子 c处理请求适配器
2.1继承Controller方式所使用的适配器:SimpleControllerHandlerAdapter
2.2 HTTP请求处理器适配器:HttpRequestHandlerAdapter
3.3注解方式(@Controller)的处理器适配器:RequestMappingHandlerAdapter
Java代码
1、新建web 项目(maven),项目结构如下图:
2、引入maven 依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.0</version>
</dependency>
3、编写三个注解,用于扫描Java类、controller层Java类、处理请求的方法
ComponentScan 扫描包的注解
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ComponentScan {
String value() default "";
}
标注为 controller 层的Java类的注解
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Controller {
String value() default "";
}
标注为处理请求方法的注解
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestMapping {
String value() default "";
}
编写一个工具类,用于扫描包使用
public class ReflexUtils {
/**
* 从包package中获取所有的Class
*
* @param pack
* @return
*/
public static Set<Class<?>> getClasses(String pack) {
// 第一个class类的集合
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
// 是否循环迭代
boolean recursive = true;
// 获取包的名字 并进行替换
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
// 定义一个枚举的集合 并进行循环来处理这个目录下的things
Enumeration<URL> dirs;
try {
dirs = Thread.currentThread().getContextClassLoader().getResources(
packageDirName);
// 循环迭代下去
while (dirs.hasMoreElements()) {
// 获取下一个元素
URL url = dirs.nextElement();
// 得到协议的名称
String protocol = url.getProtocol();
// 如果是以文件的形式保存在服务器上
if ("file".equals(protocol)) {
System.err.println("file类型的扫描");
// 获取包的物理路径
String filePath = URLDecoder.decode(url.getFile(), "UTF-8");
// 以文件的方式扫描整个包下的文件 并添加到集合中
findAndAddClassesInPackageByFile(packageName, filePath,
recursive, classes);
} else if ("jar".equals(protocol)) {
// 如果是jar包文件
// 定义一个JarFile
System.err.println("jar类型的扫描");
JarFile jar;
try {
// 获取jar
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
// 从此jar包 得到一个枚举类
Enumeration<JarEntry> entries = jar.entries();
// 同样的进行循环迭代
while (entries.hasMoreElements()) {
// 获取jar里的一个实体 可以是目录 和一些jar包里的其他文件 如META-INF等文件
JarEntry entry = entries.nextElement();
String name = entry.getName();
// 如果是以/开头的
if (name.charAt(0) == '/') {
// 获取后面的字符串
name = name.substring(1);
}
// 如果前半部分和定义的包名相同
if (name.startsWith(packageDirName)) {
int idx = name.lastIndexOf('/');
// 如果以"/"结尾 是一个包
if (idx != -1) {
// 获取包名 把"/"替换成"."
packageName = name.substring(0, idx)
.replace('/', '.');
}
// 如果可以迭代下去 并且是一个包
if ((idx != -1) || recursive) {
// 如果是一个.class文件 而且不是目录
if (name.endsWith(".class")
&& !entry.isDirectory()) {
// 去掉后面的".class" 获取真正的类名
String className = name.substring(
packageName.length() + 1, name
.length() - 6);
try {
// 添加到classes
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
// log
// .error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
// log.error("在扫描用户定义视图时从jar包获取文件出错");
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
/**
* 以文件的形式来获取包下的所有Class
*
* @param packageName
* @param packagePath
* @param recursive
* @param classes
*/
public static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
// 获取此包的目录 建立一个File
File dir = new File(packagePath);
// 如果不存在或者 也不是目录就直接返回
if (!dir.exists() || !dir.isDirectory()) {
// log.warn("用户定义包名 " + packageName + " 下没有任何文件");
return;
}
// 如果存在 就获取包下的所有文件 包括目录
File[] dirfiles = dir.listFiles(new FileFilter() {
// 自定义过滤规则 如果可以循环(包含子目录) 或则是以.class结尾的文件(编译好的java类文件)
public boolean accept(File file) {
return (recursive && file.isDirectory())
|| (file.getName().endsWith(".class"));
}
});
// 循环所有文件
for (File file : dirfiles) {
// 如果是目录 则继续扫描
if (file.isDirectory()) {
findAndAddClassesInPackageByFile(packageName + "."
+ file.getName(), file.getAbsolutePath(), recursive,
classes);
} else {
// 如果是java类文件 去掉后面的.class 只留下类名
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
// 添加到集合中去
//classes.add(Class.forName(packageName + '.' + className));
//经过回复同学的提醒,这里用forName有一些不好,会触发static方法,没有使用classLoader的load干净
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
// log.error("添加用户自定义视图类错误 找不到此类的.class文件");
e.printStackTrace();
}
}
}
}
}
4、编写模仿springmvc 中和 servlet 相关的Java 代码
HttpServletBean
public class HttpServletBean extends HttpServlet {
@Override
public void init() throws ServletException {
// 初始化我们的springmvcbean的对象 和url与方法关联
initServletBean();
}
protected void initServletBean() {
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) {
doService(req,resp);
}
protected void doService(HttpServletRequest req, HttpServletResponse resp) {
}
}
FrameworkServlet
public class FrameworkServlet extends HttpServletBean {
@Override
protected void initServletBean() {
onRefresh();
}
protected void onRefresh() {
}
@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) {
}
}
DispatcherServlet
public class DispatcherServlet extends FrameworkServlet {
private RequestMappingHandlerMapping requestMappingHandlerMapping;
public DispatcherServlet() {
requestMappingHandlerMapping = new RequestMappingHandlerMapping();
}
@Override
protected void onRefresh() {
initStrategies();
}
private void initStrategies() {
requestMappingHandlerMapping.initHandlerMappings();
}
@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) {
doDispatch(req, resp);
}
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) {
try {
// 1.处理请求url
String requestURI = req.getRequestURI();
// 2.根据url查找对应的Handler
HandlerExecutionChain handler = getHandler(requestURI);
if (handler == null) {
noHandlerFound(req, resp);
return;
}
// 3.使用java的反射机制执行请求方法 返回对应的modelAndView
ModelAndView modelAndView = handler.handler();
// 4.开始渲染视图层
render(modelAndView, req, resp);
} catch (Exception e) {
}
}
public void render(ModelAndView modelAndView, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String viewName = modelAndView.getViewName();
req.getRequestDispatcher("/WEB-INF/view/" + viewName + ".jsp").forward(req, resp);
}
private HandlerExecutionChain getHandler(String url) {
HandlerMethod handlerMethod = requestMappingHandlerMapping.getHandlerMethod(url);
if (handlerMethod == null) {
return null;
}
HandlerExecutionChain handlerExecutionChain = new HandlerExecutionChain(handlerMethod);
return handlerExecutionChain;
}
protected void noHandlerFound(HttpServletRequest request, HttpServletResponse response) throws Exception {
throw new Exception("没有查找到对应的请求");
}
}
5、编写 ServletContainerInitializer 的实现类
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
/**
* onStartup servlet容器初始化的时候就会调用该方法
*
* @param classInfos 获取 WebApplicationInitializer 所有的子类
* @param ctx
* @throws ServletException
*/
public void onStartup(Set<Class<?>> classInfos, ServletContext ctx) throws ServletException {
for (Class<?> classInfo : classInfos) {
//classInfo 都是WebApplicationInitializer类的子类
try {
Method method = classInfo.getMethod("onStartup", ServletContext.class);
Object object = classInfo.newInstance();
method.invoke(object, ctx);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
WebApplicationInitializer
public interface WebApplicationInitializer {
void onStartup(ServletContext servletContext) throws ServletException;
}
AbstractDispatcherServletInitializer
public class AbstractDispatcherServletInitializer implements WebApplicationInitializer {
@Override
public void onStartup(ServletContext servletContext) throws ServletException {
// 1.开始注册我们的DispatcherServlet
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcherServlet", new DispatcherServlet());
dispatcherServlet.addMapping("/");// 拦截所有的请求
// dispatcherServlet.setLoadOnStartup(1);
}
}
6、编写 RequestMappingHandlerMapping ,url 和请求方法的处理类
public class RequestMappingHandlerMapping {
// 在初始化我们SpringMVC Bean对象、url与方法关联存放到Map集合中
private Map<String, HandlerMethod> registry = new HashMap<>();
public void initHandlerMappings() {
ComponentScan componentScan = SpringMvcConfig.class.getDeclaredAnnotation(ComponentScan.class);
String springmvcPackage = componentScan.value();
if (StringUtils.isEmpty(springmvcPackage)) {
return;
}
// 1. 使用java反射机制 查找该包下com.kaico.controller 有那些控制类
Set<Class<?>> classes = ReflexUtils.getClasses(springmvcPackage);
// 2. 循环遍历每个类 只要有加上
for (Class<?> classInfo : classes) {
// 3.判断类上是否有加上我们的控制注解
Controller controller = classInfo.getDeclaredAnnotation(Controller.class);
if (controller == null) {
continue;
}
// 4.遍历控制层类中方法是否有加上RequestMapping
Method[] declaredMethods = classInfo.getDeclaredMethods();
for (Method methodInfo : declaredMethods) {
RequestMapping requestMapping = methodInfo.getDeclaredAnnotation(RequestMapping.class);
if (requestMapping == null) {
continue;
}
String url = requestMapping.value();
// 存放到hashMap集合中 key url value: Method
registry.put(url, new HandlerMethod(newInstance(classInfo), methodInfo));
}
}
}
private Object newInstance(Class classInfo) {
try {
Object value = classInfo.newInstance();
return value;
} catch (Exception e) {
return null;
}
}
public HandlerMethod getHandlerMethod(String url) {
return registry.get(url);
}
}
7、编写handler
public class HandlerExecutionChain {
HandlerMethod handlerMethod;
public HandlerExecutionChain(HandlerMethod handlerMethod) {
this.handlerMethod = handlerMethod;
}
public ModelAndView handler() throws InvocationTargetException, IllegalAccessException {
// 1. 使用java的反射机制执行我们请求方法
Method method = handlerMethod.getMethod();
Object bean = handlerMethod.getBean();
// 2.执行我们的请求的方法
Object viewName = method.invoke(bean, null);
ModelAndView modelAndView = new ModelAndView((String) viewName);
return modelAndView;
}
}
HandlerMethod
public class HandlerMethod {
// 请求方法对应的bean对象
private Object bean;
private Method method;
public HandlerMethod(Object bean, Method method) {
this.bean = bean;
this.method = method;
}
public Object getBean() {
return bean;
}
public Method getMethod() {
return method;
}
}
8、编写视图层使用的Java类
public class ModelAndView {
// 跳转页面名称
private String viewName;
public ModelAndView(String viewName) {
this.viewName = viewName;
}
public String getViewName() {
return viewName;
}
}
9、编写一个配置文件
内容如下:
com.kaico.servlet.web.SpringServletContainerInitializer
11、编写springmvc 配置类
@ComponentScan("com.mayikt.controller")
public class SpringMvcConfig {
}
10、编写一个 controller 和一个 jsp 文件
@Controller
public class PayController {
@RequestMapping("/pay")
public String pay() {
return "pay";
}
}
jsp文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
你好,这里是高仿springmvc 框架
</body>
</html>
项目部署在 tomcat 中。
流程总结:根据配置文件,servlet 容器会加载类SpringServletContainerInitializer执行里面的 onStartup 方法,找到实现WebApplicationInitializer 接口的类,在servlet 初始化时做一些初始化操作,利用反射把 url 对应的 请求方法 HandlerMethod 都加载存储到 RequestMappingHandlerMapping 里的registry 集合中。请求时所有拦截所有请求,DispatcherServlet 中的doDispatch 根据 url 找到对应的 HandlerMethod 执行对应的方法。在返回 ModelAndView ,最后渲染视图层。