FilterDispatcher是Struts2的核心控制器,首先看一下init()方法。
- public void init(FilterConfig filterConfig) throws ServletException {
- try {
- this.filterConfig = filterConfig;
- initLogging();
-
- dispatcher = createDispatcher(filterConfig);
- dispatcher.init();
-
- dispatcher.getContainer().inject(this);
-
-
- staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig));
- } finally {
- ActionContext.setContext(null);
- }
- }
-
- public void setHostConfig(HostConfig filterConfig) {
-
- String param = filterConfig.getInitParameter("packages");
-
- String packages = getAdditionalPackages();
- if (param != null) {
- packages = param + " " + packages;
- }
- this.pathPrefixes = parse(packages);
- initLogging(filterConfig);
- }
现在回去doFilter的方法,每当有一个Request,都会调用这些Filters的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);
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- 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 (staticResourceLoader.canHandle(resourcePath)) {
-
- staticResourceLoader.findStaticResource(resourcePath, request, response);
- } else {
-
- chain.doFilter(request, response);
- }
-
- return;
- }
-
- dispatcher.serviceAction(request, response, servletContext, mapping);
-
- } finally {
- try {
- ActionContextCleanUp.cleanUp(req);
- } finally {
- UtilTimerStack.pop(timerKey);
- }
- }
- }
-
- public ActionMapping getMapping(HttpServletRequest request,
- ConfigurationManager configManager) {
- ActionMapping mapping = new ActionMapping();
- String uri = getUri(request);
-
-
- int indexOfSemicolon = uri.indexOf(";");
- uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;
-
- uri = dropExtension(uri, mapping);
- if (uri == null) {
- return null;
- }
-
- parseNameAndNamespace(uri, mapping, configManager);
-
- handleSpecialParameters(request, mapping);
-
-
- if (mapping.getName() == null) {
- returnnull;
- }
-
- if (allowDynamicMethodCalls) {
-
- String name = mapping.getName();
- int exclamation = name.lastIndexOf("!");
- if (exclamation != -1) {
- mapping.setName(name.substring(0, exclamation));
- mapping.setMethod(name.substring(exclamation + 1));
- }
- }
-
- return mapping;
- }
从代码中看出,getMapping()方法返回ActionMapping类型的对象,该对象包含三个参数:Action的name、namespace和要调用的方法method。
如果getMapping()方法返回ActionMapping对象为null,则FilterDispatcher认为用户请求不是Action,自然另当别论,FilterDispatcher会做一件非常有意思的事:如果请求以/struts开头,会自动查找在web.xml文件中配置的 packages初始化参数,就像下面这样:
- <filter>
- <filter-name>struts2</filter-name>
- <filter-class>
- org.apache.struts2.dispatcher.FilterDispatcher
- </filter-class>
- <init-param>
- <param-name>packages</param-name>
- <param-value>com.lizanhong.action</param-value>
- </init-param>
- </filter>
FilterDispatcher会将com.lizanhong.action包下的文件当作静态资源处理,即直接在页面上显示文件内容,不过会忽略扩展名为class的文件。比如在com.lizanhong.action包下有一个aaa.txt的文本文件,其内容为“中华人民共和国”,访问 http://localhost:8081/Struts2Demo/struts/aaa.txt时会输出txt中的内容
FilterDispatcher.findStaticResource()方法
- protectedvoid findStaticResource(String name, HttpServletRequest request, HttpServletResponse response) throws IOException {
- if (!name.endsWith(".class")) {
-
- for (String pathPrefix : pathPrefixes) {
- InputStream is = findInputStream(name, pathPrefix);
- if (is != null) {
- ...
-
- String contentType = getContentType(name);
- if (contentType != null) {
- response.setContentType(contentType);
- }
- ...
- try {
-
- copy(is, response.getOutputStream());
- } finally {
- is.close();
- }
- return;
- }
- }
- }
- }
如果用户请求的资源不是以/struts开头——可能是.jsp文件,也可能是.html文件,则通过过滤器链继续往下传送,直到到达请求的资源为止。
如果getMapping()方法返回有效的ActionMapping对象,则被认为正在请求某个Action,将调用 Dispatcher.serviceAction(request, response, servletContext, mapping)方法,该方法是处理Action的关键所在。
下面就来看serviceAction,这又回到全局变量dispatcher中了
-
- public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
- ActionMapping mapping) throws ServletException {
-
- Map<String, Object> extraContext = createContextMap(request, response, mapping, context);
-
-
- ValueStack stack = (ValueStack) request.getAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY);
- boolean nullStack = stack == null;
- if (nullStack) {
- ActionContext ctx = ActionContext.getContext();
- if (ctx != null) {
- stack = ctx.getValueStack();
- }
- }
- 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 (mapping.getResult() != null) {
- Result result = mapping.getResult();
- result.execute(proxy.getInvocation());
- } else {
-
- proxy.execute();
- }
-
-
- if (!nullStack) {
- request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
- }
- } catch (ConfigurationException e) {
-
- if(devMode) {
- LOG.error("Could not find action or result", e);
- }
- else {
- LOG.warn("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);
- }
- }