Struts2架构图
chain,Filter主要包括ActionContextCleanUp,它主要清理当前线程的ActionContext和Dispatcher;FilterDispatcher主要通过AcionMapper来决定需要调用哪个Action。
ActionMapper取得了ActionMapping后,在Dispatcher的serviceAction方法里创建ActionProxy,ActionProxy创建ActionInvocation,然后ActionInvocation调用Interceptors,执行Action本身,创建Result并返回,当然,如果要在返回之前做些什么,可以实现PreResultListener。
Struts2部分类介绍
这部分从Struts2参考文档中翻译就可以了。
ActionMapper
ActionMapper其实是HttpServletRequest和Action调用请求的一个映射,它屏蔽了Action对于Request等java
Servlet类的依赖。Struts2中它的默认实现类是DefaultActionMapper,ActionMapper很大的用处可以根据自己的需要来设计url格式,它自己也有Restful的实现,具体可以参考文档的docs/actionmapper.html。
ActionProxy&ActionInvocation
Action的一个代理,由ActionProxyFactory创建,它本身不包括Action实例,默认实现DefaultActionProxy是由ActionInvocation持有Action实例。ActionProxy作用是如何取得Action,无论是本地还是远程。而ActionInvocation的作用是如何执行Action,拦截器的功能就是在ActionInvocation中实现的。
ConfigurationProvider&Configuration
ConfigurationProvider就是Struts2中配置文件的解析器,Struts2中的配置文件主要是尤其实现类XmlConfigurationProvider
Struts2请求流程
1、客户端发送请求
2、请求先通过ActionContextCleanUp-->FilterDispatcher
3、FilterDispatcher通过ActionMapper来决定这个Request需要调用哪个Action
4、如果ActionMapper决定调用某个Action,FilterDispatcher把请求的处理交给ActionProxy,这儿已经转到它的Delegate--Dispatcher来执行
5、ActionProxy根据ActionMapping和ConfigurationManager找到需要调用的Action类
6、ActionProxy创建一个ActionInvocation的实例
7、ActionInvocation调用真正的Action,当然这涉及到相关拦截器的调用
8、Action执行完毕,ActionInvocation创建Result并返回,当然,如果要在返回之前做些什么,可以实现PreResultListener。添加PreResultListener可以在Interceptor中实现,不知道其它还有什么方式?
Struts2(2.1.2)部分源码阅读
从org.apache.struts2.dispatcher.FilterDispatcher开始
//创建Dispatcher,此类是一个Delegate,它是真正完成根据url解析,读取对应Action的地方
init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
initLogging();
= createDispatcher(filterConfig);
dispatcher.init();
dispatcher.getContainer().inject(this);
//读取初始参数pakages,调用parse(),解析成类似/org/apache/struts2/static,/template的数组
param = filterConfig.getInitParameter("packages");
packages = "org.apache.struts2.static template
org.apache.struts2.interceptor.debugging";
!= null) {
packages;
this.pathPrefixes = parse(packages);
ActionContext.setContext(null);
init_DefaultProperties() {
configurationManager.addConfigurationProvider
DefaultPropertiesProvide
打开DefaultPropertiesProvide
register(ContainerBuilder builder, LocatableProperties props)
ConfigurationException {
defaultSettings = new
PropertiesSettings("org/apache/struts2/default");
ConfigurationException("Could not find or error in
org/apache/struts2/default.properties", e);
//PropertiesSettings
//读取org/apache/struts2/default.properties的配置信息,如果项目中需要覆盖,可以在classpath里的struts.properties里覆写
PropertiesSettings(String name) {
ClassLoaderUtils.getResource(name + ".properties",
getClass());
LOG.debug(name + ".properties missing");
new LocatableProperties();
return;
LocationImpl(null, settingsUrl.toString()));
settingsUrl.openStream();
settings.load(in);
StrutsException("Could not load " + name + ".properties:" + e,
e);
null) {
{
io);
再来看init_TraditionalXmlConfigurat
init_TraditionalXmlConfigurat
//如果没有配置就使用默认的"struts-default.xml,struts-plugin.xml,struts.xml",
initParams.get("config");
configPaths = DEFAULT_CONFIGURATION_PATHS;
configPaths.split("//s*[,]//s*");
(file.endsWith(".xml")) {
{
configurationManager.addConfigurationProvider
XmlConfigurationProvider
configurationManager.addConfigurationProvider
StrutsXmlConfigurationPr
{
IllegalArgumentException
对于其它配置文件只用StrutsXmlConfigurationPr
addPackage(Element packageElement) throws ConfigurationException
{
buildPackageContext(packageElement);
newPackage.build();
packageElement);
packageElement);
packageElement);
packageElement);
packageElement);
packageElement);
packageElement.getElementsByTagName_r("action");
i++) {
actionElement = (Element) actionList.item(i);
addAction(actionElement, newPackage);
packageElement);
cfg);
这儿发现一个配置上的小技巧,我的xwork2.0.*是没有的,但是看源码是看到xwork2.1.*是可以的。继续看XmlConfigurationProvider
loadConfigurationFiles(String fileName, Element includeElement)
{
{
doc.getDocumentElement();
rootElement.getChildNodes();
children.getLength();
childSize; i++) {
child = (Element) childNode;
String nodeName = child.getNodeName();
//解析每个action配置是,对于include文件可以使用通配符*来进行配置
//如Struts.xml中可配置成
(nodeName.equals("include")) {
child.getAttribute("file");
if(includeFileName.indexOf('*') != -1 ) {
ClassPathFinder();
wildcardFinder.setPattern(includeFileName);
wildcardFinder.findMatches();
docs.addAll(loadConfigurationFiles(match, child));
docs.addAll(loadConfigurationFiles(includeFileName, child));
loadedFileUrls.add(url.toString());
init_CustomConfigurationProvi
init_CustomConfigurationProvi
initParams.get("configProviders");
classes = configProvs.split("//s*[,]//s*");
(String cname : classes) {
this.getClass());
(ConfigurationProvider)cls.newInstance();
configurationManager.addConfigurationProvider
好了,现在再回到FilterDispatcher,每次发送一个Request,FilterDispatcher都会调用doFilter方法。
doFilter(ServletRequest req, ServletResponse res, FilterChain
chain) throws IOException, ServletException {
(HttpServletRequest) req;
(HttpServletResponse) res;
getServletContext();
";
stack =
dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
ActionContext ctx = new ActionContext(stack.getContext());
ActionContext.setContext(ctx);
UtilTimerStack.push(timerKey);
//根据content type来使用不同的Request封装,可以参见Dispatcher的wrapRequest
prepareDispatcherAndWrap
ActionMapping mapping;
{
//根据url取得对应的Action的配置信息--ActionMapping,actionMapper是通过Container的inject注入的
actionMapper.getMapping(request,
dispatcher.getConfigurationManager());
(Exception ex) {
ActionMapping", ex);
response, servletContext,
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
//如果找不到对应的action配置,则直接返回。比如你输入***.jsp等等
//这儿有个例外,就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中,当然.class文件除外。如果再没有则跳转到404
(mapping == null) {
request, should we look for a static resource?
RequestUtils.getServletPath(request);
&& null != request.getPathInfo()) {
resourcePath.startsWith("/struts")) {
resourcePath.substring("/struts".length());
response);
//正式开始Action的方法了
dispatcher.serviceAction(request, response, servletContext,
mapping);
{
ActionContextCleanUp.cleanUp(req);
{
UtilTimerStack.pop(timerKey);
Dispatcher类的serviceAction方法:
serviceAction(HttpServletRequest request, HttpServletResponse
response, ServletContext context,ActionMapping mapping) throws
ServletException {
response, mapping, context);
create a new copy and pass it in to be used by the new Action
request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
extraContext.put(ActionContext.VALUE_STACK,
valueStackFactory.createValueStack(stack));
Dispatcher";
UtilTimerStack.push(timerKey);
namespace = mapping.getNamespace();
name = mapping.getName();
method = mapping.getMethod();
Configuration config =
configurationManager.getConfiguration();
ActionProxy proxy =
config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
false);
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY,
proxy.getInvocation().getStack());
ActionMapping says to go straight to a result, do it!
(mapping.getResult() != null) {
mapping.getResult();
result.execute(proxy.getInvocation());
{
there was a previous value stack then set it back onto the
request
!= null) {
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY,
stack);
LOG.error("Could not find action or result", e);
sendError(request, response, context,
HttpServletResponse.SC_NOT_FOUND, e);
sendError(request, response, context,
HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
UtilTimerStack.pop(timerKey);
第一句createContextMap()方法,该方法主要把Application、Session、Request的key
value值拷贝到Map中,并放在HashMap中,可以参见createContextMap方法:
createContextMap(HttpServletRequest request, HttpServletResponse
response,
ActionMapping mapping, ServletContext context) {
objects
applied separately
HashMap(request.getParameterMap());
ServletContext
ApplicationMap(context);
params, session, application, request, response, context);
extraContext.put(ServletActionContext.ACTION_MAPPING,
mapping);
后面才是最主要的--ActionProxy,ActionInvocation。ActionProxy是Action的一个代理类,也就是说Action的调用是通过ActionProxy实现的,其实就是调用了ActionProxy.execute()方法,而该方法又调用了ActionInvocation.invoke()方法。归根到底,最后调用的是DefaultActionInvocation.invokeAction()方法。先看DefaultActionInvocation的init方法。
init(ActionProxy proxy) {
object factories, can use the ActionProxy and other
ActionContext.getContext();
actionContext.setActionInvocation(this);
stack.push(action);
contextMap.put("action", action);
ActionContext(contextMap);
invocationContext.setName(proxy.getActionName());
the iterator if someone changes the list
ArrayList(proxy.getConfig().getInterceptors());
createAction(Map contextMap) {
"+proxy.getActionName();
UtilTimerStack.push(timerKey);
//这儿默认建立Action是StrutsObjectFactory,实际中我使用的时候都是使用Spring创建的Action,这个时候使用的是SpringObjectFactory
objectFactory.buildAction(proxy.getActionName(),
proxy.getNamespace(), proxy.getConfig(), contextMap);
UtilTimerStack.pop(timerKey);
actionEventListener.prepare(action, stack);
接下来看看DefaultActionInvocation 的invoke方法。
throws Exception {
UtilTimerStack.push(profileKey);
(executed) {
IllegalStateException("Action has already executed");
(interceptors.hasNext()) {
interceptor = (InterceptorMapping) interceptors.next();
UtilTimerStack.profile("interceptor:
"+interceptor.getName(),
UtilTimerStack.ProfilingBlock() {
throws Exception {
interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
{
//interceptor执行完了之后执行action
invokeActionOnly();
needed because the result will be executed, then control will
return to the Interceptor, which will
above and flow through again
(!executed) {
//在Result返回之前调用preResultListeners
null) {
preResultListeners.iterator();
iterator.hasNext();) {
PreResultListener listener = (PreResultListener)
iterator.next();
_profileKey="preResultListener: ";
{
UtilTimerStack.push(_profileKey);
resultCode);
{
UtilTimerStack.pop(_profileKey);
we're supposed to
{
resultCode;
UtilTimerStack.pop(profileKey);
看程序中的if(interceptors.hasNext())语句,当然,interceptors里存储的是interceptorMapping列表(它包括一个Interceptor和一个name),所有的截拦器必须实现Interceptor的intercept方法,而该方法的参数恰恰又是ActionInvocation,在intercept方法中还是调用invocation.invoke(),从而实现了一个Interceptor链的调用。当所有的Interceptor执行完,最后调用invokeActionOnly方法来执行Action相应的方法。
invokeAction(Object action, ActionConfig actionConfig) throws
Exception {
"+proxy.getActionName();
UtilTimerStack.push(timerKey);
methodCalled = false;
methodResult = null;
method = null;
{
getAction().getClass().getMethod(methodName, new Class[0]);
(NoSuchMethodException e) {
//如果没有对应的方法,则使用do+Xxxx来再次获得方法
methodName.substring(0, 1).toUpperCase() +
methodName.substring(1);
getAction().getClass().getMethod(altMethodName, new
Class[0]);
(NoSuchMethodException e1) {
{
unknownHandler.handleUnknownActionMetho
(NoSuchMethodException e2) {
one
e;
(!methodCalled) {
method.invoke(action, new Object[0]);
//根据不同的Result类型返回不同值
//如输出流Result
(methodResult instanceof Result) {
(Result) methodResult;
{
methodResult;
IllegalArgumentException
in action " + getAction().getClass() + "");
to return the source exception.
t = e.getTargetException();
(actionEventListener != null) {
actionEventListener.handleException(t, getStack());
instanceof Exception) {
{
UtilTimerStack.pop(timerKey);
好了,action执行完了,还要根据ResultConfig返回到view,也就是在invoke方法中调用executeResult方法。
executeResult() throws Exception {
"+getResultCode();
UtilTimerStack.push(timerKey);
!= null) {
//可以参考Result的实现,如用了比较多的ServletDispatcherResult,ServletActionRedirectRes
(resultCode != null && !Action.NONE.equals(resultCode))
{
ConfigurationException("No result defined for action " +
getAction().getClass().getName()
result " + getResultCode(), proxy.getConfig());
{
{
"+getAction().getClass().getName()+" at
"+proxy.getConfig().getLocation());
UtilTimerStack.pop(timerKey);
createResult() throws Exception {
= explicitResult;
explicitResult = null;;
ret;
{
//根据result名称获得ResultConfig,resultCode就是result的name
results.get(resultCode);
(NullPointerException e) {
(resultConfig == null) {
//如果找不到对应name的ResultConfig,则使用name为*的Result
results.get("*");
{
//参照StrutsObjectFactory的代码
objectFactory.buildResult(resultConfig,
invocationContext.getContextMap());
(Exception e) {
exception while instantiating the result of type " +
resultConfig.getClassName(), e);
resultConfig);
!Action.NONE.equals(resultCode) && unknownHandler != null)
{
unknownHandler.handleUnknownResult(invocationContext,
proxy.getActionName(), proxy.getConfig(), resultCode);
//StrutsObjectFactory
buildResult(ResultConfig resultConfig, Map extraContext) throws
Exception {
resultConfig.getClassName();
null;
extraContext);
//这句很重要,后面将会谈到,reflectionProvider参见OgnlReflectionProvider;
//resultConfig.getParams()就是result配置文件里所配置的参数
reflectionProvider.setProperties(resultConfig.getParams(), result,
extraContext);
(Result) result;
ConfigurationException(result.getClass().getName() + " does not
implement Result.");
最后补充一下,Struts2的查找值和设置值都是使用Ognl来实现的。关于Ognl的介绍可以到其官方网站查看http://www.ognl.org/,我在网上也找到另外一篇http://www.javaeye.com/topic/254684和http://www.javaeye.com/topic/223612。完了来看下面这段小测试程序(其它的Ognl的测试可以自己添加)。
public class TestOgnl {
context;
throws Exception {
ognlGetValue() throws Exception {
Assert.assertEquals("myyate", Ognl.getValue("name", user));
Assert.assertEquals("cares", Ognl.getValue("dept.name",
user));
Assert.assertEquals("myyate", Ognl.getValue("name", context,
user));
Assert.assertEquals("contextmap", Ognl.getValue("#name", context,
user));
Assert.assertEquals("parker", Ognl.getValue("#pen", context,
user));
ognlSetValue() throws Exception {
user, "myyateC");
Assert.assertEquals("myyateC", Ognl.getValue("name", user));
Ognl.setValue("dept.name", user, "caresC");
Assert.assertEquals("caresC", Ognl.getValue("dept.name",
user));
Assert.assertEquals("contextmap", Ognl.getValue("#name", context,
user));
context, user, "contextmapC");
Assert.assertEquals("contextmapC", Ognl.getValue("#name", context,
user));
Assert.assertEquals("parker", Ognl.getValue("#pen", context,
user));
context, user, "parkerC");
Assert.assertEquals("parkerC", Ognl.getValue("#name", context,
user));
main(String[] args) throws Exception {
JUnitCore.runClasses(TestOgnl.class);
{
User("myyate", new Dept("cares"));
OgnlContext();
"parker");
"contextmap");
}
class User {
Dept dept) {
{
{
dept) {
setName(String name) {
}
class Dept {
{
name;
{
setName(String name) {
}
这样,一个Struts2的请求流程基本上就结束了。