初始化

master
niuniuniu 2023-11-01 08:26:54 +08:00
commit 528f61742a
14 changed files with 418 additions and 0 deletions

38
.gitignore vendored 100644
View File

@ -0,0 +1,38 @@
target/
!.mvn/wrapper/maven-wrapper.jar
!**/src/main/**/target/
!**/src/test/**/target/
### IntelliJ IDEA ###
.idea/modules.xml
.idea/jarRepositories.xml
.idea/compiler.xml
.idea/libraries/
*.iws
*.iml
*.ipr
### Eclipse ###
.apt_generated
.classpath
.factorypath
.project
.settings
.springBeans
.sts4-cache
### NetBeans ###
/nbproject/private/
/nbbuild/
/dist/
/nbdist/
/.nb-gradle/
build/
!**/src/main/**/build/
!**/src/test/**/build/
### VS Code ###
.vscode/
### Mac OS ###
.DS_Store

8
.idea/.gitignore vendored 100644
View File

@ -0,0 +1,8 @@
# 默认忽略的文件
/shelf/
/workspace.xml
# 基于编辑器的 HTTP 客户端请求
/httpRequests/
# Datasource local storage ignored files
/dataSources/
/dataSources.local.xml

11
.idea/aws.xml 100644
View File

@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="accountSettings">
<option name="activeRegion" value="us-east-1" />
<option name="recentlyUsedRegions">
<list>
<option value="us-east-1" />
</list>
</option>
</component>
</project>

View File

@ -0,0 +1,7 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="Encoding">
<file url="file://$PROJECT_DIR$/src/main/java" charset="UTF-8" />
<file url="file://$PROJECT_DIR$/src/main/resources" charset="UTF-8" />
</component>
</project>

20
.idea/misc.xml 100644
View File

@ -0,0 +1,20 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="CodeInsightWorkspaceSettings">
<option name="optimizeImportsOnTheFly" value="true" />
</component>
<component name="ExternalStorageConfigurationManager" enabled="true" />
<component name="MarkdownSettingsMigration">
<option name="stateVersion" value="1" />
</component>
<component name="MavenProjectsManager">
<option name="originalFiles">
<list>
<option value="$PROJECT_DIR$/pom.xml" />
</list>
</option>
</component>
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" project-jdk-name="17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>

6
.idea/vcs.xml 100644
View File

@ -0,0 +1,6 @@
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$" vcs="Git" />
</component>
</project>

65
pom.xml 100644
View File

@ -0,0 +1,65 @@
<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.brave</groupId>
<artifactId>untitled7</artifactId>
<packaging>war</packaging>
<version>1.0-SNAPSHOT</version>
<name>untitled7 Maven Webapp</name>
<url>http://maven.apache.org</url>
<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>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.reflections</groupId>
<artifactId>reflections</artifactId>
<version>0.9.11</version>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.2</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.*</include>
</includes>
</resource>
</resources>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<version>2.5.2</version>
</plugin>
</plugins>
</build>
</project>

View File

@ -0,0 +1,15 @@
package com.brave.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target(ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyController {
String value() default "";
}

View File

@ -0,0 +1,14 @@
package com.brave.annotation;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface MyRequestMapping {
String value() default "";
}

View File

@ -0,0 +1,24 @@
package com.brave.controller;
import com.brave.annotation.MyController;
import com.brave.annotation.MyRequestMapping;
@MyRequestMapping(value = "/test")
@MyController
public class TestController {
@MyRequestMapping(value = "/test1")
public void test1() {
System.out.println("test1被调用");
}
@MyRequestMapping(value = "/test2")
public void test2() {
System.out.println("test2被调用了");
}
@MyRequestMapping(value = "/test3")
public void test3(){
System.out.println("test3被调用了");
}
}

View File

@ -0,0 +1,183 @@
package com.brave.servlet;
import com.brave.annotation.MyController;
import com.brave.annotation.MyRequestMapping;
import org.reflections.Reflections;
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.IOException;
import java.io.InputStream;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.*;
public class MyDispatcherServlet extends HttpServlet {
/**
* .properties
*/
private Properties properties=new Properties();
/**
* setcontroller
*/
private Set<Class<?>> classSet=new HashSet<>();
/**
* SpringMVC
*/
private Map<String, Object> springMVCContext=new HashMap<>();
/**
*
*/
private Map<String, Method> handlerMapping=new HashMap<>();
/**
* controller
*/
private Map<String,Object> controllerMap=new HashMap<>();
@Override
public void init(ServletConfig config) throws ServletException {
//加载配置文件在web.xml中配置的初始化参数contextfigLocation
String initParameter = config.getInitParameter("contextConfigLocation");
try {
loadConfigFile(initParameter);
}catch (Exception e){
e.printStackTrace();
}
//扫描controller
scanPackage(properties.getProperty("package"));
//初始化controller包
initController();
//初始化处理器映射器
initHandlerMapping();
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp){
//处理请求
if (handlerMapping.isEmpty()){
return;
}
//获取url
String uri = req.getRequestURI();
String contextPath = req.getContextPath();
String url = uri.replace(contextPath, "");
if (!handlerMapping.containsKey(url)){
try {
resp.getWriter().println("404");
} catch (IOException e) {
throw new RuntimeException(e);
}
}else {
Method method = handlerMapping.get(url);
Object controller = controllerMap.get(url);
try {
method.invoke(controller);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
}
private void initHandlerMapping() {
if (springMVCContext.isEmpty()){
return;
}
for (Map.Entry<String, Object> entry : springMVCContext.entrySet()) {
//获取class对象
Class<?> aClass = entry.getValue().getClass();
if (!aClass.isAnnotationPresent(MyController.class)){
continue;
}else {
String baseUrl="";
if (aClass.isAnnotationPresent(MyRequestMapping.class)){
//如果类包含注解MyRequestMapping获取注解值
MyRequestMapping annotation = aClass.getAnnotation(MyRequestMapping.class);
baseUrl=annotation.value();
}
//获取所有方法
Method[] methods=aClass.getMethods();
for (Method method : methods) {
//判断方法上含有MyRequestMapping注解
if (method.isAnnotationPresent(MyRequestMapping.class)){
MyRequestMapping annotation = method.getAnnotation(MyRequestMapping.class);
String url = annotation.value();
url = baseUrl +url;
//将该放入方法集
handlerMapping.put(url,method);
try {
//放入controllerMap中
controllerMap.put(url,aClass.newInstance());
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
}
}
}
private void initController() {
if (classSet.isEmpty()){
return;
}
for (Class<?> controller : classSet) {
try {
springMVCContext.put(lowerFirstWord(controller.getSimpleName()), controller.newInstance());
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
private String lowerFirstWord(String simpleName) {
char[] array = simpleName.toCharArray();
array[0] +=32;
return String.valueOf(array);
}
private void scanPackage(String packageName) {
Reflections reflections = new Reflections(packageName);
classSet=reflections.getTypesAnnotatedWith(MyController.class);
}
private void loadConfigFile(String fileName) {
//以流的方式获取资源
InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream(fileName);
try {
properties.load(inputStream);
} catch (IOException e) {
throw new RuntimeException(e);
}finally {
try {
inputStream.close();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}

View File

@ -0,0 +1,22 @@
<?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">
<!-- 配置我们自己的前端控制器MyDispatcherServlet就是一个servlet拦截前端发送的请求-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>com.brave.servlet.MyDispatcherServlet</servlet-class>
<!-- 配置扫描包-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>application.properties</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<!-- 拦截所有请求-->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>

View File

@ -0,0 +1,5 @@
<html>
<body>
<h2>Hello World!</h2>
</body>
</html>