struts1源碼學習1

來源:互聯網
上載者:User

標籤:struts1 源碼 java actionservlet

初始化方法學習

public class ActionServlet extends HttpServlet//servlet初始化 public void init() throws ServletException {        final String configPrefix = "config/";        final int configPrefixLength = configPrefix.length() - 1;        // Wraps the entire initialization in a try/catch to better handle        // unexpected exceptions and errors to provide better feedback        // to the developer        try {            initInternal();            initOther();            initServlet();            initChain();            getServletContext().setAttribute(Globals.ACTION_SERVLET_KEY, this);            initModuleConfigFactory();            // Initialize modules as needed            ModuleConfig moduleConfig = initModuleConfig("", config);            initModuleMessageResources(moduleConfig);            initModulePlugIns(moduleConfig);            initModuleFormBeans(moduleConfig);            initModuleForwards(moduleConfig);            initModuleExceptionConfigs(moduleConfig);            initModuleActions(moduleConfig);            moduleConfig.freeze();            Enumeration names = getServletConfig().getInitParameterNames();            while (names.hasMoreElements()) {                String name = (String) names.nextElement();                if (!name.startsWith(configPrefix)) {                    continue;                }                String prefix = name.substring(configPrefixLength);                moduleConfig =                    initModuleConfig(prefix,                        getServletConfig().getInitParameter(name));                initModuleMessageResources(moduleConfig);                initModulePlugIns(moduleConfig);                initModuleFormBeans(moduleConfig);                initModuleForwards(moduleConfig);                initModuleExceptionConfigs(moduleConfig);                initModuleActions(moduleConfig);                moduleConfig.freeze();            }            this.initModulePrefixes(this.getServletContext());            this.destroyConfigDigester();        } catch (UnavailableException ex) {            throw ex;        } catch (Throwable t) {            // The follow error message is not retrieved from internal message            // resources as they may not have been able to have been            // initialized            log.error("Unable to initialize Struts ActionServlet due to an "                + "unexpected exception or error thrown, so marking the "                + "servlet as unavailable.  Most likely, this is due to an "                + "incorrect or missing library dependency.", t);            throw new UnavailableException(t.getMessage());        }    }

1、initInternal方法

 protected void initInternal()        throws ServletException {        try {//internalName是org.apache.struts.action.ActionResources            internal = MessageResources.getMessageResources(internalName);        } catch (MissingResourceException e) {            log.error("Cannot load internal resources from ‘" + internalName                + "‘", e);            throw new UnavailableException(                "Cannot load internal resources from ‘" + internalName + "‘");        }    }

看一下org.apache.struts.action.ActionResources,提示資訊資料,我這看到的是英文版和日文版
該方法主要就是載入提示資訊資料,載入完成後儲存到internal這個屬性裡

2、initOther方法

protected void initOther()        throws ServletException {        String value;//讀取actionservlet的設定檔,config預設是/WEB-INF/struts-config.xml        value = getServletConfig().getInitParameter("config");        if (value != null) {            config = value;        }        // Backwards compatibility for form beans of Java wrapper classes        // Set to true for strict Struts 1.0 compatibility//從web.xml讀取資料轉換器開關        value = getServletConfig().getInitParameter("convertNull");        if ("true".equalsIgnoreCase(value) || "yes".equalsIgnoreCase(value)            || "on".equalsIgnoreCase(value) || "y".equalsIgnoreCase(value)            || "1".equalsIgnoreCase(value)) {            convertNull = true;        }        if (convertNull) {            ConvertUtils.deregister();//幾種類型轉換            ConvertUtils.register(new BigDecimalConverter(null),                BigDecimal.class);            ConvertUtils.register(new BigIntegerConverter(null),                BigInteger.class);            ConvertUtils.register(new BooleanConverter(null), Boolean.class);            ConvertUtils.register(new ByteConverter(null), Byte.class);            ConvertUtils.register(new CharacterConverter(null), Character.class);            ConvertUtils.register(new DoubleConverter(null), Double.class);            ConvertUtils.register(new FloatConverter(null), Float.class);            ConvertUtils.register(new IntegerConverter(null), Integer.class);            ConvertUtils.register(new LongConverter(null), Long.class);            ConvertUtils.register(new ShortConverter(null), Short.class);        }    }

3、initServlet()方法

讀取並解析struts的設定檔(struts-config.xml)

protected void initServlet()        throws ServletException {        // Remember our servlet name//通過servletconfig獲得該servlet名稱        this.servletName = getServletConfig().getServletName();        // Prepare a Digester to scan the web application deployment descriptor//apache的一個xml解析工具        Digester digester = new Digester();//把當前對象(ActinServlet)放入digester中        digester.push(this);        digester.setNamespaceAware(true);        digester.setValidating(false);        // Register our local copy of the DTDs that we can find//解析了幾個dtd,struts1內建的        for (int i = 0; i < registrations.length; i += 2) {            URL url = this.getClass().getResource(registrations[i + 1]);            if (url != null) {                digester.register(registrations[i], url.toString());            }        }        // Configure the processing rules that we need//類似xpath,得到web-app/servlet-mapping下的參數,並傳給ActinServletaddServletMapping方法執行</span>        digester.addCallMethod("web-app/servlet-mapping", "addServletMapping", 2);//將web-app/servlet-mapping/servlet-name的值,作為方法的第一個參數        digester.addCallParam("web-app/servlet-mapping/servlet-name", 0);//將web-app/servlet-mapping/url-pattern的值,作為方法的第二個參數        digester.addCallParam("web-app/servlet-mapping/url-pattern", 1);        // Process the web application deployment descriptor        if (log.isDebugEnabled()) {            log.debug("Scanning web.xml for controller servlet mapping");        }//讀取/WEB-INF/web.xml(寫死的        InputStream input =            getServletContext().getResourceAsStream("/WEB-INF/web.xml");        if (input == null) {            log.error(internal.getMessage("configWebXml"));            throw new ServletException(internal.getMessage("configWebXml"));        }        try {//解析xml,隨後執行了前面的方法addServletMapping            digester.parse(input);        } catch (IOException e) {            log.error(internal.getMessage("configWebXml"), e);            throw new ServletException(e);        } catch (SAXException e) {            log.error(internal.getMessage("configWebXml"), e);            throw new ServletException(e);        } finally {            try {                input.close();            } catch (IOException e) {                log.error(internal.getMessage("configWebXml"), e);                throw new ServletException(e);            }        }        // Record a servlet context attribute (if appropriate)        if (log.isDebugEnabled()) {            log.debug("Mapping for servlet ‘" + servletName + "‘ = ‘"                + servletMapping + "‘");        }        if (servletMapping != null) {//把struts1配置的url匹配字串放入servletcontext中            getServletContext().setAttribute(Globals.SERVLET_KEY, servletMapping);        }    }


本文出自 “helloworld” 部落格,轉載請與作者聯絡!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.