思路整理
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 {
public static Set<Class<?>> getClasses(String pack) {
Set<Class<?>> classes = new LinkedHashSet<Class<?>>();
boolean recursive = true;
String packageName = pack;
String packageDirName = packageName.replace('.', '/');
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)) {
System.err.println("jar类型的扫描");
JarFile jar;
try {
jar = ((JarURLConnection) url.openConnection())
.getJarFile();
Enumeration<JarEntry> entries = jar.entries();
while (entries.hasMoreElements()) {
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) {
if (name.endsWith(".class")
&& !entry.isDirectory()) {
String className = name.substring(
packageName.length() + 1, name
.length() - 6);
try {
classes.add(Class
.forName(packageName + '.'
+ className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
return classes;
}
public static void findAndAddClassesInPackageByFile(String packageName,
String packagePath, final boolean recursive, Set<Class<?>> classes) {
File dir = new File(packagePath);
if (!dir.exists() || !dir.isDirectory()) {
return;
}
File[] dirfiles = dir.listFiles(new FileFilter() {
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 {
String className = file.getName().substring(0,
file.getName().length() - 6);
try {
classes.add(Thread.currentThread().getContextClassLoader().loadClass(packageName + '.' + className));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}
}
}
4、编写模仿springmvc 中和 servlet 相关的Java 代码 HttpServletBean
public class HttpServletBean extends HttpServlet {
@Override
public void init() throws ServletException {
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 {
String requestURI = req.getRequestURI();
HandlerExecutionChain handler = getHandler(requestURI);
if (handler == null) {
noHandlerFound(req, resp);
return;
}
ModelAndView modelAndView = handler.handler();
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 {
public void onStartup(Set<Class<?>> classInfos, ServletContext ctx) throws ServletException {
for (Class<?> classInfo : classInfos) {
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 {
ServletRegistration.Dynamic dispatcherServlet = servletContext.addServlet("dispatcherServlet", new DispatcherServlet());
dispatcherServlet.addMapping("/");
}
}
6、编写 RequestMappingHandlerMapping ,url 和请求方法的处理类
public class RequestMappingHandlerMapping {
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;
}
Set<Class<?>> classes = ReflexUtils.getClasses(springmvcPackage);
for (Class<?> classInfo : classes) {
Controller controller = classInfo.getDeclaredAnnotation(Controller.class);
if (controller == null) {
continue;
}
Method[] declaredMethods = classInfo.getDeclaredMethods();
for (Method methodInfo : declaredMethods) {
RequestMapping requestMapping = methodInfo.getDeclaredAnnotation(RequestMapping.class);
if (requestMapping == null) {
continue;
}
String url = requestMapping.value();
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 {
Method method = handlerMethod.getMethod();
Object bean = handlerMethod.getBean();
Object viewName = method.invoke(bean, null);
ModelAndView modelAndView = new ModelAndView((String) viewName);
return modelAndView;
}
}
HandlerMethod
public class HandlerMethod {
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 ,最后渲染视图层。
|