最近按照网上博客大神们的教程,也模仿着写了个springmvc框架,但是由于基础稍薄弱,再加上忘得比较多,顺便就巩固一下基础知识.(本人用的是工具是IDEA).
首先,发一下我的目录结构:
配置的截图也发几张吧,如下:
上面是web.xml文件的路径.下面是web资源文件的路径,例如,html,js,jsp...一般来说,这个路径都是WEB-INF的上级路径.
但是配置完了之后,有个问题,代码里面读取properties文件读取不到.研究了好久发现,其实是因为我之前项目结构更改了,之前我创建了一个别的文件夹,然后把classes文件放到了那个文件夹下面,后来我把这个文件夹删掉了之后,classes文件夹我直接移动到webapp下面的.可能是编译的原因,配置文件无法进入classpath下,最后我重新ReBuild一下项目就解决了.也算是很狗血...
一.首先的话,配置一个Maven项目(如何配置maven项目就不说了,一搜一大堆.推荐网站:https://blog.csdn.net/qq_35437792/article/details/80631434),我用的公司内网,结果创建完maven项目之后报错,结果自己开个热点之后就好了... 很蓝瘦.
二.在pom.xml里面只需要添加一个servlet依赖即可:
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
三.在web.xml中配置我们的servlet:
<servlet>
<servlet-name>MySpringMvc</servlet-name>
<servlet-class>com.zhmystic.mvcbyhand.servlet.MyDispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:myapplication.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>MySpringMvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
四.自定义注解:MyAutowired,MyController,MyService,MyRequestMapping,MyRequestParam
(关于自定义注解的部分,这里不加详细介绍,搬运网址,感觉写的很好:http://www.cnblogs.com/liangweiping/p/3837332.html)
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyAutowired {
String value() default "";
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyController {
String value() default "";
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestMapping {
String value();
}
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestParam {
String value() ;
}
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyService {
String value() default "";
}
五.创建servlet
package com.zhmystic.mvcbyhand.servlet;
import com.zhmystic.mvcbyhand.annotation.MyAutowired;
import com.zhmystic.mvcbyhand.annotation.MyController;
import com.zhmystic.mvcbyhand.annotation.MyRequestMapping;
import com.zhmystic.mvcbyhand.annotation.MyService;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.*;
import java.util.logging.Logger;
/**
* <P>
* Copyright 2018 sun_car All Rights Reserved.
* </p>
*
* @author zhmystic.
* @date 15:40 2018/12/7
* @description MVC框架的请求分发中转
*/
public class MyDispatcherServlet extends HttpServlet {
private Logger logger = Logger.getLogger("init");
Properties properties = new Properties();
private List<String> classNames = new ArrayList<>();
private Map<String, Object> ioc = new HashMap<>();
private Map<String, Method> handlerMapping = new HashMap<>();
private Map<String, Object> controllerMap =new HashMap<>();
@Override
public void init(ServletConfig config) throws ServletException {
super.init();
logger.info("初始化MyDispatcherServlet");
//1.加载配置文件,填充properties字段
doLoadConfig(config.getInitParameter("contextConfigLocation"));
//2.根据properties,初始化所有相关联的类,扫描用户设定的包下面所有的类
doScanner(properties.getProperty("scanPackage"));
//3.拿到扫描到的类,通过反射机制,实例化,并且放到ioc容器中(k-v beanName-bean) beanName默认是首字母小写
doInstance();
// 4.自动化注入依赖
doAutowired();
//5.初始化HandlerMapping(将url和method对应上)
initHandlerMapping();
}
/**
* 1.根据配置文件位置,读取配置文件中的配置信息,将其填充到properties字段
* @param contextConfigLocation 配置文件的位置
*/
private void doLoadConfig(String contextConfigLocation) {
//把web.xml中的contextConfigLocation对应value值的文件加载到流里面
String resource = contextConfigLocation.split(":")[1];
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(resource);
//也可以用下面方式直接读取,上面的只是先从web.xml中读取参数,然后读取的文件
// InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream("myapplication.properties");
try {
//用Properties文件加载文件里的内容
logger.info("读取" + contextConfigLocation + "里面的文件");
properties.load(resourceAsStream);
}catch (Exception e){
e.printStackTrace();
}finally {
//关流
if (resourceAsStream != null) {
try {
resourceAsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 2.将指定包下扫描得到的类,添加到classNames字段中;
* @param scanPackage 需要扫描的包名
*/
private void doScanner(String scanPackage) {
URL url = this.getClass().getClassLoader().getResource("/" + scanPackage.replaceAll("\\.","/"));
File dir = new File(url.getFile());
for (File file : dir.listFiles()) {
if(file.isDirectory()){
//递归读取包
doScanner(scanPackage+"."+file.getName());
}else{
String className =scanPackage +"." +file.getName().replace(".class", "");
classNames.add(className);
}
}
}
/**
* 3.将classNames中的类实例化,经key-value:类名(小写)-类对象放入ioc字段中
*/
private void doInstance() {
if (classNames.isEmpty()) {
return;
}
//遍历集合
for (String className:classNames) {
try {
//把类搞出来,反射来实例化(只有加@MyController需要实例化)
Class<?> clazz = Class.forName(className);
if (clazz.isAnnotationPresent(MyController.class)) {
ioc.put(toLowerFirstWord(clazz.getSimpleName()),clazz.newInstance());
}else if (clazz.isAnnotationPresent(MyService.class)) {
MyService myService = clazz.getAnnotation(MyService.class);
String beanName = myService.value();
if ("".equals(beanName.trim())){
beanName=toLowerFirstWord(clazz.getSimpleName());
}
Object newInstance = clazz.newInstance();
ioc.put(beanName,newInstance);
Class<?>[] interfaces = clazz.getInterfaces();
for (Class<?> i:interfaces) {
ioc.put(i.getName(),newInstance);
}
}else {
continue;
}
}catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
/**
* 4.自动化的依赖注入
*/
private void doAutowired() {
if (ioc.isEmpty()){
return;
}
for (Map.Entry<String,Object> entry:ioc.entrySet()){
//包括私有的方法,在spring中没有隐私,@MyAutowired可以注入public、private字段
Field[] fields=entry.getValue().getClass().getDeclaredFields();
for (Field field:fields){
if (!field.isAnnotationPresent(MyAutowired.class)){
continue;
}
MyAutowired autowired= field.getAnnotation(MyAutowired.class);
String beanName=autowired.value().trim();
if ("".equals(beanName)){
beanName=field.getType().getName();
}
field.setAccessible(true);
try {
field.set(entry.getValue(),ioc.get(beanName));
}catch (Exception e){
e.printStackTrace();
continue;
}
}
}
}
/**
* 5.初始化HandlerMapping(将url和method对应上)
*/
private void initHandlerMapping() {
if(ioc.isEmpty()){
return;
}
try {
for (Map.Entry<String, Object> entry: ioc.entrySet()) {
Class<? extends Object> clazz = entry.getValue().getClass();
if(!clazz.isAnnotationPresent(MyController.class)){
continue;
}
//拼url时,是controller头的url拼上方法上的url
String baseUrl ="";
if(clazz.isAnnotationPresent(MyRequestMapping.class)){
MyRequestMapping annotation = clazz.getAnnotation(MyRequestMapping.class);
baseUrl=annotation.value();
}
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if(!method.isAnnotationPresent(MyRequestMapping.class)){
continue;
}
MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
String url = annotation.value();
url =(baseUrl+"/"+url).replaceAll("/+", "/");
handlerMapping.put(url,method);
controllerMap.put(url,clazz.newInstance());
System.out.println(url+","+method);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("执行MyDispatcherServlet的doGet()");
try{
//处理请求
doDispatch(req,resp);
}catch (Exception e) {
resp.getWriter().write("500!! Server Exception");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
logger.info("执行MyDispatcherServlet的doPost()");
try{
//处理请求
doDispatch(req,resp);
}catch (Exception e) {
resp.getWriter().write("500!! Server Exception");
}
}
/**
* 处理请求
* @param req
* @param resp
*/
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws IOException {
if(handlerMapping.isEmpty()){
return;
}
String url =req.getRequestURI();
String contextPath = req.getContextPath();
url=url.replace(contextPath, "").replaceAll("/+", "/");
// 去掉url前面的斜杠"/",所有的@MyRequestMapping可以不用写斜杠"/"
if(url.lastIndexOf('/')!=0){
url=url.substring(1);
}
if(!this.handlerMapping.containsKey(url)){
resp.getWriter().write("404 NOT FOUND!");
logger.info("404 NOT FOUND!");
return;
}
Method method =this.handlerMapping.get(url);
//获取方法的参数列表
Class<?>[] parameterTypes = method.getParameterTypes();
//获取请求的参数
Map<String, String[]> parameterMap = req.getParameterMap();
//保存参数值
Object [] paramValues= new Object[parameterTypes.length];
//方法的参数列表
for (int i = 0; i<parameterTypes.length; i++){
//根据参数名称,做某些处理
String requestParam = parameterTypes[i].getSimpleName();
if (requestParam.equals("HttpServletRequest")){
//参数类型已明确,这边强转类型
paramValues[i]=req;
continue;
}
if (requestParam.equals("HttpServletResponse")){
paramValues[i]=resp;
continue;
}
if(requestParam.equals("String")){
for (Map.Entry<String, String[]> param : parameterMap.entrySet()) {
String value =Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
paramValues[i]=value;
}
}
}
//利用反射机制来调用
try {
//第一个参数是method所对应的实例 在ioc容器中
//method.invoke(this.controllerMap.get(url), paramValues);
method.invoke(this.controllerMap.get(url), paramValues);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 首字母转为小写
* @param name
* @return
*/
private String toLowerFirstWord(String name){
char[] charArray = name.toCharArray();
charArray[0] += 32;
return String.valueOf(charArray);
}
}
里面涉及到了好多的基础知识,顺便温习一下,要不然都快忘光了.
第一步里面的类加载器,读取配置文件.
未完待遇.....