根据Spring MVC的工作原理,手写一个Spring MVC的简单框架,如下:
1.pom.xml文件如下:
4.0.0
com.springmvc.source
springmvc
1.0-SNAPSHOT
2.4
javax.servlet
servlet-api
${servelt.api.version}
provided
test
org.mortbay.jetty
maven-jetty-plugin
6.1.10
3
/
8080
2.web.xml文件如下:
my spring mvc
mymvc
com.springmvc.lize.servlet.GPDispatcherServlet
contextConfigLocation
application.properties
1
mymvc
/*
application.properties文件如下:
scanPackage=com.springmvc.lize.demo //需要扫描的文件
首先定义一些注解
@Target({ElementType.FIELD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPAurowired {
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPController {
String value() default "";
}
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPRequestMapping {
String value() default "";
}
@Target({ElementType.PARAMETER})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPRequestParam {
String value() default "";
}
@Target({ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface GPService {
String value() default "";
}
下面主要定义GPDispatcherServlet:
package com.springmvc.lize.servlet;
import com.springmvc.lize.annotation.GPAurowired;
import com.springmvc.lize.annotation.GPController;
import com.springmvc.lize.annotation.GPRequestMapping;
import com.springmvc.lize.annotation.GPService;
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.*;
/**
* Created by Administrator on 2019/6/22.
*/
public class GPDispatcherServlet extends HttpServlet {
private Properties contextConfig=new Properties();
private List classNames=new ArrayList(); //
private Map ioc=new HashMap(); //IOC容器
private Map handlerMapping=new HashMap(); //映射关系
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
try {
doDispatch(req,resp);
}catch (Exception e){
resp.getWriter().write("500 Execption,Details:\r\n"+Arrays.toString(e.getStackTrace())
.replaceAll("\\[|\\]","").replaceAll(",\\s","\r\n"));
}
}
//关键方法
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("/+","/");
if (!handlerMapping.containsKey(url)){
resp.getWriter().write("404 not Find!!!");
return;
}
Method method = handlerMapping.get(url);
System.out.println(method);
//获取方法的参数列表
Class>[] parameterTypes = method.getParameterTypes();
//获取请求的参数
Map parameterMap = req.getParameterMap();
//保存参数值
Object[] paramValues=new Object[parameterTypes.length];
//方法的参数列表
for (int i = 0; i parameterType = parameterTypes[i];
if (parameterType==HttpServletRequest.class){
paramValues[i]=req;
continue;
}else if (parameterType==HttpServletResponse.class){
paramValues[i]=resp;
continue;
}else if(parameterType==String.class){
for (Map.Entry param:parameterMap.entrySet()){
String value = Arrays.toString(param.getValue())
.replaceAll("\\[|\\]", "")
.replaceAll(",\\s", ",");
paramValues[i]=value;
}
}
}
try {
String beanName = lowerFirstCase(method.getDeclaringClass().getSimpleName());
method.invoke(this.ioc.get(beanName),paramValues);
}catch (Exception e){
e.printStackTrace();
}
}
@Override
public void init(ServletConfig config) throws ServletException {
// System.out.println("---------------------------------");
//1.加载配置文件
doLoadConfig(config.getInitParameter("contextConfigLocation"));
//2.扫描所有相关联的类
doScanner(contextConfig.getProperty("scanPackage"));
//3.初始化所有先关联的类并将其保存在IOC容器中
doInstance();
//4.执行依赖注入(把加了@Aurowired注解的赋值)
doAutoWired();
//5.构造HadnlerMapping,将url和Methed进行关联
initHandlerMapping();
System.out.println("Init Finsh!!!!");
}
private void initHandlerMapping() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry entry : ioc.entrySet()) {
Class> clazz = entry.getValue().getClass();
if (!clazz.isAnnotationPresent(GPController.class)){
continue;
}
String baseUrl="";
if (clazz.isAnnotationPresent(GPRequestMapping.class)){
GPRequestMapping requestMapping = clazz.getAnnotation(GPRequestMapping.class);
baseUrl=requestMapping.value();
}
Method[] methods = clazz.getMethods();
for (Method method:methods){
if (!method.isAnnotationPresent(GPRequestMapping.class)){
continue;
}
GPRequestMapping requestMapping = method.getAnnotation(GPRequestMapping.class);
String url = requestMapping.value();
url=(baseUrl+"/"+url).replaceAll("/+","/");
handlerMapping.put(url,method);
System.out.println("Mapping :"+url+","+method);
}
}
}
private void doAutoWired() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry entry : ioc.entrySet()) {
//注入的意思就是吧所有的IOC容器中加了@Autowired注解的字段全部赋值
Field[] fields = entry.getValue().getClass().getDeclaredFields();
for (Field field:fields){
//判断是否加了注解,不是所有的
if (!field.isAnnotationPresent(GPAurowired.class)){
continue;
}
GPAurowired aurowired = field.getAnnotation(GPAurowired.class);
String beanName = aurowired.value().trim();
if ("".equals(beanName)){
beanName= field.getType().getName();
}
//如果字段私有,强制访问
field.setAccessible(true);
try {
field.set(entry.getValue(),ioc.get(beanName));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
private void doInstance() {
if (classNames.isEmpty()){
return;
}else {
try {
for (String className:classNames){
Class> clazz = Class.forName(className);
//clazz.newInstance();
//ioc.put()
//key规则:
//1.默认类名首字母小写
//2.自定义命名([] interfaces = clazz.getInterfaces();
for (Class> i:interfaces){
ioc.put(i.getName(),instance);
}
}else {
continue;
}
clazz.newInstance();
}
}catch (Exception e) {
e.printStackTrace();
}
}
}
private String lowerFirstCase(String str) {
char[] chars=str.toCharArray();
chars[0]+=32;
return String.valueOf(chars);
}
private void doScanner(String basePackage) {
URL url = this.getClass().getClassLoader().getResource("/" + basePackage.replaceAll("\\.", "/"));
File dir=new File(url.getFile());
for (File file:dir.listFiles()){
if (file.isDirectory()){
doScanner(basePackage+"."+file.getName());
}else {
String className=basePackage+"."+file.getName().replace(".class","");
classNames.add(className);
System.out.println(className);
}
}
}
private void doLoadConfig(String location){
InputStream is = this.getClass().getClassLoader().getResourceAsStream(location);
try {
contextConfig.load(is);
} catch (IOException e) {
e.printStackTrace();
}finally {
if (null!=is){
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
定义的demo如下:
@GPController
@GPRequestMapping("/demo")
public class DemoAction {
@GPAurowired
private IDemoService demoService;
@GPRequestMapping("/query.json")
public void query(HttpServletRequest req,HttpServletResponse resq,
@GPRequestParam String name){
String result=demoService.get(name);
try {
resq.getWriter().write(result);
} catch (IOException e) {
e.printStackTrace();
}
}
}
@GPService
public class DemoSeviceImpl implements IDemoService {
@Override
public String get(String name) {
return "Hello"+name+"!!!!";
}
}