首页 > 代码库 > struts2源码学习之初始化(一)
struts2源码学习之初始化(一)
看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<String> getInitParameterNames() { return MakeIterator.convert(config.getInitParameterNames()); } public ServletContext getServletContext() { return config.getServletContext(); } }
2.初始化日志记录器,如果用户在web.xml中配置filter时配置了loggerFactory参数的话
通过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<Pattern> buildExcludedPatternsList( Dispatcher dispatcher ) private List<Pattern> buildExcludedPatternsList( String patterns ) }
3.创建Dispatcher并初始化
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<String, String> params = new HashMap<String, String>(); for ( Iterator e = filterConfig.getInitParameterNames(); e.hasNext(); ) { String name = (String) e.next(); String value = http://www.mamicode.com/filterConfig.getInitParameter(name);>
这里filter配置的参数会被保存如Dispatcher对象中,配置如:<filter> <filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class> <init-param> <param-name>filterParam</param-name> <param-value>abc</param-value> </init-param> </filter>
4.初始化静态资源加载器public StaticContentLoader initStaticContentLoader( HostConfig filterConfig, Dispatcher dispatcher ) { StaticContentLoader loader = dispatcher.getContainer().getInstance(StaticContentLoader.class); loader.setHostConfig(filterConfig); return loader; }
在完成了Dispatcher的初始化之后,struts2维护的一个容器Container就创建完成了,可以使用了。这里通过container创建一个StaticContentLoader对象。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有一个实现类为DefaultStaticContentLoader类。在一般情况下,struts2是不会处理静态资源的请求的,除非请求的路径是以struts或static开头,如有个test应用,那么请求必须是/test/struts/...或者/test/static/...这样才会处理。如果struts2框架不处理静态资源的请求的话,谁来处理呢?自然是web容器了,比如tomcat。在StrutsPrepareAndExecuteFilter中:
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException { <span style="white-space:pre"> </span>... 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); } ... }
可以看到,如果不处理,那么调用chain.doFilter(),请求也就不进入struts2框架了。那么,如果要让struts2框架处理这样的请求,应该怎么做呢?
首先,自然是请求的路径要以struts或static开头了。
然后,静态资源应该存放在应用的如下几个包之一:
struts
org.apache.struts2.static
template
org.apache.struts2.interceptor.debugging
也可以自己在filter配置参数指定包名:
<init-param> <param-name>packages</param-name> <param-value>abc</param-value> </init-param>
如果有多个包的话,可以用逗号分隔。如此即可。
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<Pattern> excludedPatterns ) private String getUri( HttpServletRequest request ) }
ExecuteOperations就简单得多了: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<Pattern>
这个配置是通过STRUTS_ACTION_EXCLUDE_PATTERN这个常量设置的。在struts.xml或者struts.properties文件中配置。
7.完成一些清理工作
其实也没清理多少东西了。
ok,初始化的基本流程分析完了,但其中Dispatcher的初始化还是一个黑盒。所以下一篇就详细分析Dispatcher的初始化。