看struts2源码已有一段时日,从今天开始,就做一个总结吧。
首先,先看看怎么调试struts2源码吧,主要是以下步骤:
使用Myeclipse创建一个web工程
导入struts2需要的jar包
如图:
让jar包关联源文件
在上图中的jar包右键,选择properties->java source attach,如果关联成功,双击jar包下的某个class文件就会显示java源代码了。
双击.class文件,在源代码关键地方设置断点
部署工程到Tomcat
Tomcat以Debug方式启动
经过以上步骤,即可执行单步调试了,这样就可以很方便的查看代码的运行状态了。
struts2框架作为MVC框架,主要作用就是帮助处理请求,以一种与web容器无关的方式。也就是说,处理请求时可以不使用HttpServletRequest等类。struts2采用Filter来拦截请求,判断如果是struts2可以处理的,请求就进入struts2框架进行处理,否则请求进入下一个Filter。
先从Filter的初始化开始来看struts2吧,因为这也是struts2框架初始化的过程。
ok,我们看看struts2的StrutsPrepareAndExecuteFilter类的init()方法:
public void init(FilterConfig filterConfig) throws ServletException {
InitOperations init = new InitOperations();
Dispatcher dispatcher = null;
try {
FilterHostConfig config = new FilterHostConfig(filterConfig);//只是进行了一层薄薄的封装
init.initLogging(config);//初始化用户在配置filter时定义的logger
dispatcher = init.initDispatcher(config);//创建一个转发器,并初始化
init.initStaticContentLoader(config, dispatcher);//初始化静态资源加载器
prepare = new PrepareOperations(filterConfig.getServletContext(), dispatcher);
execute = new ExecuteOperations(filterConfig.getServletContext(), dispatcher);
this.excludedPatterns = init.buildExcludedPatternsList(dispatcher);
postInit(dispatcher, filterConfig);
} finally {
if (dispatcher != null) {
dispatcher.cleanUpAfterInit();
}
init.cleanup();
}
}
从以上代码可以归纳出,初始化主要完成以下这些事情:
1.封装init()的参数filterConfig成struts2定义的FilterHostConfig
只是进行了一层薄薄的封装,代码如下:
public class FilterHostConfig implements HostConfig {
private FilterConfig config;
public FilterHostConfig(FilterConfig config) {
this.config = config;
}
public String getInitParameter(String key) {
return config.getInitParameter(key);
}
public Iterator getInitParameterNames() {
return MakeIterator.convert(config.getInitParameterNames());
}
public ServletContext getServletContext() {
return config.getServletContext();
}
}
通过InitOperations类的initLogging()。InitOperations类主要是封装了一些初始化操作,以下是该类的所有方法,从名字也可以看出方法的功能。
public class InitOperations {
public InitOperations()
public void initLogging( HostConfig filterConfig )
public Dispatcher initDispatcher( HostConfig filterConfig )
public StaticContentLoader initStaticContentLoader( HostConfig filterConfig, Dispatcher dispatcher )
public Dispatcher findDispatcherOnThread()
private Dispatcher createDispatcher( HostConfig filterConfig )
public void cleanup()
public List buildExcludedPatternsList( Dispatcher dispatcher )
private List buildExcludedPatternsList( String patterns )
}
Dispatcher在struts2中是一个很重要的类,它的工作就是将filter拦截到的请求转入struts2的请求处理模块。当然,首先Dispatcher会被初始化,它的初始化方法init()可是干了很多的活呢。这部分在后面会细细的讲解,先看看大概是怎样一个过程吧。在InitOperations类中:
public Dispatcher initDispatcher( HostConfig filterConfig ) {
Dispatcher dispatcher = createDispatcher(filterConfig);
dispatcher.init();
return dispatcher;
}
private Dispatcher createDispatcher( HostConfig filterConfig ) {
Map params = new HashMap();
for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) {
String name = (String) e.next();
String value = filterConfig.getInitParameter(name);
params.put(name, value);
}
return new Dispatcher(filterConfig.getServletContext(), params);
}
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
filterParam
abc
public StaticContentLoader initStaticContentLoader( HostConfig filterConfig, Dispatcher dispatcher ) {
StaticContentLoader loader = dispatcher.getContainer().getInstance(StaticContentLoader.class);
loader.setHostConfig(filterConfig);
return loader;
}
StaticContentLoader是接口,看看该接口声明了哪些方法:
public interface StaticContentLoader {
public boolean canHandle(String path);
public abstract void setHostConfig(HostConfig filterConfig);
public abstract void findStaticResource(String path, HttpServletRequest request, HttpServletResponse response)
throws IOException;
}
如果struts2框架不处理静态资源的请求的话,谁来处理呢?自然是web容器了,比如tomcat。在StrutsPrepareAndExecuteFilter中:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
...
ActionMapping mapping = prepare.findActionMapping(request, response, true);
if (mapping == null) {
boolean handled = execute.executeStaticResourceRequest(request, response);
if (!handled) {
chain.doFilter(request, response);
}
} else {
execute.executeAction(request, response, mapping);
}
...
}
那么,如果要让struts2框架处理这样的请求,应该怎么做呢?
首先,自然是请求的路径要以struts或static开头了。
然后,静态资源应该存放在应用的如下几个包之一:
struts
org.apache.struts2.static
template
org.apache.struts2.interceptor.debugging
也可以自己在filter配置参数指定包名:
packages
abc
如此即可。
5.创建PrepareOperations对象和ExecuteOperations对象
PrepareOperations和ExecuteOperations有什么用呢?和InitOperations类似,封装一些操作。只不过InitOperations是封装初始化的操作,而前两者则是封装请求预处理和请求处理的操作,当处理请求时方法被调用。先看PrepareOperations有哪些操作:
public class PrepareOperations {
public PrepareOperations(ServletContext servletContext, Dispatcher dispatcher)
public ActionContext createActionContext(HttpServletRequest request, HttpServletResponse response)
public void cleanupRequest(HttpServletRequest request)
public void assignDispatcherToThread()
public void setEncodingAndLocale(HttpServletRequest request, HttpServletResponse response)
public HttpServletRequest wrapRequest(HttpServletRequest oldRequest)
public ActionMapping findActionMapping
(HttpServletRequest request, HttpServletResponse response)
public ActionMapping findActionMapping(HttpServletRequest request, HttpServletResponse response, boolean forceLookup)
public void cleanupDispatcher()
public boolean isUrlExcluded( HttpServletRequest request, List excludedPatterns )
private String getUri( HttpServletRequest request )
}
public class ExecuteOperations {
private ServletContext servletContext;
private Dispatcher dispatcher;
public ExecuteOperations(ServletContext servletContext, Dispatcher dispatcher) {
this.dispatcher = dispatcher;
this.servletContext = servletContext;
}
/**
* Tries to execute a request for a static resource
* @return True if it was handled, false if the filter should fall through
* @throws IOException
* @throws ServletException
*/
public boolean executeStaticResourceRequest(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
// there is no action in this request, should we look for a static resource?
String resourcePath = RequestUtils.getServletPath(request);
if ("".equals(resourcePath) && null != request.getPathInfo()) {
resourcePath = request.getPathInfo();
}
StaticContentLoader staticResourceLoader = dispatcher.getContainer().getInstance(StaticContentLoader.class);
if (staticResourceLoader.canHandle(resourcePath)) {
staticResourceLoader.findStaticResource(resourcePath, request, response);
// The framework did its job here
return true;
} else {
// this is a normal request, let it pass through
return false;
}
}
/**
* Executes an action
* @throws ServletException
*/
public void executeAction(HttpServletRequest request, HttpServletResponse response, ActionMapping mapping) throws ServletException {
dispatcher.serviceAction(request, response, servletContext, mapping);
}
}
6.封装配置filter时指定的不处理的action请求的pattern成List
这个配置是通过STRUTS_ACTION_EXCLUDE_PATTERN这个常量设置的。在struts.xml或者struts.properties文件中配置。
7.完成一些清理工作
其实也没清理多少东西了。ok,初始化的基本流程分析完了,但其中Dispatcher的初始化还是一个黑盒。所以下一篇struts2源码学习之初始化(二)就详细分析Dispatcher的初始化。