- 浏览: 114772 次
- 性别:
- 来自: 武汉
文章分类
- 全部博客 (98)
- java (27)
- jms (2)
- jta (0)
- 性能调优及内存分析 (4)
- 设计模式 (14)
- 框架 (6)
- 其它 (9)
- job (1)
- maven (1)
- 服务器 (2)
- 分布式 (3)
- ibatis (1)
- linux (0)
- mysql (0)
- 并发编程 (0)
- java多线程 (2)
- 前端跨域 (1)
- 线程dump分析 (0)
- velocity (0)
- 数据库 (2)
- 协议 (0)
- 监控 (0)
- 开源软件 (2)
- 算法 (0)
- 网络 (1)
- spring (1)
- 编码 (0)
- 数据结构 (0)
- HTable和HTablePool使用注意事项 (0)
- opencms (0)
- android (16)
- 操作系统 (2)
- top (0)
最新评论
-
hold_on:
@Override public boolea ...
android listview的HeadView左右切换图片(仿新浪,网易,百度等切换图片) -
achersnake:
123
Servlet中listener(监听器)和filter的总结 -
angel243fly:
我用了这个方法,还是报同样的错误,还有什么建议吗?
eclipse提示CreateProcess error=87错误的解决方法
Struts2架构图
请求首先通过Filter 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及其子类StrutsXmlConfigurationProvider来解析,
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的地方
public void init(FilterConfig filterConfig) throws ServletException {
try {
this.filterConfig = filterConfig;
initLogging();
dispatcher = createDispatcher(filterConfig);
dispatcher.init();
dispatcher.getContainer().inject(this);
//读取初始参数pakages,调用parse(),解析成类似/org/apache/struts2/static,/template的数组
String param = filterConfig.getInitParameter("packages");
String packages = "org.apache.struts2.static template org.apache.struts2.interceptor.debugging";
if (param != null) {
packages = param + " " + packages;
}
this.pathPrefixes = parse(packages);
} finally {
ActionContext.setContext(null);
}
}
public void init(FilterConfig filterConfig) throws ServletException {
try {
this.filterConfig = filterConfig;
initLogging();
dispatcher = createDispatcher(filterConfig);
dispatcher.init();
dispatcher.getContainer().inject(this);
//读取初始参数pakages,调用parse(),解析成类似/org/apache/struts2/static,/template的数组
String param = filterConfig.getInitParameter("packages");
String packages = "org.apache.struts2.static template org.apache.struts2.interceptor.debugging";
if (param != null) {
packages = param + " " + packages;
}
this.pathPrefixes = parse(packages);
} finally {
ActionContext.setContext(null);
}
}
顺着流程我们看Disptcher的init方法。init方法里就是初始读取一些配置文件等,先看init_DefaultProperties,主要是读取properties配置文件。
private void init_DefaultProperties() {
configurationManager.addConfigurationProvider(new DefaultPropertiesProvider());
}
configurationManager.addConfigurationProvider(new DefaultPropertiesProvider());
}
打开DefaultPropertiesProvider
public void register(ContainerBuilder builder, LocatableProperties props)
throws ConfigurationException {
Settings defaultSettings = null;
try {
defaultSettings = new PropertiesSettings("org/apache/struts2/default");
} catch (Exception e) {
throw new ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e);
}
loadSettings(props, defaultSettings);
}
//PropertiesSettings
//读取org/apache/struts2/default.properties的配置信息,如果项目中需要覆盖,可以在classpath里的struts.properties里覆写
public PropertiesSettings(String name) {
URL settingsUrl = ClassLoaderUtils.getResource(name + ".properties", getClass());
if (settingsUrl == null) {
LOG.debug(name + ".properties missing");
settings = new LocatableProperties();
return;
}
settings = new LocatableProperties(new LocationImpl(null, settingsUrl.toString()));
// Load settings
InputStream in = null;
try {
in = settingsUrl.openStream();
settings.load(in);
} catch (IOException e) {
throw new StrutsException("Could not load " + name + ".properties:" + e, e);
} finally {
if(in != null) {
try {
in.close();
} catch(IOException io) {
LOG.warn("Unable to close input stream", io);
}
}
}
}
throws ConfigurationException {
Settings defaultSettings = null;
try {
defaultSettings = new PropertiesSettings("org/apache/struts2/default");
} catch (Exception e) {
throw new ConfigurationException("Could not find or error in org/apache/struts2/default.properties", e);
}
loadSettings(props, defaultSettings);
}
//PropertiesSettings
//读取org/apache/struts2/default.properties的配置信息,如果项目中需要覆盖,可以在classpath里的struts.properties里覆写
public PropertiesSettings(String name) {
URL settingsUrl = ClassLoaderUtils.getResource(name + ".properties", getClass());
if (settingsUrl == null) {
LOG.debug(name + ".properties missing");
settings = new LocatableProperties();
return;
}
settings = new LocatableProperties(new LocationImpl(null, settingsUrl.toString()));
// Load settings
InputStream in = null;
try {
in = settingsUrl.openStream();
settings.load(in);
} catch (IOException e) {
throw new StrutsException("Could not load " + name + ".properties:" + e, e);
} finally {
if(in != null) {
try {
in.close();
} catch(IOException io) {
LOG.warn("Unable to close input stream", io);
}
}
}
}
再来看init_TraditionalXmlConfigurations方法,这个是读取struts-default.xml和Struts.xml的方法。
private void init_TraditionalXmlConfigurations() {
//首先读取web.xml中的config初始参数值
//如果没有配置就使用默认的"struts-default.xml,struts-plugin.xml,struts.xml",
//这儿就可以看出为什么默认的配置文件必须取名为这三个名称了
//如果不想使用默认的名称,直接在web.xml中配置config初始参数即可
String configPaths = initParams.get("config");
if (configPaths == null) {
configPaths = DEFAULT_CONFIGURATION_PATHS;
}
String[] files = configPaths.split("\\s*[,]\\s*");
//依次解析配置文件,xwork.xml单独解析
for (String file : files) {
if (file.endsWith(".xml")) {
if ("xwork.xml".equals(file)) {
configurationManager.addConfigurationProvider(new XmlConfigurationProvider(file, false));
} else {
configurationManager.addConfigurationProvider(new StrutsXmlConfigurationProvider(file, false, servletContext));
}
} else {
throw new IllegalArgumentException("Invalid configuration file name");
}
}
}
//首先读取web.xml中的config初始参数值
//如果没有配置就使用默认的"struts-default.xml,struts-plugin.xml,struts.xml",
//这儿就可以看出为什么默认的配置文件必须取名为这三个名称了
//如果不想使用默认的名称,直接在web.xml中配置config初始参数即可
String configPaths = initParams.get("config");
if (configPaths == null) {
configPaths = DEFAULT_CONFIGURATION_PATHS;
}
String[] files = configPaths.split("\\s*[,]\\s*");
//依次解析配置文件,xwork.xml单独解析
for (String file : files) {
if (file.endsWith(".xml")) {
if ("xwork.xml".equals(file)) {
configurationManager.addConfigurationProvider(new XmlConfigurationProvider(file, false));
} else {
configurationManager.addConfigurationProvider(new StrutsXmlConfigurationProvider(file, false, servletContext));
}
} else {
throw new IllegalArgumentException("Invalid configuration file name");
}
}
}
对于其它配置文件只用StrutsXmlConfigurationProvider,此类继承XmlConfigurationProvider,而XmlConfigurationProvider又实现ConfigurationProvider接口。类XmlConfigurationProvider负责配置文件的读取和解析,addAction()方法负责读取<action>标签,并将数据保存在ActionConfig中;addResultTypes()方法负责将<result-type>标签转化为ResultTypeConfig对象;loadInterceptors()方法负责将<interceptor>标签转化为InterceptorConfi对象;loadInterceptorStack()方法负责将<interceptor-ref>标签转化为InterceptorStackConfig对象;loadInterceptorStacks()方法负责将<interceptor-stack>标签转化成InterceptorStackConfig对象。而上面的方法最终会被addPackage()方法调用,将所读取到的数据汇集到PackageConfig对象中。来看XmlConfigurationProvider的源代码,详细的我自己也就大体浏览了一下,各位可以自己研读。
protected PackageConfig addPackage(Element packageElement) throws ConfigurationException {
PackageConfig.Builder newPackage = buildPackageContext(packageElement);
if (newPackage.isNeedsRefresh()) {
return newPackage.build();
}
.
addResultTypes(newPackage, packageElement);
loadInterceptors(newPackage, packageElement);
loadDefaultInterceptorRef(newPackage, packageElement);
loadDefaultClassRef(newPackage, packageElement);
loadGlobalResults(newPackage, packageElement);
loadGobalExceptionMappings(newPackage, packageElement);
NodeList actionList = packageElement.getElementsByTagName("action");
for (int i = 0; i < actionList.getLength(); i++) {
Element actionElement = (Element) actionList.item(i);
addAction(actionElement, newPackage);
}
loadDefaultActionRef(newPackage, packageElement);
PackageConfig cfg = newPackage.build();
configuration.addPackageConfig(cfg.getName(), cfg);
return cfg;
}
PackageConfig.Builder newPackage = buildPackageContext(packageElement);
if (newPackage.isNeedsRefresh()) {
return newPackage.build();
}
.
addResultTypes(newPackage, packageElement);
loadInterceptors(newPackage, packageElement);
loadDefaultInterceptorRef(newPackage, packageElement);
loadDefaultClassRef(newPackage, packageElement);
loadGlobalResults(newPackage, packageElement);
loadGobalExceptionMappings(newPackage, packageElement);
NodeList actionList = packageElement.getElementsByTagName("action");
for (int i = 0; i < actionList.getLength(); i++) {
Element actionElement = (Element) actionList.item(i);
addAction(actionElement, newPackage);
}
loadDefaultActionRef(newPackage, packageElement);
PackageConfig cfg = newPackage.build();
configuration.addPackageConfig(cfg.getName(), cfg);
return cfg;
}
这儿发现一个配置上的小技巧,我的xwork2.0.*是没有的,但是看源码是看到xwork2.1.*是可以的。继续看XmlConfigurationProvider的源代码:
private List loadConfigurationFiles(String fileName, Element includeElement) {
List<Document> docs = new ArrayList<Document>();
if (!includedFileNames.contains(fileName)) {
Element rootElement = doc.getDocumentElement();
NodeList children = rootElement.getChildNodes();
int childSize = children.getLength();
for (int i = 0; i < childSize; i++) {
Node childNode = children.item(i);
if (childNode instanceof Element) {
Element child = (Element) childNode;
final String nodeName = child.getNodeName();
//解析每个action配置是,对于include文件可以使用通配符*来进行配置
//如Struts.xml中可配置成<include file="actions_*.xml"/>
if (nodeName.equals("include")) {
String includeFileName = child.getAttribute("file");
if(includeFileName.indexOf('*') != -1 ) {
ClassPathFinder wildcardFinder = new ClassPathFinder();
wildcardFinder.setPattern(includeFileName);
Vector<String> wildcardMatches = wildcardFinder.findMatches();
for (String match : wildcardMatches) {
docs.addAll(loadConfigurationFiles(match, child));
}
}
else {
docs.addAll(loadConfigurationFiles(includeFileName, child));
}
}
}
}
docs.add(doc);
loadedFileUrls.add(url.toString());
}
}
return docs;
}
List<Document> docs = new ArrayList<Document>();
if (!includedFileNames.contains(fileName)) {
Element rootElement = doc.getDocumentElement();
NodeList children = rootElement.getChildNodes();
int childSize = children.getLength();
for (int i = 0; i < childSize; i++) {
Node childNode = children.item(i);
if (childNode instanceof Element) {
Element child = (Element) childNode;
final String nodeName = child.getNodeName();
//解析每个action配置是,对于include文件可以使用通配符*来进行配置
//如Struts.xml中可配置成<include file="actions_*.xml"/>
if (nodeName.equals("include")) {
String includeFileName = child.getAttribute("file");
if(includeFileName.indexOf('*') != -1 ) {
ClassPathFinder wildcardFinder = new ClassPathFinder();
wildcardFinder.setPattern(includeFileName);
Vector<String> wildcardMatches = wildcardFinder.findMatches();
for (String match : wildcardMatches) {
docs.addAll(loadConfigurationFiles(match, child));
}
}
else {
docs.addAll(loadConfigurationFiles(includeFileName, child));
}
}
}
}
docs.add(doc);
loadedFileUrls.add(url.toString());
}
}
return docs;
}
init_CustomConfigurationProviders方式初始自定义的Provider,配置类全名和实现ConfigurationProvider接口,用逗号隔开即可。
private void init_CustomConfigurationProviders() {
String configProvs = initParams.get("configProviders");
if (configProvs != null) {
String[] classes = configProvs.split("\\s*[,]\\s*");
for (String cname : classes) {
try {
Class cls = ClassLoaderUtils.loadClass(cname, this.getClass());
ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();
configurationManager.addConfigurationProvider(prov);
}
}
}
}
String configProvs = initParams.get("configProviders");
if (configProvs != null) {
String[] classes = configProvs.split("\\s*[,]\\s*");
for (String cname : classes) {
try {
Class cls = ClassLoaderUtils.loadClass(cname, this.getClass());
ConfigurationProvider prov = (ConfigurationProvider)cls.newInstance();
configurationManager.addConfigurationProvider(prov);
}
}
}
}
好了,现在再回到FilterDispatcher,每次发送一个Request,FilterDispatcher都会调用doFilter方法。
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
ServletContext servletContext = getServletContext();
String timerKey = "FilterDispatcher_doFilter: ";
try {
ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
ActionContext ctx = new ActionContext(stack.getContext());
ActionContext.setContext(ctx);
UtilTimerStack.push(timerKey);
//根据content type来使用不同的Request封装,可以参见Dispatcher的wrapRequest
request = prepareDispatcherAndWrapRequest(request, response);
ActionMapping mapping;
try {
//根据url取得对应的Action的配置信息--ActionMapping,actionMapper是通过Container的inject注入的
mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());
} catch (Exception ex) {
log.error("error getting ActionMapping", ex);
dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
return;
}
//如果找不到对应的action配置,则直接返回。比如你输入***.jsp等等
//这儿有个例外,就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中,当然.class文件除外。如果再没有则跳转到404
if (mapping == null) {
// 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();
}
if (serveStatic && resourcePath.startsWith("/struts")) {
String name = resourcePath.substring("/struts".length());
findStaticResource(name, request, response);
} else {
chain.doFilter(request, response);
}
return;
}
//正式开始Action的方法了
dispatcher.serviceAction(request, response, servletContext, mapping);
} finally {
try {
ActionContextCleanUp.cleanUp(req);
} finally {
UtilTimerStack.pop(timerKey);
}
}
}
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) res;
ServletContext servletContext = getServletContext();
String timerKey = "FilterDispatcher_doFilter: ";
try {
ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
ActionContext ctx = new ActionContext(stack.getContext());
ActionContext.setContext(ctx);
UtilTimerStack.push(timerKey);
//根据content type来使用不同的Request封装,可以参见Dispatcher的wrapRequest
request = prepareDispatcherAndWrapRequest(request, response);
ActionMapping mapping;
try {
//根据url取得对应的Action的配置信息--ActionMapping,actionMapper是通过Container的inject注入的
mapping = actionMapper.getMapping(request, dispatcher.getConfigurationManager());
} catch (Exception ex) {
log.error("error getting ActionMapping", ex);
dispatcher.sendError(request, response, servletContext, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, ex);
return;
}
//如果找不到对应的action配置,则直接返回。比如你输入***.jsp等等
//这儿有个例外,就是如果path是以“/struts”开头,则到初始参数packages配置的包路径去查找对应的静态资源并输出到页面流中,当然.class文件除外。如果再没有则跳转到404
if (mapping == null) {
// 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();
}
if (serveStatic && resourcePath.startsWith("/struts")) {
String name = resourcePath.substring("/struts".length());
findStaticResource(name, request, response);
} else {
chain.doFilter(request, response);
}
return;
}
//正式开始Action的方法了
dispatcher.serviceAction(request, response, servletContext, mapping);
} finally {
try {
ActionContextCleanUp.cleanUp(req);
} finally {
UtilTimerStack.pop(timerKey);
}
}
}
Dispatcher类的serviceAction方法:
public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,ActionMapping mapping) throws ServletException {
Map<String, Object> extraContext = createContextMap(request, response, mapping, context);
// If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
if (stack != null) {
extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
}
String timerKey = "Handling request from Dispatcher";
try {
UtilTimerStack.push(timerKey);
String namespace = mapping.getNamespace();
String name = mapping.getName();
String method = mapping.getMethod();
Configuration config = configurationManager.getConfiguration();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, extraContext, true, false);
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());
// if the ActionMapping says to go straight to a result, do it!
if (mapping.getResult() != null) {
Result result = mapping.getResult();
result.execute(proxy.getInvocation());
} else {
proxy.execute();
}
// If there was a previous value stack then set it back onto the request
if (stack != null) {
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
}
} catch (ConfigurationException e) {
LOG.error("Could not find action or result", e);
sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (Exception e) {
sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} finally {
UtilTimerStack.pop(timerKey);
}
}
Map<String, Object> extraContext = createContextMap(request, response, mapping, context);
// If there was a previous value stack, then create a new copy and pass it in to be used by the new Action
ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
if (stack != null) {
extraContext.put(ActionContext.VALUE_STACK, valueStackFactory.createValueStack(stack));
}
String timerKey = "Handling request from Dispatcher";
try {
UtilTimerStack.push(timerKey);
String namespace = mapping.getNamespace();
String name = mapping.getName();
String method = mapping.getMethod();
Configuration config = configurationManager.getConfiguration();
ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(
namespace, name, method, extraContext, true, false);
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());
// if the ActionMapping says to go straight to a result, do it!
if (mapping.getResult() != null) {
Result result = mapping.getResult();
result.execute(proxy.getInvocation());
} else {
proxy.execute();
}
// If there was a previous value stack then set it back onto the request
if (stack != null) {
request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
}
} catch (ConfigurationException e) {
LOG.error("Could not find action or result", e);
sendError(request, response, context, HttpServletResponse.SC_NOT_FOUND, e);
} catch (Exception e) {
sendError(request, response, context, HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e);
} finally {
UtilTimerStack.pop(timerKey);
}
}
第一句createContextMap()方法,该方法主要把Application、Session、Request的key value值拷贝到Map中,并放在HashMap<String,Object>中,可以参见createContextMap方法:
public Map<String,Object> createContextMap(HttpServletRequest request, HttpServletResponse response,
ActionMapping mapping, ServletContext context) {
// request map wrapping the http request objects
Map requestMap = new RequestMap(request);
// parameters map wrapping the http parameters. ActionMapping parameters are now handled and applied separately
Map params = new HashMap(request.getParameterMap());
// session map wrapping the http session
Map session = new SessionMap(request);
// application map wrapping the ServletContext
Map application = new ApplicationMap(context);
Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);
extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);
return extraContext;
}
ActionMapping mapping, ServletContext context) {
// request map wrapping the http request objects
Map requestMap = new RequestMap(request);
// parameters map wrapping the http parameters. ActionMapping parameters are now handled and applied separately
Map params = new HashMap(request.getParameterMap());
// session map wrapping the http session
Map session = new SessionMap(request);
// application map wrapping the ServletContext
Map application = new ApplicationMap(context);
Map<String,Object> extraContext = createContextMap(requestMap, params, session, application, request, response, context);
extraContext.put(ServletActionContext.ACTION_MAPPING, mapping);
return extraContext;
}
后面才是最主要的--ActionProxy,ActionInvocation。ActionProxy是Action的一个代理类,也就是说Action的调用是通过ActionProxy实现的,其实就是调用了ActionProxy.execute()方法,而该方法又调用了ActionInvocation.invoke()方法。归根到底,最后调用的是DefaultActionInvocation.invokeAction()方法。先看DefaultActionInvocation的init方法。
public void init(ActionProxy proxy) {
this.proxy = proxy;
Map contextMap = createContextMap();
// Setting this so that other classes, like object factories, can use the ActionProxy and other
// contextual information to operate
ActionContext actionContext = ActionContext.getContext();
if(actionContext != null) {
actionContext.setActionInvocation(this);
}
//创建Action,可Struts2里是每次请求都新建一个Action
createAction(contextMap);
if (pushAction) {
stack.push(action);
contextMap.put("action", action);
}
invocationContext = new ActionContext(contextMap);
invocationContext.setName(proxy.getActionName());
// get a new List so we don't get problems with the iterator if someone changes the list
List interceptorList = new ArrayList(proxy.getConfig().getInterceptors());
interceptors = interceptorList.iterator();
}
protected void createAction(Map contextMap) {
// load action
String timerKey = "actionCreate: "+proxy.getActionName();
try {
UtilTimerStack.push(timerKey);
//这儿默认建立Action是StrutsObjectFactory,实际中我使用的时候都是使用Spring创建的Action,这个时候使用的是SpringObjectFactory
action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
}
..
} finally {
UtilTimerStack.pop(timerKey);
}
if (actionEventListener != null) {
action = actionEventListener.prepare(action, stack);
}
}
this.proxy = proxy;
Map contextMap = createContextMap();
// Setting this so that other classes, like object factories, can use the ActionProxy and other
// contextual information to operate
ActionContext actionContext = ActionContext.getContext();
if(actionContext != null) {
actionContext.setActionInvocation(this);
}
//创建Action,可Struts2里是每次请求都新建一个Action
createAction(contextMap);
if (pushAction) {
stack.push(action);
contextMap.put("action", action);
}
invocationContext = new ActionContext(contextMap);
invocationContext.setName(proxy.getActionName());
// get a new List so we don't get problems with the iterator if someone changes the list
List interceptorList = new ArrayList(proxy.getConfig().getInterceptors());
interceptors = interceptorList.iterator();
}
protected void createAction(Map contextMap) {
// load action
String timerKey = "actionCreate: "+proxy.getActionName();
try {
UtilTimerStack.push(timerKey);
//这儿默认建立Action是StrutsObjectFactory,实际中我使用的时候都是使用Spring创建的Action,这个时候使用的是SpringObjectFactory
action = objectFactory.buildAction(proxy.getActionName(), proxy.getNamespace(), proxy.getConfig(), contextMap);
}
..
} finally {
UtilTimerStack.pop(timerKey);
}
if (actionEventListener != null) {
action = actionEventListener.prepare(action, stack);
}
}
接下来看看DefaultActionInvocation 的invoke方法。
public String invoke() throws Exception {
String profileKey = "invoke: ";
try {
UtilTimerStack.push(profileKey);
if (executed) {
throw new IllegalStateException("Action has already executed");
}
//先执行interceptors
if (interceptors.hasNext()) {
final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
UtilTimerStack.profile("interceptor: "+interceptor.getName(),
new UtilTimerStack.ProfilingBlock<String>() {
public String doProfiling() throws Exception {
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
return null;
}
});
} else {
//interceptor执行完了之后执行action
resultCode = invokeActionOnly();
}
String profileKey = "invoke: ";
try {
UtilTimerStack.push(profileKey);
if (executed) {
throw new IllegalStateException("Action has already executed");
}
//先执行interceptors
if (interceptors.hasNext()) {
final InterceptorMapping interceptor = (InterceptorMapping) interceptors.next();
UtilTimerStack.profile("interceptor: "+interceptor.getName(),
new UtilTimerStack.ProfilingBlock<String>() {
public String doProfiling() throws Exception {
resultCode = interceptor.getInterceptor().intercept(DefaultActionInvocation.this);
return null;
}
});
} else {
//interceptor执行完了之后执行action
resultCode = invokeActionOnly();
}
发表评论
-
用Berkeley DB实现的BdbFrontier
2012-04-12 17:38 0简单的说,Berkeley DB就 ... -
不简单的URL去重
2012-04-12 16:21 0转:http://blog.csdn.net/hist ... -
如何读开源框架源码
2011-04-17 13:25 1537转:http://benbear2008.iteye.com/ ... -
Log4j使用总结
2011-04-15 16:58 772转:http://kdboy.iteye.com/blog/2 ... -
Commons-logging + Log4j 入门指南(part2)
2011-04-15 16:56 952为什么说“CONSOLE”表示将日志信息输出到“控制台”呢?那 ... -
Commons-logging + Log4j 入门指南(part1)
2011-04-15 16:52 676转:http://touch.iteye.com/blog/3 ... -
struts2源码分析1(part2)
2011-04-13 10:33 688转: http://blog.csdn.net/accpsz/ ...
相关推荐
6. **源码分析**: 要深入理解Struts2的文件上传机制,你需要查看Struts2的源码,特别是`org.apache.struts2.dispatcher.multipart.JakartaMultiPartRequest`和`org.apache.struts2.components.Form`这两个类。...
这个"struts-2.3.8-all-part1"压缩包包含了Struts 2框架的完整版本,版本号为2.3.8。由于文件较大,所以被分为两个部分上传,这部分是第一部分,包括了`apps`, `docs`, `src`, `lib`等关键目录。接下来,我们将深入...
4. **源码分析** - `struts2_01_014_FileUp`可能是一个具体的Action类,负责处理上传和下载操作。它可能包含了处理文件路径、文件名、文件内容的逻辑。 - 源码中可能涉及到的其他组件包括:表单验证、异常处理、...
9. **源码分析** 对于深入理解Struts2文件上传的工作原理,阅读源码是非常有帮助的。了解`FileUploadInterceptor`如何工作,以及`MultipartRequest`类如何解析Multipart请求,可以加深对整个过程的理解。 10. **...
压缩包中的三个文件`JasperReportTest.part2.rar`、`JasperReportTest.part1.rar`和`JasperReportTest.part3.rar`很可能是分片的文件,你需要使用合适的工具(如WinRAR或7-Zip)将它们合并成一个完整的JasperReport...
【JSP源码工程文件(part1)】是一个包含了使用Struts和Hibernate框架开发的Java Web项目的源代码。这个项目提供了对JSP技术的深入理解,同时也展现了如何将MVC设计模式通过Struts框架实现,以及如何利用Hibernate...
**(1)配置Struts2拦截器** 在struts.xml配置文件中,为使用SWFupload的Action添加特定的拦截器链,以避免Struts2默认的文件上传处理。可以创建一个新的Interceptor,例如`swfUploadInterceptor`,然后在Action配置...
1. **MVC设计模式**:了解Struts如何实现请求分发,Spring如何处理业务逻辑和视图渲染。 2. **Spring框架**:研究Spring的IoC容器是如何管理对象的生命周期和依赖关系,以及AOP在事务管理和日志记录中的应用。 3. ...
全书分4篇,共24章,其中,第1篇为技能学习篇,主要包括Java Web开发环境、JSP语法、JSP内置对象、Java Bean技术、Servlet技术、EL与JSTL标签库、数据库应用开发、初识Struts2基础、揭密Struts2高级技术、Hib锄劬e...
1. **MVC框架**:这部分源码可能使用了Spring MVC或Struts2等MVC架构,用于实现业务逻辑和视图的分离,提高代码可维护性。 2. **用户认证与授权**:通过例如Spring Security或Apache Shiro,实现用户登录、权限控制...
3. **Struts2**:Struts2是一个基于MVC(Model-View-Controller)设计模式的开源Java Web框架。它提供了一种组织应用程序结构的方式,使开发者可以更专注于业务逻辑的实现。Struts2的核心组件包括Action、...
通过分析代码、运行示例和调试问题,你可以深入了解J2EE架构的工作原理,同时提高自己的编程能力。此外,与课堂笔记结合学习,将更全面地理解项目背后的理论知识。在实践中遇到问题时,可以参考李兴华在CSDN上的分享...
你可以通过分析Action类、Interceptor、配置文件(struts.xml)等内容,深入理解Struts2如何与Servlet协同工作,完成文件的上传下载操作。此外,还可能涉及到异常处理、文件路径管理、安全性(防止恶意文件上传)等...
1:外文原文 Struts——an open-source MVC implementation This article introduces Struts, a Model-View-Controller implementation that uses servlets and JavaServer Pages (JSP) technology. Struts can help...
通过阅读《精通Spring(清晰书签版)》.part1.rar和.part2.rar这两个压缩包文件,你将能系统地学习和掌握Spring框架的各个方面,提升自己的Java EE开发能力。这本书的内容详实,实例丰富,是Spring学习者不可多得的...
9. **源码分析**:SWFUpload本身是开源的,熟悉其源码可以帮助开发者更好地理解和定制功能。 10. **工具集成**:SWFUpload可以与各种Java Web框架(如Spring MVC、Struts2)集成,理解这些框架如何处理文件上传会更...
8. **源码分析**:作为一个开源工具,jspsmart的源码可供开发者学习和定制,你可以深入理解其内部实现,根据项目需求进行扩展或优化。 9. **整合框架**:在实际开发中,jspsmart常与Spring MVC、Struts2等Web框架...
源码分析 `Commons FileUpload`的源码对于深入理解其工作原理和优化文件上传处理很有帮助。通过阅读源码,我们可以学习如何解析MIME数据流,如何管理内存与磁盘之间的切换,以及如何处理各种异常情况。 ### 7. ...