根据Spring MVC的工作原理,手写一个Spring MVC的简单框架,如下:
1.pom.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.springmvc.source</groupId>
<artifactId>springmvc</artifactId>
<version>1.0-SNAPSHOT</version>
<properties>
<servelt.api.version>2.4</servelt.api.version>
</properties>
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>${servelt.api.version}</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>test</finalName>
<plugins>
<plugin>
<groupId>org.mortbay.jetty</groupId>
<artifactId>maven-jetty-plugin</artifactId>
<version>6.1.10</version>
<configuration>
<scanIntervalSeconds>3</scanIntervalSeconds>
<webAppConfig>
<contextPath>/</contextPath>
</webAppConfig>
<connectors>
<connector implementation="org.mortbay.jetty.nio.SelectChannelConnector">
<port>8080</port>
</connector>
</connectors>
</configuration>
</plugin>
</plugins>
</build>
</project>
2.web.xml文件如下:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="spring-mvc" version="2.5">
<display-name>my spring mvc</display-name>
<servlet>
<servlet-name>mymvc</servlet-name>
<servlet-class>com.springmvc.lize.servlet.GPDispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>application.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mymvc</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
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<String> classNames=new ArrayList<String>(); //
private Map<String,Object> ioc=new HashMap<String, Object>(); //IOC容器
private Map<String,Method> handlerMapping=new HashMap<String, Method>(); //映射关系
@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<String,String[]> parameterMap = req.getParameterMap();
//保存参数值
Object[] paramValues=new Object[parameterTypes.length];
//方法的参数列表
for (int i = 0; i <parameterTypes.length ; i++) {
Class<?> 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<String,String[]> 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<String, Object> 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<String, Object> 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.自定义命名(<bean id="XXX" class="XXX")
//3.自动类型匹配(例如:将实现类赋值给接口)
if (clazz.isAnnotationPresent(GPController.class)){
Object instance = clazz.newInstance();
String beanName = lowerFirstCase(clazz.getSimpleName());
ioc.put(beanName,instance);
}else if (clazz.isAnnotationPresent(GPService.class)){
//Service
GPService service = clazz.getAnnotation(GPService.class);
String beanName = service.value();
//1.默认首字母小写
if("".equals(beanName.trim())){
beanName=lowerFirstCase(clazz.getName());
}
Object instance = clazz.newInstance();
ioc.put(beanName,instance);
//2.自动类型匹配(例如:将实现类赋值给接口)
Class<?>[] 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+"!!!!";
}
}