1.pom.xml
<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/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.tempus.cn</groupId>
<artifactId>myspringmvc</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>myspringmvc Maven Webapp</name>
<url>http://maven.apache.org</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>myspringmvc</finalName>
</build>
</project>
2.相关的注解类
package myspringmvc.servlet;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author asus
* @date 2018年11月21日 上午10:32:45
*
*/
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyController {
/**
* 表示给controller注册别名
*
*/
String value() default "";
}
package myspringmvc.servlet;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author asus
* @date 2018年11月21日 上午10:32:45
*
*/
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestMapping {
/**
* 表示该访问方法的url
*
*/
String value() default "";
}
package myspringmvc.servlet;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author asus
* @date 2018年11月21日 上午10:32:45
*
*/
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface MyRequestParam {
/**
* 表示参数的别名,必填
*
*/
String value();
}
3.配置文件
application.properties:
scanPackage=myspringmvc.mycontroller
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" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<servlet>
<servlet-name>MyDispatcherServlet</servlet-name>
<servlet-class>myspringmvc.servlet.MyDispatcherServlet</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>MyDispatcherServlet</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
</web-app>
4.主逻辑类 MyDispatcherServlet
package myspringmvc.servlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MyDispatcherServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
private 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 {
//加载配置文件
doLoadConfig(config.getInitParameter("contextConfigLocation"));
//初始化所有相关联得类,扫描用户设定得包下面所有得类
doScanner(properties.getProperty("scanPackage"));
//拿到扫描的类,通过反射机制实例化,并放到ioc容器中(k-v,beanName-bean),beanName默认是首字母小写
doInstance();
//初始化HandlerMapping,将url和method对应上
initHandleMapping();
}
private void initHandleMapping() {
if(ioc.isEmpty()){
return;
}
try {
for(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();
}
}
private void doInstance() {
if(classNames.isEmpty()){
return;
}
for(String className: classNames){
//获得类,通过反射实例化(只有加@controller的类实例化)
try {
Class<?> clazz = Class.forName(className);
if(clazz.isAnnotationPresent(MyController.class)){
ioc.put(toLowerFistWord(clazz.getSimpleName()), clazz.newInstance());
}else{
continue;
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
private String toLowerFistWord(String name) {
char[] charArray = name.toCharArray();
charArray[0] += 32;
return String.valueOf(charArray);
}
private void doScanner(String packageName) {
//把所有的“.”替换成“/”
URL url = this.getClass().getClassLoader().getResource("/"+packageName.replaceAll("\\.", "/"));
File dir = new File(url.getFile());
for(File file: dir.listFiles()){
if(file.isDirectory()){
//递归读取包
doScanner(packageName + "." + file.getName());
}else{
String className = packageName + "." + file.getName().replace(".class", "");
classNames.add(className);
}
}
}
private void doLoadConfig(String location) {
//把web.xml里面contextConfigLocation对应value值得文件加载到流里面
InputStream asStream = this.getClass().getClassLoader().getResourceAsStream(location);
try {
//用properties文件加载文件里面得内容
properties.load(asStream);
} catch (IOException e) {
e.printStackTrace();
}finally{
if(asStream != null){
try {
asStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
@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 {
//处理请求
doDispatcher(req,resp);
} catch (Exception e) {
resp.getWriter().write("500!!server Exception");
}
}
private void doDispatcher(HttpServletRequest req, HttpServletResponse resp) throws Exception {
if(handlerMapping.isEmpty()){
return;
}
//getRequestUrl返回全路径,req.getUri返回出去host或是域名以外的路径
String url = req.getRequestURI();
String contextPath = req.getContextPath();
url = url.replace(contextPath, "").replaceAll("/+", "/");
if(!this.handlerMapping.containsKey(url)){
resp.getWriter().write("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(Entry<String, String[]> param: parameterMap.entrySet()){
String value = Arrays.toString(param.getValue()).replaceAll("\\[|\\]", "").replaceAll(",\\s", ",");
paramValues[i] = value;
}
}
}
try {
//利用反射机制来调用(invoke方法就是动态调用Method类代表的方法)
method.invoke(this.controllerMap.get(url), paramValues);//第一个参数时method对应的实例,再ioc容器中(invoke最终调用的时sun.reflect.MethodAccessor)
} catch (Exception e) {
e.printStackTrace();
}
}
}
5.测试类 NewController
package myspringmvc.mycontroller;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import myspringmvc.servlet.MyController;
import myspringmvc.servlet.MyRequestMapping;
import myspringmvc.servlet.MyRequestParam;
@MyController
@MyRequestMapping("/test")
public class NewController {
@MyRequestMapping("/test1")
public void test1(HttpServletRequest request, HttpServletResponse response,
@MyRequestParam("param") String param){
System.out.println(param);
try {
response.getWriter().write( "doTest method success! param:"+param);
} catch (IOException e) {
e.printStackTrace();
}
}
@MyRequestMapping("/doTest2")
public void test2(HttpServletRequest request, HttpServletResponse response){
try {
response.getWriter().println("doTest2 method success!");
} catch (IOException e) {
e.printStackTrace();
}
}
}
本地访问地址:http://localhost:8080/myspringmvc/test/test1
上述主逻辑类中对各个模块做了详细的说明,可以帮助更好的了解springmvc的原理,这里不作赘述。