更新项目

master
王堂东 2023-10-29 22:25:29 +08:00
parent e0ce85f9c5
commit d304a0dad8
16 changed files with 305 additions and 217 deletions

62
pom.xml
View File

@ -16,9 +16,67 @@
<dependencies>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.3</version>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>dom4j</groupId>
<artifactId>dom4j</artifactId>
<version>1.6.1</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.5</version>
</dependency>
<dependency>
<groupId>com.sun.xml.bind</groupId>
<artifactId>jaxb-impl</artifactId>
<version>2.3.1</version>
</dependency>
<dependency>
<groupId>com.sun.xml.messaging.saaj</groupId>
<artifactId>saaj-impl</artifactId>
<version>1.5.1</version>
</dependency>
</dependencies>
<build>
<finalName>SpringMvc</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.3.0</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.10.1</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.2</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.4.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>3.0.1</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>3.0.0</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>

View File

@ -1,4 +1,4 @@
package com.wtd.annotation;
package com.enjoy.wtd.annotation;
import java.lang.annotation.*;

View File

@ -1,4 +1,4 @@
package com.wtd.annotation;
package com.enjoy.wtd.annotation;
import java.lang.annotation.*;

View File

@ -1,4 +1,4 @@
package com.wtd.annotation;
package com.enjoy.wtd.annotation;
import java.lang.annotation.*;

View File

@ -1,4 +1,4 @@
package com.wtd.annotation;
package com.enjoy.wtd.annotation;
import java.lang.annotation.*;

View File

@ -1,4 +1,4 @@
package com.wtd.annotation;
package com.enjoy.wtd.annotation;
import java.lang.annotation.*;

View File

@ -1,10 +1,10 @@
package com.wtd.controller;
package com.enjoy.wtd.controller;
import com.wtd.annotation.WtdAutowiredAnnotation;
import com.wtd.annotation.WtdControllerAnnotation;
import com.wtd.annotation.WtdRequestMappingAnnotation;
import com.wtd.annotation.WtdRequestParamAnnotation;
import com.wtd.service.WtdService;
import com.enjoy.wtd.annotation.WtdControllerAnnotation;
import com.enjoy.wtd.annotation.WtdRequestMappingAnnotation;
import com.enjoy.wtd.annotation.WtdRequestParamAnnotation;
import com.enjoy.wtd.annotation.WtdAutowiredAnnotation;
import com.enjoy.wtd.service.WtdService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

View File

@ -1,4 +1,4 @@
package com.wtd.service;
package com.enjoy.wtd.service;
/**
* @program: wtd-mvc

View File

@ -1,7 +1,7 @@
package com.wtd.service.impl;
package com.enjoy.wtd.service.impl;
import com.wtd.annotation.WtdServiceAnnotation;
import com.wtd.service.WtdService;
import com.enjoy.wtd.annotation.WtdServiceAnnotation;
import com.enjoy.wtd.service.WtdService;
/**
* @program: wtd-mvc
@ -13,6 +13,6 @@ import com.wtd.service.WtdService;
public class WtdServiceImpl implements WtdService {
@Override
public String query(String name, String age) {
return "name==="+name+"; age==="+age;
return "name="+name+"; age="+age;
}
}

View File

@ -0,0 +1,228 @@
package com.enjoy.wtd.servlet;
import com.enjoy.wtd.annotation.*;
import com.enjoy.wtd.controller.WtdController;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @program: wtd-mvc
* @description:
* @author: Mr.Wang
* @create: 2023-10-28 17:02
**/
public class DispatcherServlet extends HttpServlet {
List<String> classNames = new ArrayList<String>();
Map<String,Object> beans = new HashMap<String,Object>();
Map<String,Object> handlerMap = new HashMap<String,Object>();
private static final long serialVersionUID = 1L;
public void init(ServletConfig config){
//把所有的bean扫描----扫描所有的class文件
scanPackage("com.enjoy"); //写到properties
doInstance(); //根据全类名创建bean
doIco();//根据bean进行依赖注入
buildUrlMapping(); // 建立映射关系
}
//com.enjoy
private void scanPackage(String basePackage){
URL url = this.getClass().getClassLoader().getResource("/"+basePackage.replaceAll("\\.","/"));
String fileStr = url.getFile();
File file = new File(fileStr);
String[] filesStr = file.list(); //spc
for (String path : filesStr) {
File filePath = new File(fileStr+path); //com.enjoy.spc...
if (filePath.isDirectory()){
scanPackage(basePackage+"."+path);
}else {
//加入list
classNames.add(basePackage+"."+filePath.getName()); //com.enjoy...xxx.class
}
}
}
//根据扫描的list全类名进行实例化
private void doInstance(){
if (classNames.size() <= 0){
System.out.println("报扫描失败.......");
return;
}
//list的所有class类对这些类进行
for (String className : classNames) {
String cn = className.replace(".class","");
try {
Class<?> clazz = Class.forName(cn); //com.enjoy.SpcController
if (clazz.isAnnotationPresent(WtdControllerAnnotation.class)){
Object instace = clazz.newInstance(); //创建控制类
WtdRequestMappingAnnotation requestMapping = clazz.getAnnotation(WtdRequestMappingAnnotation.class);
String rmvalue = requestMapping.value(); // /spc
beans.put(rmvalue,instace);
}else if (clazz.isAnnotationPresent(WtdServiceAnnotation.class)){
WtdServiceAnnotation service = clazz.getAnnotation(WtdServiceAnnotation.class);
Object instance = clazz.newInstance();
beans.put(service.value(),instance);
}else {
continue;
}
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (InstantiationException e) {
throw new RuntimeException(e);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}
}
//把nacos注入到controller
public void doIco(){
if (beans.entrySet().size() <= 0){
System.out.println("没有一个实例化类");
}
//把map里所有的实例化遍历出来
for (Map.Entry<String,Object> entry : beans.entrySet()){
Object instance = entry.getValue();
Class<?> clazz = instance.getClass();
if (clazz.isAnnotationPresent(WtdControllerAnnotation.class)){
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if (field.isAnnotationPresent(WtdAutowiredAnnotation.class)){
WtdAutowiredAnnotation auto = field.getAnnotation(WtdAutowiredAnnotation.class);
String key = auto.value(); //spcServiceImpl
field.setAccessible(true);
try {
field.set(instance,beans.get(key));
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
}
}else {
continue;
}
}
}else{
continue;
}
}
}
private void buildUrlMapping(){
if (beans.entrySet().size() <= 0){
System.out.println("没有类的实例化......");
return;
}
for (Map.Entry<String , Object> entry: beans.entrySet()){
Object instance = entry.getValue();
Class<?> clazz = instance.getClass();
if (clazz.isAnnotationPresent(WtdControllerAnnotation.class)){
WtdRequestMappingAnnotation requestMapping = clazz.getAnnotation(WtdRequestMappingAnnotation.class);
String classPath = requestMapping.value();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if (method.isAnnotationPresent(WtdRequestMappingAnnotation.class)){
WtdRequestMappingAnnotation methodMapping = method.getAnnotation(WtdRequestMappingAnnotation.class);
String methodPath = methodMapping.value();
handlerMap.put(classPath+methodPath, method);
}else {
continue;
}
}
}else {
continue;
}
}
}
@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 {
// 获取请求路径 /spc-mvc/spc/query v/spc/query->method
String uri = req.getRequestURI();
String context = req.getContextPath(); //spc-mvc
String path = uri.replace(context, ""); //spc/query
Method method = (Method) handlerMap.get(path);
//根据 key=/spc到map去拿
WtdController instance = (WtdController) beans.get("/" + path.split("/")[1]);// /spc
Object arg[] = hand(req, resp, method);
try {
method.invoke(instance,arg);
} catch (IllegalAccessException e) {
throw new RuntimeException(e);
} catch (InvocationTargetException e) {
throw new RuntimeException(e);
}
}
private static Object[] hand(HttpServletRequest request,HttpServletResponse response,Method method){
//拿到当前待执行的方法有哪些参数
Class<?>[] paramClazzs = method.getParameterTypes();
//根据参数的个数new 一个参数的数组将方法里的所有参数值到args来
Object[] args = new Object[paramClazzs.length];
int args_i = 0;
int index = 0;
for (Class<?> paramClazz : paramClazzs) {
if (ServletRequest.class.isAssignableFrom(paramClazz)){
args[args_i++] = request;
}
if (ServletResponse.class.isAssignableFrom(paramClazz)){
args[args_i++] = response;
}
// 从0-3判断有没有RequestParam注解很明显paramClazz为0和1时不是
// 当为2和3时为@RequestParam,需更解析
// 当为2和3时为@RequestParam,需更解析
java.lang.annotation.Annotation[] paramAns = method.getParameterAnnotations()[index];
if (paramAns.length > 0 ){
for (Annotation paramAn : paramAns) {
if (WtdRequestParamAnnotation.class.isAssignableFrom(paramAn.getClass())){
WtdRequestParamAnnotation rp =(WtdRequestParamAnnotation) paramAn ;
//找到注解里的name和age
args[args_i++] = request.getParameter(rp.value());
}
}
}
index++;
}
return args;
}
}

View File

@ -1,198 +0,0 @@
package com.wtd.servlet;
import com.wtd.annotation.*;
import com.wtd.controller.WtdController;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import java.text.Annotation;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* @program: wtd-mvc
* @description:
* @author: Mr.Wang
* @create: 2023-10-28 17:02
**/
public class DispatcherServlet extends HttpServlet {
List<String> classNames=new ArrayList<>();
Map<String,Object> beans=new HashMap<String,Object>();
Map<String,Object> handlerMap=new HashMap<String,Object>();
public void init(ServletConfig config){
scanPackage("com.wtd");//写到properties
doInstance();//根据全类名创建bean
doIoc();//根据bean进行依赖注入
buildUrlMapping();
}
public void scanPackage(String basePackage){
URL url=this.getClass().getClassLoader().getResource("/"+basePackage.replaceAll("\\.","/"));
String fileStr=url.getFile();
File file=new File(fileStr);
String[] filesStr = file.list();
for (String path : filesStr) {
File filePath=new File(fileStr+path);
if(filePath.isDirectory()){
scanPackage(basePackage+"."+path);
}else{
classNames.add(basePackage+"."+filePath.getName());
}
}
}
//根据扫描出来的全类名 进行实例化
private void doInstance(){
if(classNames.size()<0){
System.out.println("扫描失败");
return;
}
//遍历list里面所有的class类
for (String className : classNames) {
String cn = className.replace(".class", "");
try {
Class<?> clazz = Class.forName(cn);
if(clazz.isAnnotationPresent(WtdControllerAnnotation.class)){
Object instance = clazz.newInstance();
WtdRequestMappingAnnotation requestMappingAnnotation = clazz.getAnnotation(WtdRequestMappingAnnotation.class);
String rmValue=requestMappingAnnotation.value();
beans.put(rmValue,instance);
}else if(clazz.isAnnotationPresent(WtdServiceAnnotation.class)){
WtdServiceAnnotation service=clazz.getAnnotation(WtdServiceAnnotation.class);
Object instance=clazz.newInstance();
beans.put(service.value(),instance);
}else {
continue;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}
}
//把service注入到controller
public void doIoc(){
if(!(beans.entrySet().size() > 0)){
System.out.println("没有一个实例类");
}
for (Map.Entry<String,Object> entry:beans.entrySet()){
Object instance=entry.getValue();
Class<?> clazz = instance.getClass();
if(clazz.isAnnotationPresent(WtdControllerAnnotation.class)){
Field[] fields = clazz.getDeclaredFields();
for (Field field : fields) {
if(field.isAnnotationPresent(WtdAutowiredAnnotation.class)){
WtdAutowiredAnnotation auto=field.getAnnotation(WtdAutowiredAnnotation.class);
String key=auto.value();
field.setAccessible(true);
try {
field.set(instance,beans.get(key));
} catch (IllegalAccessException e) {
e.printStackTrace();
}
}else {
continue;
}
}
}else {
continue;
}
}
}
private void buildUrlMapping(){
if(!(beans.entrySet().size() > 0)){
System.out.println("没有类的实例化");
return;
}
for (Map.Entry<String,Object> entry:beans.entrySet()){
Object instance=entry.getValue();
Class<?> clazz=instance.getClass();
if(clazz.isAnnotationPresent(WtdControllerAnnotation.class)){
WtdRequestMappingAnnotation requestMappingAnnotation=clazz.getAnnotation(WtdRequestMappingAnnotation.class);
String classPath = requestMappingAnnotation.value();
Method[] methods = clazz.getMethods();
for (Method method : methods) {
if(method.isAnnotationPresent(WtdRequestMappingAnnotation.class)){
WtdRequestMappingAnnotation methodMapping=method.getAnnotation(WtdRequestMappingAnnotation.class);
String methodPath=methodMapping.value();
handlerMap.put(classPath+methodPath,method);
}else {
continue;
}
}
}else {
continue;
}
}
}
@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 {
String uri=req.getRequestURI();
String context=req.getContextPath();
String path=uri.replace(context,"");
Method method=(Method) handlerMap.get(path);
//根据key=/wtd到map去拿
WtdController instance=(WtdController) beans.get("/"+path.split("/")[1]);
Object arg[]=hand(req,resp,method);
try {
method.invoke(instance,arg);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
}
private static Object[] hand(HttpServletRequest request,HttpServletResponse response,Method method){
Class<?>[] paramClazzs = method.getParameterTypes();
Object[] args=new Object[paramClazzs.length];
int args_i=0;
int index=0;
for (Class<?> paramClazz : paramClazzs) {
if(ServletRequest.class.isAssignableFrom(paramClazz)){
args[args_i++]=request;
}
if(ServletResponse.class.isAssignableFrom(paramClazz)){
args[args_i++]=response;
}
Annotation[] paramAns= (Annotation[]) method.getParameterAnnotations()[index];
if(paramAns.length>0){
for (Annotation paramAn : paramAns) {
if(WtdRequestParamAnnotation.class.isAssignableFrom(paramAn.getClass())){
WtdRequestParamAnnotation rp=(WtdRequestParamAnnotation) paramAn;
args[args_i++]=request.getParameter(rp.value());
}
}
}
index++;
}
return args;
}
}

Binary file not shown.

Binary file not shown.

Binary file not shown.

View File

@ -6,7 +6,7 @@
<display-name>wtd-mvc</display-name>
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>com.wtd.servlet.DispatcherServlet</servlet-class>
<servlet-class>com.enjoy.wtd.servlet.DispatcherServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>