今天这篇文章就是打算带大家深入的理解一下什么是MVC框架,以及MVC框架的原理,我相信很多人都会用MVC框架比如说SpringMVC、Struts2等但是我相信很大一部分人并不理解他的原理。所以今天这篇文章就带大家去感受一下吧,我就以自己写的一个MVC框架为例子给大家讲解一下吧!
最起初的开发基本都是基于Jsp/Servlet/JavaBean的MVC开发模式,但是这种模式下很有很多的问题,比如开发复杂、重复代码过多不易维护等问题,于是框架应运而生。框架说道底使用的技术无非就是反射技术,要是想学好框架不懂反射一切白扯。
进入正题:当你写一个mvc框架时首先要启动框架让框架运行起来,框架使用的是servlet或者filter来启动,我这里就以filter启动实现的:这里类似于SpringMVC的前端控制器(但是SpringMVC前端控制器使用的Servlet,Struts2采用的是Filter)
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<filter>
<display-name>BaseFilter</display-name>
<filter-name>BaseFilter</filter-name>
<filter-class>com.loveight.filter.BaseFilter</filter-class>
<init-param>
<param-name>package</param-name>
<param-value>com.loveight</param-value>
</init-param>
<init-param>
<param-name>packages</param-name>
<param-value>com.test</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>BaseFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
其中init-param参数表示Action所属的包名,可以传递多个包名,该过滤器拦截所有的请
接下来我们来BaseFilter过滤器的源代码:
public class BaseFilter implements Filter {
private AnnotationCache annotationCache;
private AnnotationFilterCache annotationFilterCache;
public void doFilter(ServletRequest req, ServletResponse resp,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
String url = request.getRequestURI();// /laopo/Login
String root = request.getContextPath(); //
String uri = url.replace(root, "");
List<FilterItem> lists = annotationFilterCache.getFilter(uri);
Iterator<FilterItem> it = lists.iterator();
while (it.hasNext()) {
FilterItem filterItem = it.next();
BaseIntercept baseIntercept = new BaseIntercept(request, response, filterItem);
if(!baseIntercept.intercept()){
return;
}
}
ActionItem actionItem = annotationCache.getAction(uri);
if (actionItem == null) {
chain.doFilter(request, response);
return;
}
BaseHandle baseHandle = new BaseHandle(request, response, annotationCache, actionItem);
baseHandle.createResponse(null);
}
public void destroy() {
}
public void init(FilterConfig filterConfig) throws ServletException {
Enumeration<String> enumeration = filterConfig.getInitParameterNames();
List<String> packages = new ArrayList<String>();
while (enumeration.hasMoreElements()) {
String name = enumeration.nextElement();
packages.add(filterConfig.getInitParameter(name));
}
List<Class<?>> list = ScannerPackage.packages(packages);
annotationCache = ClassReflect.getActionClass(list);
annotationFilterCache = AnnotationFilterCache.newIntance();
}
}
首先框架启动的时候我们需要扫描class文件从class文件中找到@Action的注解并且将其缓存起来,这样当请求过来时我们可以从缓存中取出应该的处理类,从而来反射创建以响应客户端的请求。这里init方法会在框架第一次启动时执行,这样我们便可以将url和类的对应关系缓存到内存里(这里的扫描结果将缓存到AnnotationCache(单例模式)对象中)。这里对应的就是springmvc中的处理器映射器。
doFilter方法会响应客户端的每一次请求当一次请求过来时,根据doFilter方法内的代码会干这几件事:首先获取请求的url,然后根据url从AnnotationCache中取出url对应的处理类,若在未找到值则表示该请求无对应资源则直接放行,这时我们会取得一个ActionItem对象,该类源码如下:
public class ActionItem {
private String actionPath;
private String methodPath;
private String methodName;
private Annotation annotation;
private Class cls;
public String getActionPath() {
return actionPath;
}
public void setMethodName(String methodName) {
this.methodName = methodName;
}
public String getMethodName() {
return methodName;
}
public void setActionPath(String actionPath) {
this.actionPath = actionPath;
}
public void setMethodPath(String methodPath) {
this.methodPath = methodPath;
}
public String getMethodPath() {
return methodPath;
}
public Annotation getAnnotation() {
return annotation;
}
public Class getCls() {
return cls;
}
public void setAnnotation(Annotation annotation) {
this.annotation = annotation;
}
public void setCls(Class cls) {
this.cls = cls;
}
@Override
public String toString() {
return "ActionItem{" +
"actionPath='" + actionPath + '\'' +
", methodPath='" + methodPath + '\'' +
", methodName='" + methodName + '\'' +
", annotation=" + annotation +
", cls=" + cls +
'}';
}
}
该对象会包含此次请求对应的类字节码对象,以及请求对应的方法和请求类型(转发、重定向、值)
当拿到这个对象后根据字节码对象反射来创建该对象,然后再试请求参数封装,将该次请求的参数反射封装到该对象的成员变量里,然后用反射执行该方法,响应代码如下:
public class BaseHandle extends RequestHandle {
private ActionItem actionItem;
public BaseHandle(HttpServletRequest request, HttpServletResponse response, AnnotationCache annotationCache, ActionItem actionItem) {
super(request, response, annotationCache);
this.actionItem = actionItem;
}
public void createResponse(String url) {
Log.log("请求对象已创建","info");
try {
Object obj = actionItem.getCls().newInstance();
setParameter2Field(obj);
if (url != null && url.length() > 0) {
setNotFirstParam(url, obj);
}
setSessionAndServletContext2Field(obj);
if (obj instanceof Context) {
Context context = (Context) obj;
context.setSession(getRequest().getSession());
context.setServletContext(getRequest().getServletContext());
if (obj instanceof SuperContext) {
SuperContext superContext = (SuperContext) obj;
superContext.setRequest(getRequest());
superContext.setResponse(getResponse());
}
}
Method met = actionItem.getCls().getMethod(actionItem.getMethodName());
Annotation annotation = actionItem.getAnnotation();
Object resObj = met.invoke(obj);
setField2RequestDomain(obj) ;
if (annotation instanceof Forward) {
String data = (String) resObj;
ActionItem actionItemSecond = getAnnotationCache().getAction(data);
if (actionItemSecond == null) {
forward(data, obj);
} else {
BaseHandle baseHandle = new BaseHandle(getRequest(), getResponse(), getAnnotationCache(), actionItemSecond);
baseHandle.createResponse(data);
}
}
if (annotation instanceof Binary) {
byte[] data = (byte[]) resObj;
responseBinary(data);
}
// if (annotation instanceof File) {
// String data = (String) met.invoke(obj);
// }
if (annotation instanceof Redirect) {
String data = (String) resObj;
redirection(data);
}
if (annotation instanceof Value) {
String data = (String) resObj;
returnValue(data);
}
if (annotation instanceof Original) {
String data = (String) resObj;
return;
}
// if (annotation instanceof Upload) {
// String data = (String) met.invoke(obj);
// }
if (annotation instanceof Image) {
Object data = resObj;
returnImage(data);
}
} catch (Exception e) {
e.printStackTrace();
}
System.gc();
Log.log("请求对象已销毁","info");
}
}
这块内容类似于SpringMVC里的处理器适配器。
等执行完方法后获取返回值若是转发(Forward)则转发到该结果视图,若是重定向则重定向(Redirect)到该结果视图。若是值(Value)得话直接返回。这里类似于SpringMVC里的视图解析器但是这里没有做视图的切换,暂时只能支持JSP若想使用freemaker velocity可能还要开发。源码如下:
public class ResponseHandle extends ConstantHandle {
public ResponseHandle(HttpServletRequest request,
HttpServletResponse response, AnnotationCache annotationCache) {
super(request, response, annotationCache);
}
protected void responseBinary(byte[] data) {
try {
getResponse().getWriter().println(data);
} catch (Exception e) {
}
}
protected void forward(String url, Object obj) {
try {
getRequest().getRequestDispatcher(url).forward(getRequest(), getResponse());
} catch (Exception e) {
e.printStackTrace();
}
}
protected void returnImage(Object data) {
getResponse().setHeader("Pragma", "no-cache");
getResponse().setHeader("Cache-Control", "no-cache");
getResponse().setDateHeader("Expires", 0);
getResponse().setContentType("image/jpeg");
try {
ImageIO.write((RenderedImage) data, "jpeg", getResponse().getOutputStream());
} catch (Exception e) {
e.printStackTrace();
}
}
protected void setField2RequestDomain(Object obj) {
Field[] field = obj.getClass().getDeclaredFields();
for (int i = 0; i < field.length; i++) {
FieldItem fieldItem = getAnnotationCache().getField(obj.getClass().getName() + field[i].getName());
field[i].setAccessible(true);
String name = field[i].getName();
Object value = null;
try {
value = field[i].get(obj);
} catch (Exception e) {
e.printStackTrace();
}
if (value == null && fieldItem == null) {
continue;
}
if (fieldItem != null) {
if (fieldItem.getAnnotation() instanceof Format && value != null) {
if (fieldItem.getParam() != null && ((String) fieldItem.getParam()).trim().length() > 0) {
SimpleDateFormat sdf = new SimpleDateFormat(fieldItem.getParam().toString());
try {
value = sdf.format(value);
} catch (Exception e) {
}
}
}
if (fieldItem.getAnnotation() instanceof ServletContext) {
Log.log("设置值" + value + "到ServletContext", "info");
getRequest().getServletContext().setAttribute((String) fieldItem.getParam(), value);
}
if (fieldItem.getAnnotation() instanceof Session) {
Log.log("设置值" + value + "到Session", "info");
getRequest().getSession().setAttribute((String) fieldItem.getParam(), value);
}
if (fieldItem.getAnnotation() instanceof UnField) {
continue;
}
}
getRequest().setAttribute(name, value);
}
}
protected void redirection(String url) {
try {
getResponse().sendRedirect(url);
} catch (Exception e) {
e.printStackTrace();
}
}
protected void returnValue(String value) {
try {
getResponse().getWriter().println(value);
} catch (Exception e) {
e.printStackTrace();
}
}
}
这个框架的工作简要流程如上图所示,如想看框架的具体功能请看下一遍文章。该框架是小弟大学毕业时所写,当时能力有限,若有不妥之处请批评改正。如需具体源码请联系QQ543142141。