日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

Struts2源码阅读(五)_FilterDispatcher核心控制器

發(fā)布時間:2024/7/23 编程问答 35 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Struts2源码阅读(五)_FilterDispatcher核心控制器 小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.

Dispatcher已經在之前講過,這就好辦了。FilterDispatcher是Struts2的核心控制器,首先看一下init()方法。

public void init(FilterConfig filterConfig) throws ServletException { try { this.filterConfig = filterConfig; initLogging(); //創(chuàng)建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); }

現(xiàn)在回去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所注入的實現(xiàn)類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實現(xiàn) //此時在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配置的包路徑去查找對應的靜態(tài)資源并輸出到頁面流中,當然.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接口的實現(xiàn)類 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包下的文件當作靜態(tài)資源處理,即直接在頁面上顯示文件內容,不過會忽略擴展名為class的文件。比如在com.lizanhong.action包下有一個aaa.txt的文本文件,其內容為“中華人民共和國”,訪問? http://localhost:8081/Struts2Demo/struts/aaa.txt 時會輸出txt中的內容
?? FilterDispatcher.findStaticResource()方法

protected void 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個字節(jié)的方式循環(huán)輸出 copy(is, response.getOutputStream()); } finally { is.close(); } return; } } } } 如果用戶請求的資源不是以/struts開頭——可能是.jsp文件,也可能是.html文件,則通過過濾器鏈繼續(xù)往下傳送,直到到達請求的資源為止。
如果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(); //創(chuàng)建一個Action的代理對象,ActionProxyFactory是創(chuàng)建ActionProxy的工廠 //參考實現(xiàn)類: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 { //執(zhí)行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); } }

創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎勵來咯,堅持創(chuàng)作打卡瓜分現(xiàn)金大獎

總結

以上是生活随笔為你收集整理的Struts2源码阅读(五)_FilterDispatcher核心控制器的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。