Struts 2 基础篇【转】
转载至 : http://www.blogjava.net/huamengxing/archive/2009/10/21/299153.html
Struts2架构图
有视频讲解百度一下就可以找到了 我是在 私塾在线 看到的 (因为这里放链接处error所以就没上连接了)
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);
}
}
configurationManager.addConfigurationProvider(new DefaultPropertiesProvider());
}
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);
}
}
}
}
//首先读取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");
}
}
}
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;
}
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;
}
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);
}

}
}
}
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);
}
}
}
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);
}
}
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;
}
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);
}
}
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();
}
// this is needed because the result will be executed, then control will return to the Interceptor, which will
// return above and flow through again
if (!executed) {
//在Result返回之前调用preResultListeners
if (preResultListeners != null) {
for (Iterator iterator = preResultListeners.iterator();
iterator.hasNext();) {
PreResultListener listener = (PreResultListener) iterator.next();
String _profileKey="preResultListener: ";
try {
UtilTimerStack.push(_profileKey);
listener.beforeResult(this, resultCode);
}
finally {
UtilTimerStack.pop(_profileKey);
}
}
}
// now execute the result, if we're supposed to
if (proxy.getExecuteResult()) {
executeResult();
}
executed = true;
}
return resultCode;
}
finally {
UtilTimerStack.pop(profileKey);
}
}
String methodName = proxy.getMethod();
String timerKey = "invokeAction: "+proxy.getActionName();
try {
UtilTimerStack.push(timerKey);
boolean methodCalled = false;
Object methodResult = null;
Method method = null;
try {
//获得需要执行的方法
method = getAction().getClass().getMethod(methodName, new Class[0]);
} catch (NoSuchMethodException e) {
//如果没有对应的方法,则使用do+Xxxx来再次获得方法
try {
String altMethodName = "do" + methodName.substring(0, 1).toUpperCase() + methodName.substring(1);
method = getAction().getClass().getMethod(altMethodName, new Class[0]);
} catch (NoSuchMethodException e1) {
// well, give the unknown handler a shot
if (unknownHandler != null) {
try {
methodResult = unknownHandler.handleUnknownActionMethod(action, methodName);
methodCalled = true;
} catch (NoSuchMethodException e2) {
// throw the original one
throw e;
}
} else {
throw e;
}
}
}
if (!methodCalled) {
methodResult = method.invoke(action, new Object[0]);
}
//根据不同的Result类型返回不同值
//如输出流Result
if (methodResult instanceof Result) {
this.explicitResult = (Result) methodResult;
return null;
} else {
return (String) methodResult;
}
} catch (NoSuchMethodException e) {
throw new IllegalArgumentException("The " + methodName + "() is not defined in action " + getAction().getClass() + "");
} catch (InvocationTargetException e) {
// We try to return the source exception.
Throwable t = e.getTargetException();
if (actionEventListener != null) {
String result = actionEventListener.handleException(t, getStack());
if (result != null) {
return result;
}
}
if (t instanceof Exception) {
throw(Exception) t;
} else {
throw e;
}
} finally {
UtilTimerStack.pop(timerKey);
}
}
//根据ResultConfig创建Result
result = createResult();
String timerKey = "executeResult: "+getResultCode();
try {
UtilTimerStack.push(timerKey);
if (result != null) {
//这儿正式执行:)
//可以参考Result的实现,如用了比较多的ServletDispatcherResult,ServletActionRedirectResult,ServletRedirectResult
result.execute(this);
} else if (resultCode != null && !Action.NONE.equals(resultCode)) {
throw new ConfigurationException("No result defined for action " + getAction().getClass().getName()
+ " and result " + getResultCode(), proxy.getConfig());
} else {
if (LOG.isDebugEnabled()) {
LOG.debug("No result returned for action "+getAction().getClass().getName()+" at "+proxy.getConfig().getLocation());
}
}
} finally {
UtilTimerStack.pop(timerKey);
}
}
public Result createResult() throws Exception {
if (explicitResult != null) {
Result ret = explicitResult;
explicitResult = null;;
return ret;
}
ActionConfig config = proxy.getConfig();
Map results = config.getResults();
ResultConfig resultConfig = null;
synchronized (config) {
try {
//根据result名称获得ResultConfig,resultCode就是result的name
resultConfig = (ResultConfig) results.get(resultCode);
} catch (NullPointerException e) {
}
if (resultConfig == null) {
//如果找不到对应name的ResultConfig,则使用name为*的Result
resultConfig = (ResultConfig) results.get("*");
}
}
if (resultConfig != null) {
try {
//参照StrutsObjectFactory的代码
Result result = objectFactory.buildResult(resultConfig, invocationContext.getContextMap());
return result;
} catch (Exception e) {
LOG.error("There was an exception while instantiating the result of type " + resultConfig.getClassName(), e);
throw new XWorkException(e, resultConfig);
}
} else if (resultCode != null && !Action.NONE.equals(resultCode) && unknownHandler != null) {
return unknownHandler.handleUnknownResult(invocationContext, proxy.getActionName(), proxy.getConfig(), resultCode);
}
return null;
}
//StrutsObjectFactory
public Result buildResult(ResultConfig resultConfig, Map extraContext) throws Exception {
String resultClassName = resultConfig.getClassName();
if (resultClassName == null)
return null;
//创建Result,因为Result是有状态的,所以每次请求都新建一个
Object result = buildBean(resultClassName, extraContext);
//这句很重要,后面将会谈到,reflectionProvider参见OgnlReflectionProvider;
//resultConfig.getParams()就是result配置文件里所配置的参数<param>
</param>//setProperties方法最终调用的是Ognl类的setValue方法
//这句其实就是把param名值设置到根对象result上
reflectionProvider.setProperties(resultConfig.getParams(), result, extraContext);
if (result instanceof Result)
return (Result) result;
throw new ConfigurationException(result.getClass().getName() + " does not implement Result.");
}
private User user;
private Map context;
@Before
public void setUp() throws Exception {
}
@Test
public void ognlGetValue() throws Exception {
reset();
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));
}
@Test
public void ognlSetValue() throws Exception {
reset();
Ognl.setValue("name", 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));
Ognl.setValue("#name", context, user, "contextmapC");
Assert.assertEquals("contextmapC", Ognl.getValue("#name", context, user));
Assert.assertEquals("parker", Ognl.getValue("#pen", context, user));
Ognl.setValue("#name", context, user, "parkerC");
Assert.assertEquals("parkerC", Ognl.getValue("#name", context, user));
}
public static void main(String[] args) throws Exception {
JUnitCore.runClasses(TestOgnl.class);
}
private void reset() {
user = new User("myyate", new Dept("cares"));
context = new OgnlContext();
context.put("pen", "parker");
context.put("name", "contextmap");
}
}
class User {
public User(String name, Dept dept) {
this.name = name;
this.dept = dept;
}
String name;
private Dept dept;
public Dept getDept() {
return dept;
}
public String getName() {
return name;
}
public void setDept(Dept dept) {
this.dept = dept;
}
public void setName(String name) {
this.name = name;
}
}
class Dept {
public Dept(String name) {
this.name = name;
}
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
Struts 2 基础篇【转】的更多相关文章
- C#多线程之基础篇3
在上一篇C#多线程之基础篇2中,我们主要讲述了确定线程的状态.线程优先级.前台线程和后台线程以及向线程传递参数的知识,在这一篇中我们将讲述如何使用C#的lock关键字锁定线程.使用Monitor锁定线 ...
- 一步步学习javascript基础篇(0):开篇索引
索引: 一步步学习javascript基础篇(1):基本概念 一步步学习javascript基础篇(2):作用域和作用域链 一步步学习javascript基础篇(3):Object.Function等 ...
- 2000条你应知的WPF小姿势 基础篇<15-21>
在正文开始之前需要介绍一个人:Sean Sexton. 来自明尼苏达双城的软件工程师,对C#和WPF有着极深的热情.最为出色的是他维护了两个博客:2,000Things You Should Know ...
- ABP框架实践基础篇之开发UI层
返回总目录<一步一步使用ABP框架搭建正式项目系列教程> 说明 其实最开始写的,就是这个ABP框架实践基础篇.在写这篇博客之前,又回头复习了一下ABP框架的理论,如果你还没学习,请查看AB ...
- C#多线程之基础篇2
在上一篇C#多线程之基础篇1中,我们主要讲述了如何创建线程.中止线程.线程等待以及终止线程的相关知识,在本篇中我们继续讲述有关线程的一些知识. 五.确定线程的状态 在这一节中,我们将讲述如何查看一个线 ...
- C#多线程之基础篇1
在多线程这一系列文章中,我们将讲述C#语言中多线程的相关知识,在多线程(基础篇)中我们将学习以下知识点: 创建线程 中止线程 线程等待 终止线程 确定线程的状态 线程优先级 前台线程和后台线程 向线程 ...
- iOS系列 基础篇 03 探究应用生命周期
iOS系列 基础篇 03 探究应用生命周期 目录: 1. 非运行状态 - 应用启动场景 2. 点击Home键 - 应用退出场景 3. 挂起重新运行场景 4. 内存清除 - 应用终止场景 5. 结尾 本 ...
- iOS系列 基础篇 04 探究视图生命周期
iOS系列 基础篇 04 探究视图生命周期 视图是应用的一个重要的组成部份,功能的实现与其息息相关,而视图控制器控制着视图,其重要性在整个应用中不言而喻. 以视图的四种状态为基础,我们来系统了解一下视 ...
- iOS系列 基础篇 05 视图鼻祖 - UIView
iOS系列 基础篇 05 视图鼻祖 - UIView 目录: UIView“家族” 应用界面的构建层次 视图分类 最后 在Cocoa和Cocoa Touch框架中,“根”类时NSObject类.同样, ...
随机推荐
- MapReduce Service更换集群外部时钟源,仅需10步
摘要:MapReduce Service 集群使用NTP进行时钟同步.本文简要介绍了MapReduce Service集群NTP机制及NTP的配置方式. 本文分享自华为云社区<MapReduce ...
- Java测试开发--Comparable和Comparator接口(五)
Comparable 简介Comparable 是排序接口.若一个类实现了Comparable接口,就意味着"该类支持排序".此外,"实现Comparable接口的类的对 ...
- 一款吊炸天的AI图片增强工具!
背景 如果你工作中需要制作文档,PPT,或者给文章配图,或者需要制作视频.一定会有在网上寻找图片素材的经历. 但网上的图质量参差不一,有时候找到了喜欢的图,但是质量不行,分辨率太低. 有的人就忍了,但 ...
- ThreadPoolExecutor里面4种拒绝策略(详细)
ThreadPoolExecutor类实现了ExecutorService接口和Executor接口,可以设置线程池corePoolSize,最大线程池大小,AliveTime,拒绝策略等.常用构造方 ...
- Java 初始化与清理
用构造器确保初始化 如何自定义构造器(constructor)? 构造器方法的名称与类名相同,并且没有返回值. 需要注意,在定义构方法时,方法名前面不要添加任何的类型说明符,格式:类名(){},构造方 ...
- Python 函数 参数传递
参数传递 在 python 中,类型属于对象,变量是没有类型的: a=[1,2,3] a="Runoob" 以上代码中,[1,2,3] 是 ...
- Maven 依赖调解源码解析(四):传递依赖,第一声明者优先
本文是系列文章<Maven 源码解析:依赖调解是如何实现的?>第四篇,主要介绍依赖调解的第二条原则:传递依赖,第一声明者优先.请按顺序阅读其他系列文章,系列文章总目录参见:https:// ...
- [uoj576]服务调度
先考虑一个子问题:仅有一个询问且无修改 对每一种颜色的贡献分类讨论,结论:最远的点一定这些点集中(任意一组)最远点对中的两个点(选择较远的一个) 证明:设$dis(x,y)$为$x$到$y$的距离,$ ...
- [atARC094F]Normalization
考虑$s$能变成$t$的必要条件(假设$s\ne t$): 1.$s$中存在一对相邻字符不同 2.$|s|=|t|$且若将a-c对应为0-2,则字符模3同余: 3.$t$中存在一对相邻两个字符相同 同 ...
- [loj3048]异或粽子
先对其求出前缀异或和,然后$o(k)$次枚举,每次选择最大值,考虑如何维护可以全局开一个堆,维护出每一个点的最大值的最大值,那么相当于要在一个点中删去一个点再找到最大值将这些删去的点重新建成一颗tri ...