实现思路
配置阶段
步骤 | 作用 |
---|
配置web.xml | DispatcherServlet |
配置init-param | contextConfigLocation |
配置param-value | classpath:application.properties |
配置Annotation | @Autowired,@Service,@Controller, @RequestMapping,@RequestParam |
初始化阶段
步骤 | 作用 |
---|
调用init()方法 | 加载配置文件 |
扫描相关类 | scan_package=zone.baize.v1 |
IOC容器初始化 | Map<String, Object> ioc |
依赖注入 | 扫描IOC容器中的实例,给没有赋值的属性自动赋值 |
初始化处理器映射器 | Map<String, Method> handlerMapping |
运行阶段
步骤 | 说明 |
---|
调用doGet()/doPost() | Web容器调用doGet()/doPost()访问 |
匹配handlerMapping | 从中找到对应的方法 |
反射调用具体需要执行的方法 | 调用方法并返回结果 |
自定义配置
配置application.properties文件
scan_package=zone.baize.v1
配置Web.xml文件
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>baiZeServlet</servlet-name>
<servlet-class>zone.baize.v1.servlet.BaiZeServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:application.properties</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>baiZeServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
添加依赖
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
配置插件
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgs>
<arg>-parameters</arg>
</compilerArgs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
<configuration>
<path>/</path>
<port>8080</port>
</configuration>
</plugin>
</plugins>
自定义注解
@Autowired
@Documented
@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Autowired {}
@Service
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Service {
String value() default "";
}
@Controller
@Documented
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Controller {
String value() default "";
}
@RequestMapping
@Documented
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestMapping {
String value() default "";
}
@RequestParam
@Documented
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
public @interface RequestParam {
String value() default "";
}
编写Service
public interface UserService {
String query(String name);
}
@Service
public class UserServiceImpl implements UserService {
@Override
public String query(String name) {
return "hello " + name;
}
}
编写Controller
@Controller
@RequestMapping("/user")
public class UserController {
@Autowired
private UserService userService;
@RequestMapping("/query")
public String query(@RequestParam String name) {
return userService.query(name);
}
}
编写前端控制器
package zone.baize.v1.servlet;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.*;
import java.net.URL;
import java.util.*;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import zone.baize.v1.anno.*;
public class BaiZeServlet extends HttpServlet {
private Properties configContext = new Properties();
private List<String> classNames = new ArrayList<>();
private Map<String, Object> ioc = new HashMap<>();
private Map<String, Method> handlerMapping = new HashMap<>();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String requestURI = req.getRequestURI().replaceAll("/+", "/");
if (!handlerMapping.containsKey(requestURI)) {
resp.setStatus(404);
resp.getWriter().write("404 NOT FOUND");
return;
}
Method method = handlerMapping.get(requestURI);
Parameter[] parameters = method.getParameters();
Object[] objects = new Object[parameters.length];
for (int i = 0; i < parameters.length; i++) {
if (parameters[i].getType() == HttpServletRequest.class) {
objects[i] = req;
} else if (parameters[i].getType() == HttpServletResponse.class) {
objects[i] = resp;
} else {
String arg = null;
if (parameters[i].isAnnotationPresent(RequestParam.class)) {
String parameter = parameters[i].getAnnotation(RequestParam.class).value().trim();
arg = parameter.equals("") ? null : parameter;
}
objects[i] = req.getParameter(arg != null ? arg : parameters[i].getName());
}
}
Object invoke = null;
try {
invoke = method.invoke(ioc.get(toLowerFirstCase(method.getDeclaringClass().getSimpleName())), objects);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
resp.getWriter().write(invoke.toString());
}
@Override
public void init(ServletConfig config) throws ServletException {
doLoadConfig(config.getInitParameter("contextConfigLocation"));
doScanner(configContext.getProperty("scan_package"));
doInitIoc();
doAutowired();
doInitHandlerMapping();
System.out.println("项目启动成功!");
}
private void doLoadConfig(String contextConfigLocation) {
InputStream inputStream =
this.getClass().getClassLoader().getResourceAsStream(contextConfigLocation.replaceAll("classpath:", ""));
try {
configContext.load(inputStream);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private void doScanner(String scanPackage) {
URL url = this.getClass().getResource("/" + scanPackage.replaceAll("\\.", "/"));
File root = new File(url.getFile());
for (File file : Objects.requireNonNull(root.listFiles())) {
if (file.isDirectory()) {
doScanner(scanPackage + "." + file.getName());
}
if (file.getName().endsWith(".class")) {
String classPath = file.getName().replace(".class", "");
classNames.add(scanPackage + "." + classPath);
}
}
}
private void doInitIoc() {
if (classNames.isEmpty()) {
return;
}
try {
for (String className : classNames) {
Class<?> clazz = Class.forName(className);
if (clazz.isAnnotationPresent(Controller.class) && !clazz.isInterface()) {
Object instance = clazz.newInstance();
String value = clazz.getAnnotation(Controller.class).value();
if (value.trim().length() > 0) {
ioc.put(value, instance);
}
ioc.put(toLowerFirstCase(clazz.getSimpleName()), instance);
}
if (clazz.isAnnotationPresent(Service.class) && !clazz.isInterface()) {
Object instance = clazz.newInstance();
String value = clazz.getAnnotation(Service.class).value();
if (value.trim().length() > 0) {
ioc.put(value, instance);
}
ioc.put(toLowerFirstCase(clazz.getSimpleName()), instance);
for (Class<?> aClass : clazz.getInterfaces()) {
String simpleName = toLowerFirstCase(aClass.getSimpleName());
if (ioc.containsKey(simpleName)) {
throw new Exception("the " + simpleName + "is not unique");
}
ioc.put(simpleName, instance);
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
private String toLowerFirstCase(String str) {
if (str.length() == 0) {
return str;
}
char[] chars = str.toCharArray();
if (chars[0] >= 'A' && chars[0] <= 'Z') {
chars[0] += 32;
}
return String.valueOf(chars);
}
private void doAutowired() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
for (Field field : entry.getValue().getClass().getDeclaredFields()) {
if (field.isAnnotationPresent(Autowired.class)) {
field.setAccessible(true);
try {
field.set(entry.getValue(), ioc.get(field.getName()));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
}
}
private void doInitHandlerMapping() {
if (ioc.isEmpty()) {
return;
}
for (Map.Entry<String, Object> entry : ioc.entrySet()) {
Class<?> clazz = entry.getValue().getClass();
if (!clazz.isAnnotationPresent(Controller.class)) {
continue;
}
String classUrl = clazz.isAnnotationPresent(RequestMapping.class)
? clazz.getAnnotation(RequestMapping.class).value() : "";
for (Method method : clazz.getMethods()) {
if (method.isAnnotationPresent(RequestMapping.class)) {
String methodUrl = method.isAnnotationPresent(RequestMapping.class)
? method.getAnnotation(RequestMapping.class).value() : "";
String url = "/" + classUrl + "/" + methodUrl;
handlerMapping.put(url.replaceAll("/+", "/"), method);
}
}
}
}
}
启动验证