一、創建maven項目
帶webapp目錄的maven項目
1.pom.xml
<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>
二、創建DispatcherServlet
在SpringMVC源碼分析之DispatcherServlet分析中,我們可以知道DispatcherServlet繼承了FrameworkServlet,又繼承了HttpServletBean,又繼承了HttpServlet,因此我們需要創建HttpServletBean、FrameworkServlet、DispatcherServlet四個類。
1.創建HttpServletBean
創建HttpServletBean,繼承HttpServlet,並重寫父類init方法,調用initServletBean方法
public class HttpServletBean extends HttpServlet {
@Override
public void init() throws ServletException {
initServletBean();
}
private void initServletBean() {
}
}
2.創建FrameworkServlet
創建FrameworkServlet,重寫initServletBean方法,並調用onRefresh方法;
重寫父類service方法,調用doService方法。
public class FrameworkServlet extends HttpServletBean{
@Override
protected void initServletBean() {
onRefresh();
}
protected void onRefresh() {
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) {
doService( req, resp);
}
protected void doService(HttpServletRequest req, HttpServletResponse resp) {
}
}
3.創建DispatcherServlet
創建DispatcherServlet,繼承FrameworkServlet,重寫父類onRefresh方法,調用initStrategies方法,再調用initHandlerMappings方法,在initHandlerMappings方法中,我們需要獲取controller註解掃包的範圍,通過RequestMappingInfoHandlerMapping的registryMapping方法;重寫父類doService方法。
public class DispatcherServlet extends FrameworkServlet {
@Override
protected void onRefresh() {
initStrategies();
}
private void initStrategies() {
initHandlerMappings();
}
private void initHandlerMappings() {
}
@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) {
}
}
三、SpringMVC對象的初始化
1.定義ComponentScan、Controller、RequestMapping註解類
@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
@Documented
public @interface ComponentScan {
String value() default "";
}
@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 "";
}
2.創建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;
}
}
3.創建SpringMvcConfig和IndexController,掃包
@ComponentScan("com.wmh.controller")
public class SpringMvcConfig {
}
@Controller
public class IndexController {
@RequestMapping(value = "/")
public String index1(){
return "index";
}
}
4.創建反射工具類
package com.wmh.util;
import java.io.File;
import java.io.FileFilter;
import java.io.IOException;
import java.net.JarURLConnection;
import java.net.URL;
import java.net.URLDecoder;
import java.util.Enumeration;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
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();
}
}
}
}
}
5.創建RequestMappingInfoHandlerMapping,初始化SpringMVCBean對象
通過SpringMVConfig獲取到掃包範圍,使用Java反射機制獲取掃包範圍中的類;
再依次遍歷類,查找類上是否含有Controller註解;
再獲取類上的所有方法,再次遍歷,查找方法上時候含有RequestMapping註解;
然後獲取RequestMapping中url地址,再將url與對應的方法關聯存放到Map集合中。
public class RequestMappingInfoHandlerMapping {
// 在初始化我們SpringMVC Bean對象、url與方法關聯存放到Map集合中
private final Map<String, HandlerMethod> registryMapping = new HashMap<String, HandlerMethod>();
public void registryMapping() {
//1.獲取SpringMVConfig的ComponentScan掃包範圍
ComponentScan declaredAnnotation = SpringMvcConfig.class.getDeclaredAnnotation(ComponentScan.class);
if (declaredAnnotation == null) {
return;
}
//2.獲取ComponentScan中value
String springmvcPackage = declaredAnnotation.value();
if (StringUtils.isEmpty(springmvcPackage)) {
return;
}
//3.使用Java反射機制獲取掃包範圍中的類
Set<Class<?>> classes = ReflexUtils.getClasses(springmvcPackage);
//4.遍歷每個類,查找類中的方法是否有加上Controller註解
classes.stream().forEach(item -> {
Controller controller = item.getDeclaredAnnotation(Controller.class);
if (controller == null) {
return;
}
//5.獲取類中的所有方法
Method[] declaredMethods = item.getDeclaredMethods();
for (Method method : declaredMethods) {
//6.遍歷方法,查找方法上是否加上RequestMapping註解
RequestMapping requestMapping = method.getDeclaredAnnotation(RequestMapping.class);
if (requestMapping != null) {
//7.獲取requestMapping中的value
String url = requestMapping.value();
//8.添加到registryMapping中
registryMapping.put(url, new HandlerMethod(newInstance(item), method));
}
}
});
}
public HandlerMethod getHandler(String url) {
return registryMapping.get(url);
}
private Object newInstance(Class classInfo) {
try {
Object value = classInfo.newInstance();
return value;
} catch (Exception e) {
return null;
}
}
}
四、編寫DispatcherServlet中doService方法
1.創建HandlerExecutionChain
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;
}
}
2.創建ModelAndView
public class ModelAndView {
// 跳轉頁面名稱
private String viewName;
public ModelAndView(String viewName) {
this.viewName = viewName;
}
public String getViewName() {
return viewName;
}
}
3.編寫DispatcherServlet中doService方法
public class DispatcherServlet extends FrameworkServlet {
RequestMappingInfoHandlerMapping requestMappingInfoHandlerMapping;
public DispatcherServlet() {
requestMappingInfoHandlerMapping = new RequestMappingInfoHandlerMapping();
}
@Override
protected void onRefresh() {
initStrategies();
}
private void initStrategies() {
initHandlerMappings();
}
private void initHandlerMappings() {
System.out.println("<<<<初始化initHandlerMappings>>>>");
requestMappingInfoHandlerMapping.registryMapping();
}
@Override
protected void doService(HttpServletRequest req, HttpServletResponse resp) {
//1.獲取Url請求
String requestURI = req.getRequestURI();
//2.根據url請求獲取具體的handler
HandlerExecutionChain handler = getHandler(requestURI);
try {
if (handler == null) {
noHandlerFound(req, resp);
return;
}
//3.執行handler方法
ModelAndView mv = handler.handler();
//4.渲染頁面
render(mv, req, resp);
} catch (Exception e) {
e.printStackTrace();
}
}
/***
* 根據modelAndView渲染頁面
* @param mv
* @param req
* @param resp
* @throws ServletException
* @throws IOException
*/
private void render(ModelAndView mv, HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String viewName = mv.getViewName();
req.getRequestDispatcher("/WEB-INF/view/" + viewName + ".jsp").forward(req, resp);//同時創建index.jsp
}
private void noHandlerFound(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.sendError(HttpServletResponse.SC_NOT_FOUND);
resp.getWriter().print("沒有查找到該請求");
}
/***
* 根據url在HandlerMapping中獲取具體的類,然後獲取集具體點的Handler
* @param url
* @return
*/
public HandlerExecutionChain getHandler(String url) {
HandlerMethod handler = requestMappingInfoHandlerMapping.getHandler(url);
if (handler == null)
return null;
HandlerExecutionChain handlerExecutionChain = new HandlerExecutionChain(handler);
return handlerExecutionChain;
}
}
4.在webapp/WEB-INF/view在創建index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
手寫SpringMVC成功
</body>
</html>
五、創建SpringServletContainerInitializer容器初始化
1.創建WebApplicationInitializer
public class WebApplicationInitializer {
}
2.創建AbstractDispatcherServletInitializer,繼承WebApplicationInitializer,編寫onStartup方法
public class AbstractDispatcherServletInitializer extends WebApplicationInitializer {
public void onStartup(ServletContext ctx)throws ServletException{
ServletRegistration.Dynamic dynamic=ctx.addServlet("dispatcherServlet",new DispatcherServlet());
dynamic.addMapping("/");//攔截所有請求
}
}
3.創建SpringServletContainerInitializer
@HandlesTypes(WebApplicationInitializer.class)
public class SpringServletContainerInitializer implements ServletContainerInitializer {
@Override
public void onStartup(Set<Class<?>> set, ServletContext servletContext) throws ServletException {
for (Class<?> classInfo : set) {
try {
//使用Java反射技術執行onStartup方法
Object o = classInfo.newInstance();
Method onStartup = classInfo.getMethod("onStartup", ServletContext.class);
onStartup.invoke(o, servletContext);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
4.在resources目錄下,創建META-INF/services/javax.servlet.ServletContainerInitializer
com.wmh.servlet.web.SpringServletContainerInitializer