版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
对于SpringMVC不了解的小友,可以看下A版的mvc框架介绍
所以,直接上代码:
项目目录结构
@Autowired注解
package com.mymvc.annotation;
import java.lang.annotation.*;
/**
* 实现自动注入
*/
@Documented
@Target(ElementType.FIELD) // 作用于字段上,实现注入
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {
String value() default "";
}
@Controller注解
package com.mymvc.annotation;
import java.lang.annotation.*;
/**
* 控制层注解
*/
@Documented // JAVADOC
@Target(ElementType.TYPE) // 作用于类上
@Retention(RetentionPolicy.RUNTIME) // 限制Annotation的生命周期,需要运行时保留
public @interface Controller {
/**
* 作用于该类上的注解有一个value属性,就是controller的名称
*/
String value() default "";
}
@RequestMapping注解
package com.mymvc.annotation;
import java.lang.annotation.*;
/**
* 地址映射处理注解
*/
@Documented
@Target({ ElementType.METHOD, ElementType.TYPE }) // 该注解可用于类以及方法上
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String value();
}
@RequestParam注解
package com.mymvc.annotation;
import java.lang.annotation.*;
/**
*
*/
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestParam {
String value();
}
@Service注解
package com.mymvc.annotation;
import java.lang.annotation.*;
/**
* 业务层注解
*/
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Service {
String value() default "";
}
DispatcherServlet (编写核心控制器)
在Spring MVC中,DispatcherServlet是核心,下面我们来实现它。首先来说,Spring MVC中的DispatcherServlet说到底,还是HttpServlet的子类,因此我这边自己的DispatcherSerlvet需要extends HttpServlet。
先添加pom依赖,提供servlet依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
<scope>provided</scope>
</dependency>
package com.mymvc.servlet;
import com.mymvc.annotation.Autowired;
import com.mymvc.annotation.Controller;
import com.mymvc.annotation.RequestMapping;
import com.mymvc.annotation.Service;
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.*;
/**
* MVC框架的请求分发中转
*/
public class DispatcherServlet extends HttpServlet {
private Properties properties = new Properties();
private List<String> classNames = new ArrayList<String>();
private Map<String, Object> ioc = new HashMap<String, Object>();
// handlerMapping的类型可以自定义为handler
private Map<String, Method> handlerMapping = new HashMap<String, Method>();
private Map<String, Object> controllerMap = new HashMap<String, Object>();
@Override
public void init(ServletConfig config) throws ServletException {
super.init();
// 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();
doAutowired2();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 注释掉父类实现,不然会报错:405 HTTP method GET is not supported by this URL
// super.doPost(req, resp);
try {
// 处理请求
doDispatch(req, resp);
} catch (Exception e) {
resp.getWriter().write("500!! Server Exception");
}
}
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 注释掉父类实现,不然会报错:405 HTTP method GET is not supported by this URL
// super.doGet(req, resp);
try {
// 处理请求
doDispatch(req, resp);
} catch (Exception e) {
resp.getWriter().write("500!! Server Exception");
}
}
private void doDispatch(HttpServletRequest req, HttpServletResponse resp) throws Exception {
if (handlerMapping.isEmpty()) {
return;
}
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 (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);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description: 根据配置文件位置,读取配置文件中的配置信息,将其填充到properties字段 Params:
*
* @param location:
* 配置文件的位置
*/
private void doLoadConfig(String location) {
// 把web.xml中的contextConfigLocation对应value值的文件加载到流里面
InputStream resourceAsStream = this.getClass().getClassLoader().getResourceAsStream(location);
try {
// 用Properties文件加载文件里的内容
properties.load(resourceAsStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
// 关流
if (null != resourceAsStream) {
try {
resourceAsStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* Description: 将指定包下扫描得到的类,添加到classNames字段中; Params:
*
* @param packageName:
* 需要扫描的包名
*/
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);
}
}
}
/**
* Description: 将classNames中的类实例化,经key-value:类名(小写)-类对象放入ioc字段中 Params:
*/
private void doInstance() {
if (classNames.isEmpty()) {
return;
}
for (String className : classNames) {
try {
// 把类搞出来,反射来实例化(只有加@Controller需要实例化)
Class<?> clazz = Class.forName(className);
if (clazz.isAnnotationPresent(Controller.class)) {
ioc.put(toLowerFirstWord(clazz.getSimpleName()), clazz.newInstance());
} else if (clazz.isAnnotationPresent(Service.class)) {
Service service = clazz.getAnnotation(Service.class);
String beanName = service.value();
if ("".equals(beanName.trim())) {
beanName = toLowerFirstWord(clazz.getSimpleName());
}
Object instance = clazz.newInstance();
ioc.put(beanName, instance);
Class[] interfaces = clazz.getInterfaces();
for (Class<?> i : interfaces) {
ioc.put(i.getName(), instance);
}
} else {
continue;
}
} catch (Exception e) {
e.printStackTrace();
continue;
}
}
}
/**
* Description:自动化的依赖注入 Params:
*/
private void doAutowired() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
// 包括私有的方法,在spring中没有隐私,@Autowired可以注入public、private字段
Field[] fields = entry.getValue().getClass().getDeclaredFields();
for (Field field : fields) {
if (!field.isAnnotationPresent(Autowired.class)) {
continue;
}
Autowired autowired = field.getAnnotation(Autowired.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;
}
}
}
}
private void doAutowired2() {
if (controllerMap.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : controllerMap.entrySet()) {
// 包括私有的方法,在spring中没有隐私,@Autowired可以注入public、private字段
Field[] fields = entry.getValue().getClass().getDeclaredFields();
for (Field field : fields) {
if (!field.isAnnotationPresent(Autowired.class)) {
continue;
}
Autowired autowired = field.getAnnotation(Autowired.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;
}
}
}
}
/**
* Description: 初始化HandlerMapping(将url和method对应上) Params:
*/
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(Controller.class)) {
continue;
}
// 拼url时,是controller头的url拼上方法上的url
String baseUrl = "";
if (clazz.isAnnotationPresent(RequestMapping.class)) {
RequestMapping requestMapping = clazz.getAnnotation(RequestMapping.class);
baseUrl = requestMapping.value();
}
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (!method.isAnnotationPresent(RequestMapping.class)) {
continue;
}
RequestMapping requestMapping = method.getAnnotation(RequestMapping.class);
String url = requestMapping.value();
// 将所有路径前面都默认添加/处理(请求的RequestMapping路径可加可不加/)
if (baseUrl.indexOf("/") != 0) {
url = ("/" + baseUrl + "/" + url).replaceAll("/+", "/");
} else {
url = (baseUrl + "/" + url).replaceAll("/+", "/");
}
handlerMapping.put(url, method);
controllerMap.put(url, clazz.newInstance());
System.out.println(url + "," + method);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Description: 将字符串中的首字母小写 Params:
*/
private String toLowerFirstWord(String name) {
char[] charArray = name.toCharArray();
charArray[0] += 32;
return String.valueOf(charArray);
}
}
web.xml(配置DispatcherServlet请求控制中心)
<servlet>
<servlet-name>MyMVC</servlet-name>
<servlet-class>com.mymvc.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>myapplication.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>
myapplication.properties
添加扫描包路径(扫描包下所有注解)
scanPackage=com.mymvc
UserController
package com.mymvc.controller;
import com.mymvc.annotation.Autowired;
import com.mymvc.annotation.Controller;
import com.mymvc.annotation.RequestMapping;
import com.mymvc.annotation.RequestParam;
import com.mymvc.service.UserService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/printParam")
public void printParam(HttpServletRequest request, HttpServletResponse response,
@RequestParam("param") String param) {
try {
response.getWriter().write("UserController:the param you send is :" + param);
userService.printParam(param);
} catch (IOException e) {
e.printStackTrace();
}
}
}
UserService
package com.mymvc.service;
public interface UserService {
public void printParam(String param);
}
UserServiceImpl
package com.mymvc.service;
import com.mymvc.annotation.Service;
@Service
public class UserServiceImpl implements UserService {
@Override
public void printParam(String param) {
System.out.println("接收到的参数为:" + param);
}
}
效果
供参考!