---
title: "超轻量级MVC框架的设计和实现 (2)"
author: "mmdev"
date: "2007-11-21T17:05:00Z"
tags: []
slug: "mvc-2"
draft: false
lastmod: "2007-11-21T17:05:00Z"
id: 1006596
url: "https://mmdev.iteye.com/blog/1006596"
---

在设计完API后，我们就需要实现这个MVC框架。MVC框架的核心是一个DispatcherServlet，用于接收所有的HTTP请求，并根据URL选择合适的Action对其进行处理。在这里，和Struts不同的是，所有的组件均被IoC容器管理，因此，DispatcherServlet需要实例化并持有Guice IoC容器，此外，DispatcherServlet还需要保存URL映射和Action的对应关系，一个Interceptor拦截器链，一个ExceptionResolver处理异常。DispatcherServlet定义如下：

package com.[javaeedev](http://www.javaeedev.com/).lightweight.mvc;

/\**  
\* Core dispatcher servlet.  
\*  
\* @author Xuefeng  
\*/  
public class DispatcherServlet extends HttpServlet {

private Log log = LogFactory.getLog(getClass());

private Map&lt;String, ActionAndMethod&gt; actionMap;  
private Interceptor\[] interceptors = null;  
private ExceptionResolver exceptionResolver = null;  
private ViewResolver viewResolver = null;

private Injector injector = null; // Guice IoC容器

...  
}

Guice的配置完全由Java 5注解完成，而在DispatcherServlet中，我们需要主动从容器中查找某种类型的Bean，相对于客户端被动地使用IoC容器（客户端甚至不能感觉到IoC容器的存在），DispatcherServlet需要使用ServiceLocator模式主动查找Bean，写一个通用方法：

private List&lt;Key&lt;?&gt;&gt; findKeysByType(Injector inj, Class&lt;?&gt; type) {  
Map&lt;Key&lt;?&gt;, Binding&lt;?&gt;&gt; map = inj.getBindings();  
List&lt;Key&lt;?&gt;&gt; keyList = new ArrayList&lt;Key&lt;?&gt;&gt;();  
for(Key&lt;?&gt; key : map.keySet()) {  
Type t = key.getTypeLiteral().getType();  
if(t instanceof Class&lt;?&gt;) {  
Class&lt;?&gt; clazz = (Class&lt;?&gt;) t;  
if(type==null || type.isAssignableFrom(clazz)) {  
keyList.add(key);  
}  
}  
}  
return keyList;  
}

DispatcherServlet初始化时就要首先初始化Guice IoC容器：

public void init(ServletConfig config) throws ServletException {  
String moduleClass = config.getInitParameter("module");  
if(moduleClass==null || moduleClass.trim().equals(""))  
throw new ServletException("Cannot find init parameter in web.xml: &lt;servlet&gt;"  
\+ "&lt;servlet-name&gt;?&lt;/servlet-name&gt;&lt;servlet-class&gt;"  
\+ getClass().getName()  
\+ "&lt;/servlet-class&gt;&lt;init-param&gt;&lt;param-name&gt;module&lt;/param-name&gt;&lt;param-value&gt;"  
\+ "put-your-config-module-full-class-name-here&lt;/param-value&gt;&lt;/init-param&gt;&lt;/servlet&gt;");  
ServletContext context = config.getServletContext();  
// init guice:  
injector = Guice.createInjector(Stage.PRODUCTION, getConfigModule(moduleClass.trim(), context));  
...  
}

然后，从IoC容器中查找Action和URL的映射关系：

private Map&lt;String, ActionAndMethod&gt; getUrlMapping(List&lt;Key&lt;?&gt;&gt; actionKeys) {  
Map&lt;String, ActionAndMethod&gt; urlMapping = new HashMap&lt;String, ActionAndMethod&gt;();  
for(Key&lt;?&gt; key : actionKeys) {  
Object obj = safeInstantiate(key);  
if(obj==null)  
continue;  
Class&lt;Action&gt; actionClass = (Class&lt;Action&gt;) obj.getClass();  
Annotation ann = key.getAnnotation();  
if(ann instanceof Named) {  
Named named = (Named) ann;  
String url = named.value();  
if(url!=null)  
url = url.trim();  
if(!"".equals(url)) {  
log.info("Bind action \[" + actionClass.getName() + "] to URL: " + url);  
// link url with this action:  
urlMapping.put(url, new ActionAndMethod(key, actionClass));  
}  
else {  
log.warn("Cannot bind action \[" + actionClass.getName() + "] to \*EMPTY* URL.");  
}  
}  
else {  
log.warn("Cannot bind action \[" + actionClass.getName() + "] because no @Named annotation found in config module. Using: binder.bind(MyAction.class).annotatedWith(Names.named(\\"/url\\"));");  
}  
}  
return urlMapping;  
}

我们假定客户端是以如下方式配置Action和URL映射的：

public class MyModule implements Module {

public void configure(Binder binder) {  
// bind actions:  
binder.bind(Action.class)  
.annotatedWith(Names.named("/start.do"))  
.to(StartAction.class);  
binder.bind(Action.class)  
.annotatedWith(Names.named("/register.do"))  
.to(RegisterAction.class);  
binder.bind(Action.class)  
.annotatedWith(Names.named("/signon.do"))  
.to(SignonAction.class);  
...  
}  
}

即通过Guice提供的一个注解Names.named()指定URL。当然还可以用其他方法，比如标注一个@Url注解可能更方便，下一个版本会加上。

Interceptor，ExceptionResolver和ViewResolver也是通过查找获得的。

下面讨论DispatcherServlet如何真正处理用户请求。第一步是根据URL查找对应的Action：

String contextPath = request.getContextPath();  
String url = request.getRequestURI().substring(contextPath.length());  
if(log.isDebugEnabled())  
log.debug("Handle for URL: " + url);  
ActionAndMethod am = actionMap.get(url);  
if(am==null) {  
response.sendError(HttpServletResponse.SC\_NOT\_FOUND); // 404 Not Found  
return;  
}

没找到Action就直接给个404 Not Found，找到了进行下一步，实例化一个Action并填充参数：

// init ActionContext:  
HttpSession session = request.getSession();  
ServletContext context = session.getServletContext();

ActionContext.setActionContext(request, response, session, context);

// 每次创建一个新的Action实例:  
Action action = (Action) injector.getInstance(am.getKey());  
// 把HttpServletRequest的参数自动绑定到Action的属性中:  
List&lt;String&gt; props = am.getProperties();  
for(String prop : props) {  
String value = request.getParameter(prop);  
if(value!=null) {  
am.invokeSetter(action, prop, value);  
}  
}

注意，为了提高速度，所有的set方法已经预先缓存了，因此避免每次请求都用反射重复查找Action的set方法。

然后要应用所有的Interceptor以便拦截Action：

InterceptorChainImpl chains = new InterceptorChainImpl(interceptors);  
chains.doInterceptor(action);  
ModelAndView mv = chains.getModelAndView();

实现InterceptorChain看上去复杂，其实就是一个简单的递归，大家看InterceptorChainImpl代码就知道了：

package com.[javaeedev](http://www.javaeedev.com/).lightweight.mvc;

/\**  
\* Used for holds an interceptor chain.  
\*  
\* @author Xuefeng  
\*/  
class InterceptorChainImpl implements InterceptorChain {

private final Interceptor\[] interceptors;  
private int index = 0;  
private ModelAndView mv = null;

InterceptorChainImpl(Interceptor\[] interceptors) {  
this.interceptors = interceptors;  
}

ModelAndView getModelAndView() {  
return mv;  
}

public void doInterceptor(Action action) throws Exception {  
if(index==interceptors.length)  
// 所有的Interceptor都执行完毕:  
mv = action.execute();  
else {  
// 必须先更新index，再调用interceptors\[index-1]，否则是一个无限递归:  
index++;  
interceptors\[index-1].intercept(action, this);  
}  
}  
}

把上面的代码用try ... catch包起来，就可以应用ExceptionResolver了。

如果得到了ModelAndView，最后一步就是渲染View了，这个过程极其简单：

// render view:  
private void render(ModelAndView mv, HttpServletRequest reqest, HttpServletResponse response) throws ServletException, IOException {  
String view = mv.getView();  
if(view.startsWith("redirect:")) {  
// 重定向:  
String redirect = view.substring("redirect:".length());  
response.sendRedirect(redirect);  
return;  
}  
Map&lt;String, Object&gt; model = mv.getModel();  
if(viewResolver!=null)  
viewResolver.resolveView(view, model, reqest, response);  
}

最简单的JspViewResolver的实现如下：

package com.[javaeedev](http://www.javaeedev.com/).lightweight.mvc.view;

/\**  
\* Let JSP render the model returned by Action.  
\*  
\* @author Xuefeng  
\*/  
public class JspViewResolver implements ViewResolver {

/\**  
\* Init JspViewResolver.  
\*/  
public void init(ServletContext context) throws ServletException {  
}

/\**  
\* Render view using JSP.  
\*/  
public void resolveView(String view, Map&lt;String, Object&gt; model, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
if(model!=null) {  
Set&lt;String&gt; keys = model.keySet();  
for(String key : keys) {  
request.setAttribute(key, model.get(key));  
}  
}  
request.getRequestDispatcher(view).forward(request, response);  
}  
}

至此，MVC框架的核心已经完成。