先用一张图来描述一下mvc框架
意思就只写一个servlet,然后就通过这一个servlet用handleMapping这个映射器找到相应的类和方法,当然还需要配置一下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>DispatcherServlet</servlet-name>
<servlet-class>DispatcherServlet所在项目中的位置</servlet-class>
<init-param>
<param-name>contentConfigLocation</param-name>
<param-value>application.properties</param-value>
</init-param>
<load-on-startup>0</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
话不多说,直接上代码
DispatcherServlet.java
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
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;
public class DispatcherServlet extends javax.servlet.http.HttpServlet {
@Override
public void init(ServletConfig config) throws ServletException {
String path = config.getInitParameter("contentConfigLocation");
InputStream is = DispatcherServlet.class.getClassLoader().getResourceAsStream(path);
HandlerMapping.load(is);
}
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取用户请求的uri /xx.do
String uri = req.getRequestURI();
HandlerMapping.MVCMapping mapping = HandlerMapping.get(uri);
if( mapping == null){
resp.sendError(404,"MVC:映射地址不存在:"+uri);
return;
}
Object obj = mapping.getObj();
Method method = mapping.getMethod();
Object result = null;
try {
result = method.invoke(obj, req, resp);
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
}
switch (mapping.getType()){
case TEXT:
resp.getWriter().write((String)result);
break;
case VIEW:
resp.sendRedirect((String)result);
break;
}
}
}
HandleMapping.java(映射器)
import java.io.IOException;
import java.io.InputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;
/**
* 映射器(包含了大量的网址与方法的对应关系)
*/
public class HandlerMapping {
private static Map<String,MVCMapping> data = new HashMap<>();
public static MVCMapping get(String uri){
return data.get(uri);
}
public static void load(InputStream is ){
Properties ppt = new Properties();
try {
ppt.load(is);
} catch (IOException e) {
e.printStackTrace();
}
//获取配置文件中描述的一个个的类
Collection<Object> values = ppt.values();
for (Object cla:values) {
String className = (String) cla;
try {
//加载配置文件中描述的每一个类
Class c = Class.forName(className);
//创建这个类的对象
Object obj = c.getConstructor().newInstance();
//获取这个类的所有方法
Method[] methods = c.getMethods();
for (Method m:methods) {
Annotation[] as = m.getAnnotations();
if(as != null){
for(Annotation annotation:as){
if(annotation instanceof ResponseBody){
//说明此方法,用于返回字符串给客户端
MVCMapping mapping = new MVCMapping(obj,m,ResponseType.TEXT);
Object o = data.put(((ResponseBody) annotation).value(),mapping);
if(o != null){
//存在了重复的请求地址
throw new RuntimeException("请求地址重复:"+((ResponseBody) annotation).value());
}
}else if(annotation instanceof ResponseView){
//说明此方法,用于返回界面给客户端
MVCMapping mapping = new MVCMapping(obj,m,ResponseType.VIEW);
Object o = data.put(((ResponseView) annotation).value(),mapping);
if(o != null){
//存在了重复的请求地址
throw new RuntimeException("请求地址重复:"+((ResponseView) annotation).value());
}
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
/**
* 映射对象,每一个对象封装了一个方法,用于处理请求
*/
public static class MVCMapping{
private Object obj;
private Method method;
private ResponseType type;
public MVCMapping() {
}
public MVCMapping(Object obj, Method method, ResponseType type) {
this.obj = obj;
this.method = method;
this.type = type;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
public Method getMethod() {
return method;
}
public void setMethod(Method method) {
this.method = method;
}
public ResponseType getType() {
return type;
}
public void setType(ResponseType type) {
this.type = type;
}
}
}
ResponseBody.java(注解)
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
/**
* 注解的作用:
* 被此注解添加的方法, 会被用于处理请求。
* 方法返回的内容,会以文字形式返回到客户端
*/
public @interface ResponseBody {
String value();
}
ResponseView.java
import java.lang.annotation.*;
@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
@Documented
/**
* 注解的作用:
* 被此注解添加的方法, 会被用于处理请求。
* 方法返回的内容,会直接重定向
*/
public @interface ResponseView {
String value();
}
application.properties文件配置,等号左边的命名必须要有但是怎么命名都可以,等号右边是相应处理类所在的位置
a=xxx.xxx.xxx.java
b=xxx.xxx.xxx.java
例如:
好了,程序猿之路漫漫,继续秃头。