Dispatcher已經在之前講過,這就好辦了。FilterDispatcher是Struts2的核心控制器,首先看一下init()方法。
- public void init(FilterConfig filterConfig) throws ServletException {
- try {
- this.filterConfig = filterConfig;
- initLogging();
- //創建dispatcher,前面都已經講過囉
- dispatcher = createDispatcher(filterConfig);
- dispatcher.init();
- //注入將FilterDispatcher中的變量通過container注入,如下面的staticResourceLoader
- dispatcher.getContainer().inject(this);
- //StaticContentLoader在BeanSelectionProvider中已經被注入了依賴關係:DefaultStaticContentLoader
- //可以在struts-default.xml中的<bean>可以找到
- staticResourceLoader.setHostConfig(new FilterHostConfig(filterConfig));
- } finally {
- ActionContext.setContext(null);
- }
- }
- //下面來看DefaultStaticContentLoader的setHostConfig
- public void setHostConfig(HostConfig filterConfig) {
- //讀取初始參數pakages,調用parse(),解析成類似/org/apache/struts2/static,/template的數組
- String param = filterConfig.getInitParameter("packages");
- //"org.apache.struts2.static template org.apache.struts2.interceptor.debugging static"
- 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 {
- // FIXME: this should be refactored better to not duplicate work with the action invocation
- //先看看ValueStackFactory所注入的實現類OgnlValueStackFactory
- //new OgnlValueStack
- ValueStack stack = dispatcher.getContainer().getInstance(ValueStackFactory.class).createValueStack();
- ActionContext ctx = new ActionContext(stack.getContext());
- ActionContext.setContext(ctx);
- UtilTimerStack.push(timerKey);
- //如果是multipart/form-data就用MultiPartRequestWrapper進行包裝
- //MultiPartRequestWrapper是StrutsRequestWrapper的子類,兩者都是HttpServletRequest實現
- //此時在MultiPartRequestWrapper中就會把Files給解析出來,用於文件上傳
- //所有request都會StrutsRequestWrapper進行包裝,StrutsRequestWrapper是可以訪問ValueStack
- //下面是參見Dispatcher的wrapRequest
- // String content_type = request.getContentType();
- //if(content_type!= null&&content_type.indexOf("multipart/form-data")!=-1){
- //MultiPartRequest multi =getContainer().getInstance(MultiPartRequest.class);
- //request =new MultiPartRequestWrapper(multi,request,getSaveDir(servletContext));
- //} else {
- // request = new StrutsRequestWrapper(request);
- // }
- request = prepareDispatcherAndWrapRequest(request, response);
- ActionMapping mapping;
- try {
- //根據url取得對應的Action的配置信息
- //看一下注入的DefaultActionMapper的getMapping()方法.Action的配置信息存儲在 ActionMapping對象中
- 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 (staticResourceLoader.canHandle(resourcePath)) {
- // 在DefaultStaticContentLoader中:return serveStatic && (resourcePath.startsWith("/struts") || resourcePath.startsWith("/static"));
- staticResourceLoader.findStaticResource(resourcePath, request, response);
- } else {
- // this is a normal request, let it pass through
- chain.doFilter(request, response);
- }
- // The framework did its job here
- return;
- }
- //正式開始Action的方法
- dispatcher.serviceAction(request, response, servletContext, mapping);
- } finally {
- try {
- ActionContextCleanUp.cleanUp(req);
- } finally {
- UtilTimerStack.pop(timerKey);
- }
- }
- }
- //下面是ActionMapper接口的實現類 DefaultActionMapper的getMapping()方法的源代碼:
- public ActionMapping getMapping(HttpServletRequest request,
- ConfigurationManager configManager) {
- ActionMapping mapping = new ActionMapping();
- String uri = getUri(request);//得到請求路徑的URI,如:testAtcion.action或testAction.do
- int indexOfSemicolon = uri.indexOf(";");//修正url的帶;jsessionid 時找不到而且的bug
- uri = (indexOfSemicolon > -1) ? uri.substring(0, indexOfSemicolon) : uri;
- uri = dropExtension(uri, mapping);//刪除擴展名,默認擴展名爲action
- if (uri == null) {
- return null;
- }
- parseNameAndNamespace(uri, mapping, configManager);//匹配Action的name和namespace
- handleSpecialParameters(request, mapping);//去掉重複參數
- //如果Action的name沒有解析出來,直接返回
- if (mapping.getName() == null) {
- returnnull;
- }
- //下面處理形如testAction!method格式的請求路徑
- if (allowDynamicMethodCalls) {
- // handle "name!method" convention.
- String name = mapping.getName();
- int exclamation = name.lastIndexOf("!");//!是Action名稱和方法名的分隔符
- if (exclamation != -1) {
- mapping.setName(name.substring(0, exclamation));//提取左邊爲name
- mapping.setMethod(name.substring(exclamation + 1));//提取右邊的method
- }
- }
- 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")) {//忽略class文件
- //遍歷packages參數
- for (String pathPrefix : pathPrefixes) {
- InputStream is = findInputStream(name, pathPrefix);//讀取請求文件流
- if (is != null) {
- ...
- // set the content-type header
- String contentType = getContentType(name);//讀取內容類型
- if (contentType != null) {
- response.setContentType(contentType);//重新設置內容類型
- }
- ...
- try {
- //將讀取到的文件流以每次複製4096個字節的方式循環輸出
- copy(is, response.getOutputStream());
- } finally {
- is.close();
- }
- return;
- }
- }
- }
- }
如果用戶請求的資源不是以/struts開頭——可能是.jsp文件,也可能是.html文件,則通過過濾器鏈繼續往下傳送,直到到達請求的資源爲止。
如果getMapping()方法返回有效的ActionMapping對象,則被認爲正在請求某個Action,將調用 Dispatcher.serviceAction(request, response, servletContext, mapping)方法,該方法是處理Action的關鍵所在。
下面就來看serviceAction,這又回到全局變量dispatcher中了
- //Load Action class for mapping and invoke the appropriate Action method, or go directly to the Result.
- public void serviceAction(HttpServletRequest request, HttpServletResponse response, ServletContext context,
- ActionMapping mapping) throws ServletException {
- //createContextMap方法主要把Application、Session、Request的key value值拷貝到Map中
- 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);
- 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();
- //創建一個Action的代理對象,ActionProxyFactory是創建ActionProxy的工廠
- //參考實現類:DefaultActionProxy和DefaultActionProxyFactory
- 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!
- //如果是Result,則直接轉向,關於Result,ActionProxy,ActionInvocation下一講中再分析
- if (mapping.getResult() != null) {
- Result result = mapping.getResult();
- result.execute(proxy.getInvocation());
- } else {
- //執行Action
- proxy.execute();
- }
- // If there was a previous value stack then set it back onto the request
- if (!nullStack) {
- request.setAttribute(ServletActionContext.STRUTS_VALUESTACK_KEY, stack);
- }
- } catch (ConfigurationException e) {
- // WW-2874 Only log error if in devMode
- 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);
- }
- }
Come From: http://qidaoxp.javaeye.com/blog/501088