DispatcherServlet是一个继承Servlet封装的类,相当于一个前置控制器,配置在web.xml文件当中的,拦截匹配的请求,Servlet拦截匹配规则要自己定义,将拦截下来的请求按照相应的规则分发到目标Controller来处理
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMVC.xmlparam-value>
init-param>
<load-on-startup>0load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
代码如下:
import java.io.Serializable;
import java.lang.reflect.Method;
public class RequestMap implements Serializable {
private Method method;
private Object object;
private String requestMethod;
public RequestMap() {
}
public RequestMap(Method method, Object object, String requestMethod) {
super();
this.method = method;
this.object = object;
this.requestMethod = requestMethod;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public Object getObject() {
return object;
}
public void setObject(Object object) {
this.object = object;
}
public String getRequestMethod() {
return requestMethod;
}
public void setRequestMethod(String requestMethod) {
this.requestMethod = requestMethod;
}
@Override
public String toString() {
return "RequestMap{" +
"method=" + method +
", object=" + object +
", requestMethod='" + requestMethod + '\'' +
'}';
}
}
代码如下:
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;
@Target({ElementType.TYPE, ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface RequestMapping {
String value();
String method() default "get";
}
代码如下:
import cn.hutool.cron.CronUtil;
import cn.hutool.cron.task.Task;
import cn.hutool.db.Db;
import cn.hutool.db.Entity;
import com.annotation.RequestMapping;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.nio.charset.StandardCharsets;
import java.sql.SQLException;
import java.util.*;
// 通过@WebServlet来拦截请求
// 也可以配置到web.xml文件中,这就是一个Servlet
@WebServlet("/")
public class DispatcherServlet extends HttpServlet {
// 映射地址和Request对象
public final static Map<String, RequestMap> map = new HashMap<>();
// 静态资源
public final static List<String> staticList = new ArrayList<>();
@Override
public void init(ServletConfig config) throws ServletException {
ServletContext servletContext = config.getServletContext();
String realPath = servletContext.getRealPath("/");
// servlet的目录
File file = new File(realPath + "\\WEB-INF\\classes\\com\\controller");
// 获取servlet目录下的所有类
String[] list = file.list();
File staticFile = new File(realPath);
FileUtil.itemFile(staticFile, staticList, realPath);
assert list != null;
for (String string : list) {
// 截取类名称
String name = string.substring(0, string.lastIndexOf("."));
try {
// 通过反射获取Class对象
Class<?> c = Class.forName("com.controller." + name);
// 判断该类上是否有RequestMapping注解
String value = "";
if (c.isAnnotationPresent(RequestMapping.class)) {
// 获取注解,进行强制转换成RequestMapping对象
RequestMapping annotation = c.getAnnotation(RequestMapping.class);
// 获取RequestMapping对象的值
value += annotation.value();
}
// 获取所有的方法
// 没有就调用父类的service方法
Method[] methods = c.getDeclaredMethods();
// 循环遍历判断是否RequestMapping这个注解
for (Method method : methods) {
if (method.isAnnotationPresent(RequestMapping.class)) {
RequestMapping meRequestMapping = method.getAnnotation(RequestMapping.class);
String requestMethod = meRequestMapping.method();
String meValue = meRequestMapping.value();
// 创建继承HttpServlet的类
Object o = c.newInstance();
// 添加Servlet
map.put(value + meValue, new RequestMap(method, o, requestMethod));
}
}
} catch (ClassNotFoundException | IllegalArgumentException | InstantiationException | IllegalAccessException e) {
e.printStackTrace();
}
}
// 这三个是我做的项目功能,你们可以不用
//selectId(ApiDataUtils.INFORMATION);
//selectId(ApiDataUtils.ROOT_ID);
//selectId(ApiDataUtils.ROOT_DETAIL_ID);
// 这是一个定时器
//CronUtil.schedule("*/1 * * * *", (Task) () -> {
// System.out.println("每一分钟执行一次,图片删除");
// try {
// List headPhoto = Db.use().query("select head_photo from information where head_photo is not null and head_photo != ''", String.class);
// String path = getServletContext().getRealPath("/page/image/head");
// File staticPath = new File(path);
// if (staticPath.exists() && headPhoto != null){
// String[] fileList = staticPath.list();
// if (fileList != null){
// for (String s : fileList) {
// if (!headPhoto.contains("/cartoon/page/image/head/" + s)){
// boolean delete = new File(staticPath, s).delete();
// if (delete){
// System.out.println("成功删除-" + s + "-文件");
// }
// }
// }
// }
// }
// } catch (SQLException e) {
// e.printStackTrace();
// }
// });
// CronUtil.setMatchSecond(true);
// CronUtil.start();
super.init(config);
}
/**
这个是我其他项目功能你们可以不用
**/
public void selectId(int choose) {
Entity entity = null;
try {
switch (choose) {
case ApiDataUtils.INFORMATION:
entity = Db.use().queryOne("select * from information order by id desc limit 1");
if (entity == null) {
ApiDataUtils.INFORMATION_ID = 1;
} else {
ApiDataUtils.INFORMATION_ID = entity.getInt("id") + 1;
}
break;
case ApiDataUtils.ROOT:
entity = Db.use().queryOne("select * from root order by id desc limit 1");
if (entity == null) {
ApiDataUtils.ROOT_ID = 1;
} else {
ApiDataUtils.ROOT_ID = entity.getInt("id") + 1;
}
break;
case ApiDataUtils.ROOT_DETAIL:
entity = Db.use().queryOne("select * from root_detail by id desc limit 1");
if (entity == null) {
ApiDataUtils.ROOT_DETAIL_ID = 1;
} else {
ApiDataUtils.ROOT_DETAIL_ID = entity.getInt("id") + 1;
}
break;
}
} catch (SQLException e) {
e.printStackTrace();
}
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
Set<String> keySet = map.keySet();
String uri = req.getRequestURI().replace(req.getContextPath(), "");
if (keySet.contains(uri)) {
RequestMap requestMap = map.get(uri);
if (req.getMethod().toLowerCase().equals(requestMap.getRequestMethod())) {
try {
resp.setContentType("application/json;charset=utf-8");
requestMap.getMethod().invoke(requestMap.getObject(), req, resp);
} catch (IllegalAccessException | InvocationTargetException | IllegalArgumentException e) {
// 这边是异常处理500
e.printStackTrace();
resp.setStatus(500);
resp.setContentType("text/html;charset=UTF-8");
ServletOutputStream outputStream = resp.getOutputStream();
outputStream.write("HTTP状态 500 - 内部服务器错误 HTTP状态 500 - 内部服务器错误
".getBytes(StandardCharsets.UTF_8));
outputStream.write("注意 主要问题的全部在控制台里查看
Apache Tomcat/8.5.76
".getBytes(StandardCharsets.UTF_8));
outputStream.close();
}
} else {
// 这边是异常处理405
resp.setStatus(405);
resp.setContentType("text/html;charset=UTF-8");
OutputStream writer = resp.getOutputStream();
writer.write(("HTTP状态 405 - 方法不允许 HTTP状态 405 - 方法不允许
类型 状态报告
消息 此URL不支持Http方法POST
描述 请求行中接收的方法由源服务器知道,但目标资源不支持
"
+ getServletContext().getServerInfo() + "").getBytes(StandardCharsets.UTF_8));
writer.close();
}
} else {
resp.setContentType(FileUtil.responseType(uri) + ";charset=UTF-8");
OutputStream writer = resp.getOutputStream();
if (staticList.contains(uri)) {
String realPath = req.getServletContext().getRealPath("/");
File file = new File(realPath + "/" + uri);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(file));
byte[] arr = new byte[1024];
int l;
while ((l = in.read(arr, 0, 1024)) != -1) {
writer.write(arr, 0, l);
}
return;
}
// 这边是异常处理404
resp.setStatus(404);
resp.setContentType("text/html;charset=UTF-8");
writer.write(("HTTP状态 404 - 未找到 HTTP状态 404 - 未找到
类型 状态报告
消息 请求的资源[/]不可用
描述 源服务器未能找到目标资源的表示或者是不愿公开一个已经存在的资源表示。
"
+ getServletContext().getServerInfo() + "").getBytes(StandardCharsets.UTF_8));
writer.close();
}
}
@Override
public void destroy() {
CronUtil.stop();
super.destroy();
}
}
码云仓库地址:https://gitee.com/lan_nan/cartoon
登录页面
首页
以上就是通过对Servlet和DispatcherServlet的理解来完成这个功能,当然还有很多缺陷,就比如静态资源的上传,需要我手动调用才能配置一个映射地址,希望大家多多支持。