struts2笔记(1)--工作流程

[b]核心控制器FilterDispatcher[/b]

核心控制器FilterDispatcher是Struts 2框架的基础,包含了框架内部的控制流程和处理机制。业务控制器Action和业务逻辑组件是需要用户来自己实现的。用户在开发Action和业务逻辑组件的同时,还需要编写相关的配置文件,供核心控制器FilterDispatcher来使用。

Struts 2的工作流程相对于Struts 1要简单,与WebWork框架基本相同,所以说Struts 2是WebWork的升级版本。Struts 2框架按照模块来划分,可以分为Servlet Filters、Struts核心模块、拦截器和用户实现部分。Struts 2框架结构图如图3.1所示。

[img]http://wishlife.iteye.com/upload/picture/pic/28863/bb9f5a85-5088-3241-b431-cd9c1d959e8c.jpg[/img]
图3.1 Struts 2框架结构图

一个请求在Struts 2框架中的处理大概分为以下几个步骤。


[list]
[*]客户端提交一个(HttpServletRequest)请求,如上文在浏览器中输入
http://localhost: 8080/bookcode/ch2/Reg.action就是提交一个(HttpServletRequest)请求。


[*]请求被提交到一系列(主要是3层)的过滤器(Filter),如(ActionContextCleanUp、其他过滤器(SiteMesh等)、 FilterDispatcher)。注意:这里是有顺序的,先ActionContext CleanUp,再其他过滤器(Othter Filters、SiteMesh等),最后到FilterDispatcher。

[*]FilterDispatcher是控制器的核心,就是MVC的Struts 2实现中控制层(Controller)的核心。

[*]FilterDispatcher询问ActionMapper是否需要调用某个Action来处理这个(HttpServlet Request)请求,如果ActionMapper决定需要调用某个Action,FilterDispatcher则把请求的处理交给ActionProxy。

[*]ActionProxy通过Configuration Manager(struts.xml)询问框架的配置文件,找到需要调用的Action类。例如,用户注册示例将找到UserReg类。

[*]ActionProxy创建一个ActionInvocation实例,同时ActionInvocation通过代理模式调用Action。但在调用之前,ActionInvocation会根据配置加载Action相关的所有Interceptor(拦截器)。

[*]一旦Action执行完毕,ActionInvocation负责根据struts.xml中的配置找到对应的返回结果result。
[/list]

[b]Struts 2的核心控制器是FilterDispatcher,有3个重要的方法:destroy()、doFilter()和Init()[/b],可以在Struts 2的下载文件夹中找到源代码,如代码3.1所示。

代码3.1 核心控制器FilterDispatcher


public class FilterDispatcher implements StrutsStatics, Filter {

/**

* 定义一个Log实例

*/

private static final Log LOG = LogFactory.getLog(FilterDispatcher.class);

/**

* 存放属性文件中的.STRUTS_I18N_ENCODING值

*/

private static String encoding;

/**

* 定义ActionMapper实例

*/

private static ActionMapper actionMapper;

/**

* 定义FilterConfig实例

*/

private FilterConfig filterConfig;

protected Dispatcher dispatcher;

/**

* 创建一个默认的dispatcher,初始化filter

* 设置默认的packages *

*/

public void init(FilterConfig filterConfig) throws ServletException {

this.filterConfig = filterConfig;

dispatcher = createDispatcher(filterConfig);

dispatcher.init();

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);

}

//销毁filter方法

public void destroy() {

if (dispatcher == null) {

LOG.warn("something is seriously wrong, Dispatcher is not initialized (null) ");

} else {

dispatcher.cleanup();

}

}

/**

* 处理一个Action或者资源请求

* <p/>

* filter尝试将请求同action mapping相匹配

* 如果找到,将执行dispatcher的serviceAction方法

* 如果Action处理失败, doFilter将建立一个异常

* <p/>

* 如果请求静态资源

* 资源将被直接复制给 response

* <p/>

* 如果找不到匹配Action 或者静态资源,则直接跳出

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 {

UtilTimerStack.push(timerKey);

request = prepareDispatcherAndWrapRequest(request, response);

ActionMapping mapping;

try {

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;

}

if (mapping == null) {

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 {

//为一个普通的request, 则通过

chain.doFilter(request, response);

}

return;

}

/**

*这个方法询问ActionMapper是否需要调用某个Action来处理这个(request)请求,

*如果ActionMapper决定需要调用某个Action,

*FilterDispatcher则把请求的处理交给ActionProxy

dispatcher.serviceAction(request, response, servletContext, mapping);

} finally {

try {

ActionContextCleanUp.cleanUp(req);

} finally {

UtilTimerStack.pop(timerKey);

}

}

}

… …

}



[b]在doFilter()方法中,将调用dispatcher.serviceAction,该方法如果找到相应的Action,将把用户请求交给ActionProxy。serviceAction()代码在Dispatcher.java中[/b],如代码3.2所示。

代码3.2 Dispatcher类


public class Dispatcher {

...

/**

* 为mapping加载类,并调用相应的方法或者直接返回result

* <p/>

* 根据用户请求的参数,建立Action上下文

* 根据指定的Action’名称和包空间名称,加载一个Action代理 <tt>ActionProxy</tt>

* 然后Action的相应方法将被执行,

*/

public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context, ActionMapping mapping) throws ServletException {

Map<String, Object> extraContext = createContextMap(request, response, mapping, context);

//如果存在一个值栈,则建立一个新的并复制以备Action使用

ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);

if (stack!= null) {

extraContext.put(ActionContext.VALUE_STACK, ValueStackFactory.getFactory().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();

//FilterDispatcher把请求的处理交给ActionProxy

ActionProxy proxy = config.getContainer().getInstance(ActionProxyFactory.class).createActionProxy(namespace, name, extraContext, true, false);

proxy.setMethod(method);

request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, proxy.getInvocation().getStack());

//ActionMapping 直接返回一个result

if (mapping.getResult() != null) {

Result result = mapping.getResult();

result.execute(proxy.getInvocation());

} else {

proxy.execute();

}

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) {

throw new ServletException(e);

} finally {

UtilTimerStack.pop(timerKey);

}

}








从上面代码中可以看出来,Struts 2用于处理用户请求的Action实例,并不是用户实现的业务控制器,而是Action代理。关于Action代理相关内容,读者可以参考拦截器章节的介绍。

[quote]★ 提示 ★

前面一直在说Action可以是一个普通的Java类,与Servlet API完全分离,但是为了实现业务逻辑,Action需要使用HttpServletRequest内容。
[/quote]

Struts 2设计的精巧之处就是使用了Action代理,Action代理可以根据系统的配置,加载一系列的拦截器,由拦截器将HttpServletRequest参数解析出来,传入Action。同样,Action处理的结果也是通过拦截器传入HttpServletResponse,然后由HttpServletRequest传给用户。

其实,该处理过程是典型的AOP(面向切面编程)的方式。Struts 2处理过程模型如图3.2所示。

[img]http://wishlife.iteye.com/upload/picture/pic/28861/902303c7-db08-3d7e-aa4d-8a291a262060.jpg[/img]


图3.2 Struts 2处理过程模型

[quote]★ 说明 ★

拦截器是Struts 2框架的核心,通过拦截器,实现了AOP(面向切面编程)。使用拦截器,可以简化Web开发中的某些应用,例如,权限拦截器可以简化Web应用中的权限检查。
[/quote]

3.1.2 业务控制器Action
业务控制器Action是由开发者自己编写实现的,Action类可以是一个简单的Java类,与Servlet API完全分离。Action一般都有一个execute()方法,也可以定义其他业务控制方法,详细内容将在后面介绍。

Action的execute()返回一个String类型值,这与Struts 1返回的ActionForward相比,简单易懂。Struts 2提供了一个ActionSupport工具类,该类实现了Action接口和validate()方法,一般开发者编写Action可以直接继承ActionSupport类。编写Action类后,开发者还必须在配置文件中配置Action。一个Action的配置应该包含下面几个元素:
[list]

[*]1、该Action的name,即用户请求所指向的URL。

[*]2、Action所对应的class元素,对应Action类的位置。

[*]3、指定result逻辑名称和实际资源的定位。
[/list]

Action是业务控制器,笔者建议在编写Action的时候,尽量避免将业务逻辑放到其中,尽量减少Action与业务逻辑模块或者组件的耦合程度。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值