interface21 - web - ContextLoaderListener(Spring Web Application Context載入流程)

来源:https://www.cnblogs.com/chenpi/archive/2018/08/23/9527304.html
-Advertisement-
Play Games

前言 最近打算花點時間好好看看spring的源碼,然而現在Spring的源碼經過迭代的版本太多了,比較龐大,看起來比較累,所以準備從最初的版本(interface21)開始入手,僅用於學習,理解其設計思想,後續慢慢研究其每次版本變更的內容。。。 先從interface21的一個典型web工程例子看起 ...


前言 

最近打算花點時間好好看看spring的源碼,然而現在Spring的源碼經過迭代的版本太多了,比較龐大,看起來比較累,所以準備從最初的版本(interface21)開始入手,僅用於學習,理解其設計思想,後續慢慢研究其每次版本變更的內容。。。

先從interface21的一個典型web工程例子看起,寵物診所 - petclinic,因為該工程基本涵蓋了Spring的APO、IOC、JDBC、Web MVC、事務、國際化、主題切換、參數校驗等主要功能。。。

繼上一篇,瞭解完Log4jConfigListener(載入Log4j日誌)的流程後,看看ContextLoaderListener(載入Spring Web Application Context)流程是如何的~~~~~~~

對應的web.xml配置

    <listener>
        <listener-class>com.interface21.web.context.ContextLoaderListener</listener-class>
    </listener>

執行時序圖(看不清的話可以點擊查看原圖)

 

時序圖中的各個步驟簡要分析

執行的入口在ContextLoaderListener類的contextInitialized方法,由於ContextLoaderListener類實現了ServletContextListener介面,所以在Servlet容器(tomcat)啟動時,會自動調用contextInitialized方法。

步驟描述:

  1. 進入ContextLoaderListener類的contextInitialized方法,該類只有一句代碼,執行ContextLoader.initContext(event.getServletContext())方法;
    public void contextInitialized(ServletContextEvent event) {
            ContextLoader.initContext(event.getServletContext());
        }
  2. 進入ContextLoader類的initContext方法,首先,從servletContext中獲取contextClass參數,如果配置了該參數,則創建該實例對象,否則創建預設的XmlWebApplicationContext實例對象,接下來調用XmlWebApplicationContext的setServletContext方法;
    public static WebApplicationContext initContext(ServletContext servletContext) throws ApplicationContextException {
            servletContext.log("Loading root WebApplicationContext");
            String contextClass = servletContext.getInitParameter(CONTEXT_CLASS_PARAM);
    
            // Now we must load the WebApplicationContext.
            // It configures itself: all we need to do is construct the class with a no-arg
            // constructor, and invoke setServletContext.
            try {
                Class clazz = (contextClass != null ? Class.forName(contextClass) : DEFAULT_CONTEXT_CLASS);
                logger.info("Loading root WebApplicationContext: using context class '" + clazz.getName() + "'");
    
                if (!WebApplicationContext.class.isAssignableFrom(clazz)) {
                    throw new ApplicationContextException("Context class is no WebApplicationContext: " + contextClass);
                }
    
                WebApplicationContext webApplicationContext = (WebApplicationContext) clazz.newInstance();
                webApplicationContext.setServletContext(servletContext);
                return webApplicationContext;
    
            } catch (ApplicationContextException ex) {
                handleException("Failed to initialize application context", ex);
    
            } catch (BeansException ex) {
                handleException("Failed to initialize beans in application context", ex);
    
            } catch (ClassNotFoundException ex) {
                handleException("Failed to load config class '" + contextClass + "'", ex);
    
            } catch (InstantiationException ex) {
                handleException("Failed to instantiate config class '" + contextClass + "': does it have a public no arg constructor?", ex);
    
            } catch (IllegalAccessException ex) {
                handleException("Illegal access while finding or instantiating config class '" + contextClass + "': does it have a public no arg constructor?", ex);
    
            } catch (Throwable ex) {
                handleException("Unexpected error loading context configuration", ex);
            }
    
            return null;
        }
  3. 進入XmlWebApplicationContext類的setServletContext方法,首先,調用initConfigLocation方法從servletContext中獲取contextConfigLocation參數(Spring Application配置文件),如果沒配置該參數,則預設獲取/WEB-INF/applicationContext.xml該文件;
        public void setServletContext(ServletContext servletContext) throws ApplicationContextException {
            this.servletContext = servletContext;
            this.configLocation = initConfigLocation();
            logger.info("Using config location '" + this.configLocation + "'");
            refresh();
    
            if (this.namespace == null) {
                // We're the root context
                WebApplicationContextUtils.publishConfigObjects(this);
                // Expose as a ServletContext object
                WebApplicationContextUtils.publishWebApplicationContext(this);
            }
        }
  4. 迎來了非常關鍵的一步操作,調用AbstractApplicationContext類的refresh()方法,該方法具體如下,每個階段的英文註釋已經比較清晰了,下麵步驟也會做個詳細描述:
        public final void refresh() throws ApplicationContextException {
            if (this.contextOptions != null && !this.contextOptions.isReloadable())
                throw new ApplicationContextException("Forbidden to reload config");
    
            this.startupTime = System.currentTimeMillis();
    
            refreshBeanFactory();
    
            if (getBeanDefinitionCount() == 0)
                logger.warn("No beans defined in ApplicationContext [" + getDisplayName() + "]");
            else
                logger.info(getBeanDefinitionCount() + " beans defined in ApplicationContext [" + getDisplayName() + "]");
    
            // invoke configurers that can override values in the bean definitions
            invokeContextConfigurers();
    
            // load options bean for this context
            loadOptions();
    
            // initialize message source for this context
            initMessageSource();
    
            // initialize other special beans in specific context subclasses
            onRefresh();
    
            // check for listener beans and register them
            refreshListeners();
    
            // instantiate singletons this late to allow them to access the message source
            preInstantiateSingletons();
    
            // last step: publish respective event
            publishEvent(new ContextRefreshedEvent(this));
        }
  5. 首先,調用AbstractXmlApplicationContext類的refreshBeanFactory方法,該方法如下,具體完成的操作內容下麵步驟會詳細描述:
      protected void refreshBeanFactory() throws ApplicationContextException {
            String identifier = "application context with display name [" + getDisplayName() + "]";
            InputStream is = null;
            try {
                // Supports remote as well as local URLs
                is = getInputStreamForBeanFactory();
                this.xmlBeanFactory = new XmlBeanFactory(getParent());
                this.xmlBeanFactory.setEntityResolver(new ResourceBaseEntityResolver(this));
                this.xmlBeanFactory.loadBeanDefinitions(is);
                if (logger.isInfoEnabled()) {
                    logger.info("BeanFactory for application context: " + this.xmlBeanFactory);
                }
            } catch (IOException ex) {
                throw new ApplicationContextException("IOException parsing XML document for " + identifier, ex);
            } catch (NoSuchBeanDefinitionException ex) {
                throw new ApplicationContextException("Cannot load configuration: missing bean definition [" + ex.getBeanName() + "]", ex);
            } catch (BeansException ex) {
                throw new ApplicationContextException("Cannot load configuration: problem instantiating or initializing beans", ex);
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException ex) {
                    throw new ApplicationContextException("IOException closing stream for XML document for " + identifier, ex);
                }
            }
        }
  6. 調用XmlWebApplicationContext類的getInputStreamForBeanFactory方法,讀取階段3獲取到的配置文件為輸入流InputStream
        protected InputStream getInputStreamForBeanFactory() throws IOException {
            InputStream in = getResourceAsStream(this.configLocation);
            if (in == null) {
                throw new FileNotFoundException("Config location not found: " + this.configLocation);
            }
            return in;
        }
  7. 返回配置文件輸入流InputStream
  8. 回到AbstractXmlApplicationContext的refreshBeanFactory方法,new出一個XmlBeanFactory對象
  9. 設置xmlBeanFactory.setEntityResolver,這裡的EntityResolver主要用於尋找DTD聲明
  10. 調用xmlBeanFactory的loadBeanDefinitions方法載入bean定義聲明
  11. 進入xmlBeanFactory類的loadBeanDefinitions方法,解析讀取的配置文件流InputStream為org.w3c.dom.Document對象,然後調用loadBeanDefinitions方法依次解析各個bean元素節點信息
        public void loadBeanDefinitions(InputStream is) throws BeansException {
            if (is == null)
                throw new BeanDefinitionStoreException("InputStream cannot be null: expected an XML file", null);
    
            try {
                logger.info("Loading XmlBeanFactory from InputStream [" + is + "]");
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                logger.debug("Using JAXP implementation [" + factory + "]");
                factory.setValidating(true);
                DocumentBuilder db = factory.newDocumentBuilder();
                db.setErrorHandler(new BeansErrorHandler());
                db.setEntityResolver(this.entityResolver != null ? this.entityResolver : new BeansDtdResolver());
                Document doc = db.parse(is);
                loadBeanDefinitions(doc);
            } catch (ParserConfigurationException ex) {
                throw new BeanDefinitionStoreException("ParserConfiguration exception parsing XML", ex);
            } catch (SAXException ex) {
                throw new BeanDefinitionStoreException("XML document is invalid", ex);
            } catch (IOException ex) {
                throw new BeanDefinitionStoreException("IOException parsing XML document", ex);
            } finally {
                try {
                    if (is != null)
                        is.close();
                } catch (IOException ex) {
                    throw new FatalBeanException("IOException closing stream for XML document", ex);
                }
            }
        }
  12. 尋找Document中聲明為bean的Element節點,依次解析
        public void loadBeanDefinitions(Document doc) throws BeansException {
            Element root = doc.getDocumentElement();
            logger.debug("Loading bean definitions");
            NodeList nl = root.getElementsByTagName(BEAN_ELEMENT);
            logger.debug("Found " + nl.getLength() + " <" + BEAN_ELEMENT + "> elements defining beans");
            for (int i = 0; i < nl.getLength(); i++) {
                Node n = nl.item(i);
                loadBeanDefinition((Element) n);
            }
        }
  13. 解析Element節點內容,獲取class聲明信息、PropertyValues等信息,封裝成AbstractBeanDefinition對象,添加到beanDefinitionMap中
        private void loadBeanDefinition(Element el) throws BeansException {
            // The DTD guarantees an id attribute is present
            String id = el.getAttribute(ID_ATTRIBUTE);
            logger.debug("Parsing bean definition with id '" + id + "'");
    
            // Create BeanDefinition now: we'll build up PropertyValues later
            AbstractBeanDefinition beanDefinition;
    
            PropertyValues pvs = getPropertyValueSubElements(el);
            beanDefinition = parseBeanDefinition(el, id, pvs);
            registerBeanDefinition(id, beanDefinition);
    
            String name = el.getAttribute(NAME_ATTRIBUTE);
            if (name != null && !"".equals(name)) {
                // Automatically create this alias. Used for
                // names that aren't legal in id attributes
                registerAlias(id, name);
            }
        }
  14. 判斷是否需要註冊alias,放到aliasMap中,實際上就是維護了bean的name和id關係
  15. 返回到AbstractXmlApplicationContext類refreshBeanFactory方法中
  16. 返回到AbstractApplicationContext類refresh方法中
  17. 執行AbstractApplicationContext的invokeContextConfigurers方法,實際上內部是執行所有實現了BeanFactoryPostProcessor介面的bean的postProcessBeanFactory方法
        private void invokeContextConfigurers() {
            String[] beanNames = getBeanDefinitionNames(BeanFactoryPostProcessor.class);
            for (int i = 0; i < beanNames.length; i++) {
                String beanName = beanNames[i];
                BeanFactoryPostProcessor configurer = (BeanFactoryPostProcessor) getBean(beanName);
                configurer.postProcessBeanFactory(getBeanFactory());
            }
        }
  18. 執行AbstractApplicationContext的loadOptions方法,獲取contextOptions bean,首先,查看配置文件是否已經配置contextOptions bean,沒有則自己創建一個new ContextOptions()對象,主要用於當應用運行時,是否可以重新載入該配置,如果配置成false的話,會在調用refresh方法時,拋出一個ApplicationContextException("Forbidden to reload config")異常;
        private void loadOptions() {
            try {
                this.contextOptions = (ContextOptions) getBean(OPTIONS_BEAN_NAME);
            } catch (NoSuchBeanDefinitionException ex) {
                logger.info("No options bean (\"" + OPTIONS_BEAN_NAME + "\") found: using default");
                this.contextOptions = new ContextOptions();
            }
        }
  19. 執行AbstractApplicationContext的initMessageSource方法,獲取messageSource bean,首先,查看配置文件是否已經配置messageSource bean,沒有則自己創建一個StaticMessageSource對象,註意如果Parent context不為null的話,需要設置Parent MessageSource
        private void initMessageSource() {
            try {
                this.messageSource = (MessageSource) getBean(MESSAGE_SOURCE_BEAN_NAME);
                // set parent message source if applicable,
                // and if the message source is defined in this context, not in a parent
                if (this.parent != null && (this.messageSource instanceof NestingMessageSource) &&
                        Arrays.asList(getBeanDefinitionNames()).contains(MESSAGE_SOURCE_BEAN_NAME)) {
                    ((NestingMessageSource) this.messageSource).setParent(this.parent);
                }
            } catch (NoSuchBeanDefinitionException ex) {
                logger.info("No MessageSource found for [" + getDisplayName() + "]: using empty StaticMessageSource");
                // use empty message source to be able to accept getMessage calls
                this.messageSource = new StaticMessageSource();
            }
        }
  20. 執行AbstractXmlUiApplicationContext的onRefresh方法,獲取themeSource bean, 主題相關(如應用可配置暗色主題或亮色主題功能),同樣,這裡也首先查看配置文件是否已經配置themeSource bean,沒有則自己創建一個ResourceBundleThemeSource對象,註意這裡還需要根據判斷條件設置Parent ThemeSource
        protected void onRefresh() {
            this.themeSource = UiApplicationContextUtils.initThemeSource(this);
        }
        public static ThemeSource initThemeSource(ApplicationContext applicationContext) {
            ThemeSource themeSource;
            try {
                themeSource = (ThemeSource) applicationContext.getBean(THEME_SOURCE_BEAN_NAME);
                // set parent theme source if applicable,
                // and if the theme source is defined in this context, not in a parent
                if (applicationContext.getParent() instanceof ThemeSource && themeSource instanceof NestingThemeSource &&
                        Arrays.asList(applicationContext.getBeanDefinitionNames()).contains(THEME_SOURCE_BEAN_NAME)) {
                    ((NestingThemeSource) themeSource).setParent((ThemeSource) applicationContext.getParent());
                }
            } catch (NoSuchBeanDefinitionException ex) {
                logger.info("No ThemeSource found for [" + applicationContext.getDisplayName() + "]: using ResourceBundleThemeSource");
                themeSource = new ResourceBundleThemeSource();
            }
            return themeSource;
        }
  21. 執行AbstractApplicationContext的refreshListeners方法,尋找所有ApplicationListener bean,將其放到ApplicationEventMulticaster對象的Set集合中
        private void refreshListeners() {
            logger.info("Refreshing listeners");
            List listeners = BeanFactoryUtils.beansOfType(ApplicationListener.class, this);
            logger.debug("Found " + listeners.size() + " listeners in bean factory");
            for (int i = 0; i < listeners.size(); i++) {
                ApplicationListener listener = (ApplicationListener) listeners.get(i);
                addListener(listener);
                logger.info("Bean listener added: [" + listener + "]");
            }
        }
  22. 執行AbstractApplicationContext的preInstantiateSingletons方法,創建單例的bean實例,創建bean對象是在調用getBean方法時創建的,具體創建邏輯在getSharedInstance方法里;另外,對實現了ApplicationContextAware介面的bean,會調用對應的介面setApplicationContext方法,這裡涉及的細節比較多,後續有時間可以具體詳細分析;
        private void preInstantiateSingletons() {
            logger.info("Configuring singleton beans in context");
            String[] beanNames = getBeanDefinitionNames();
            logger.debug("Found " + beanNames.length + " listeners in bean factory: names=[" +
                    StringUtils.arrayToDelimitedString(beanNames, ",") + "]");
            for (int i = 0; i < beanNames.length; i++) {
                String beanName = beanNames[i];
                if (isSingleton(beanName)) {
                    getBean(beanName);
                }
            }
        }
        public Object getBean(String name) throws BeansException {
            Object bean = getBeanFactory().getBean(name);
            configureManagedObject(name, bean);
            return bean;
        }
        private final synchronized Object getSharedInstance(String pname, Map newlyCreatedBeans) throws BeansException {
            // Get rid of the dereference prefix if there is one
            String name = transformedBeanName(pname);
    
            Object beanInstance = this.singletonCache.get(name);
            if (beanInstance == null) {
                logger.info("Creating shared instance of singleton bean '" + name + "'");
                beanInstance = createBean(name, newlyCreatedBeans);
                this.singletonCache.put(name, beanInstance);
            } else {
                if (logger.isDebugEnabled())
                    logger.debug("Returning cached instance of singleton bean '" + name + "'");
            }
    
            // Don't let calling code try to dereference the
            // bean factory if the bean isn't a factory
            if (isFactoryDereference(pname) && !(beanInstance instanceof FactoryBean)) {
                throw new BeanIsNotAFactoryException(name, beanInstance);
            }
    
            // Now we have the beanInstance, which may be a normal bean
            // or a FactoryBean. If it's a FactoryBean, we use it to
            // create a bean instance, unless the caller actually wants
            // a reference to the factory.
            if (beanInstance instanceof FactoryBean) {
                if (!isFactoryDereference(pname)) {
                    // Configure and return new bean instance from factory
                    FactoryBean factory = (FactoryBean) beanInstance;
                    logger.debug("Bean with name '" + name + "' is a factory bean");
                    beanInstance = factory.getObject();
    
                    // Set pass-through properties
                    if (factory.getPropertyValues() != null) {
                        logger.debug("Applying pass-through properties to bean with name '" + name + "'");
                        new BeanWrapperImpl(beanInstance).setPropertyValues(factory.getPropertyValues());
                    }
                    // Initialization is really up to factory
                    //invokeInitializerIfNecessary(beanInstance);
                } else {
                    // The user wants the factory itself
                    logger.debug("Calling code asked for BeanFactory instance for name '" + name + "'");
                }
            }    // if we're dealing with a factory bean
    
            return beanInstance;
        }
        private void configureManagedObject(String name, Object bean) {
            if (bean instanceof ApplicationContextAware &&
                    (!isSingleton(name) || !this.managedSingletons.contains(bean))) {
                logger.debug("Setting application context on ApplicationContextAware object [" + bean + "]");
                ApplicationContextAware aca = (ApplicationContextAware) bean;
                aca.setApplicationContext(this);
                this.managedSingletons.add(bean);
            }
        }
  23. 執行AbstractApplicationContext的publishEvent方法,發佈ContextRefreshedEvent事件,如果parent不為空,一起發佈,內部的邏輯是執行對應eventListeners的onApplicationEvent方法
        public final void publishEvent(ApplicationEvent event) {
            if (logger.isDebugEnabled()) {
                logger.debug("Publishing event in context [" + getDisplayName() + "]: " + event.toString());
            }
            this.eventMulticaster.onApplicationEvent(event);
            if (this.parent != null) {
                parent.publishEvent(event);
            }
        }
  24. 回到XmlWebApplicationContext類
  25. 執行WebApplicationContextUtils.publishConfigObjects方法,尋找所有config bean,將其設置到ServletContext的屬性中
        public static void publishConfigObjects(WebApplicationContext wac) throws ApplicationContextException {
            logger.info("Configuring config objects");
            String[] beanNames = wac.getBeanDefinitionNames();
            for (int i = 0; i < beanNames.length; i++) {
                String name = beanNames[i];
                if (name.startsWith(CONFIG_OBJECT_PREFIX)) {
                    // Strip prefix
                    String strippedName = name.substring(CONFIG_OBJECT_PREFIX.length());
                    try {
                        Object configObject = wac.getBean(name);
                        wac.getServletContext().setAttribute(strippedName, configObject);
                        logger.info("Config object with name [" + name + "] and class [" + configObject.getClass().getName() +
                                "] initialized and added to ServletConfig");
                    } catch (BeansException ex) {
                        throw new ApplicationContextException("Couldn't load config object with name '" + name + "': " + ex, ex);
                    }
                }
            }
        }
  26. 執行WebApplicationContextUtils.publishWebApplicationContext,將WebApplicationContext設置到ServletContext屬性中
        public static void publishWebApplicationContext(WebApplicationContext wac) {
            // Set WebApplicationContext as an attribute in the ServletContext so
            // other components in this web application can access it
            ServletContext sc = wac.getServletContext();
            if (sc == null)
                throw new IllegalArgumentException("ServletContext can't be null in WebApplicationContext " + wac);
    
            sc.setAttribute(WebApplicationContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE_NAME, wac);
            logger.info(
                    "Loader initialized on server name "
                            + wac.getServletContext().getServerInfo()
                            + "; WebApplicationContext object is available in ServletContext with name '"
                            + WebApplicationContext.WEB_APPLICATION_CONTEXT_ATTRIBUTE_NAME
                            + "'");
        }
  27. 返回webApplicationContext到ContextLoader類
  28. ContextLoaderListener.contextInitialized方法執行結束

 

就這樣,Spring Web Application Context載入完成了,是不是感覺也挺簡單的,主要就是讀取xml配置文件中bean的配置信息,創建bean實例放到一個map中維護,當然,中間還穿插了各種邏輯;

另外補充下,當Servlet容器銷毀時,會調用ContextLoaderListener的contextDestroyed方法,最終是調用ContextLoader.closeContext(event.getServletContext(),執行一些資源銷毀等操作,銷毀工廠創建的bean對象,發佈ContextClosedEvent事件等;

  public void close() {
        logger.info("Closing application context [" + getDisplayName() + "]");

        // destroy all cached singletons in this context,
        // invoking DisposableBean.destroy and/or "destroy-method"
        getBeanFactory().destroySingletons();

        // publish respective event
        publishEvent(new ContextClosedEvent(this));
    }

interface21代碼參考

 https://github.com/peterchenhdu/interface21


您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 1. jdk,jre,jvm之間的關係 是`Java Java JVM Java JVM`。 可以說 語言是跨平臺的,但 不是。 是`Java JVM`+核心類庫。 是`Java JRE`。 2. Java的分類 JAVASE、JAVAEE、JAVAME 為標準版, 為企業版, 為微型版 3. Ja ...
  • 目錄: 一、一些相關的BIF 二、、課時40課後習題及答案 ********************** 一、一些相關的BIF ********************** 1、issubclass(class,classinfo) 如果第一個參數(class)是第二個參數(classinfo)的一 ...
  • QFileSystemModel繼承自QAbstractItemModel類,作為子類,需要實現一些成員函數。面向對象編程中,如何劃分父類和子類的職責需要仔細權衡。拿flags函數的設計來說,目的是讓model能獲取肚子里的某一個node的信息。如果把它放在父類中,會出現什麼問題呢?問題是,無法針對 ...
  • 請編寫一個函數,使其可以刪除某個鏈表中給定的(非末尾)節點,你將只被給定要求被刪除的節點。 現有一個鏈表 -- head = [4,5,1,9],它可以表示為: 4 -> 5 -> 1 -> 9 示例 1: 輸入: head = [4,5,1,9], node = 5 輸出: [4,1,9] 解釋: ...
  • 給定一個二叉搜索樹, 找到該樹中兩個指定節點的最近公共祖先。 百度百科中最近公共祖先的定義為:“對於有根樹 T 的兩個結點 p、q,最近公共祖先表示為一個結點 x,滿足 x 是 p、q 的祖先且 x 的深度儘可能大(一個節點也可以是它自己的祖先)。” 例如,給定如下二叉搜索樹: root = [6, ...
  • 請判斷一個鏈表是否為迴文鏈表。 示例 1: 輸入: 1->2 輸出: false 示例 2: 輸入: 1->2->2->1 輸出: true 進階: 你能否用 O(n) 時間複雜度和 O(1) 空間複雜度解決此題? # Definition for singly-linked list. # cla ...
  • 給定一個整數n,判斷它是否為2的次方冪。 方法:2,4,8都是2的n次冪 任何整數乘以2,都相當於向左移動了一位,而2的0次冪為1,所以2的n次冪就是1向左移動n位。這樣,2的冪的特征就是二進位表示只有最高位為1,其他位均為0。二進位標下形式為: 10 100 1000 減1後與自身進行按位與,如果 ...
  • python2.x版本的字元編碼有時讓人很頭疼,遇到問題,網上方法可以解決錯誤,但對原理還是一知半解,本文主要介紹 python 中字元串處理的原理,附帶解決 json 文件輸出時,顯示中文而非 unicode 問題。首先簡要介紹字元串編碼的歷史,其次,講解 python 對於字元串的處理,及編碼的 ...
一周排行
    -Advertisement-
    Play Games
  • 移動開發(一):使用.NET MAUI開發第一個安卓APP 對於工作多年的C#程式員來說,近來想嘗試開發一款安卓APP,考慮了很久最終選擇使用.NET MAUI這個微軟官方的框架來嘗試體驗開發安卓APP,畢竟是使用Visual Studio開發工具,使用起來也比較的順手,結合微軟官方的教程進行了安卓 ...
  • 前言 QuestPDF 是一個開源 .NET 庫,用於生成 PDF 文檔。使用了C# Fluent API方式可簡化開發、減少錯誤並提高工作效率。利用它可以輕鬆生成 PDF 報告、發票、導出文件等。 項目介紹 QuestPDF 是一個革命性的開源 .NET 庫,它徹底改變了我們生成 PDF 文檔的方 ...
  • 項目地址 項目後端地址: https://github.com/ZyPLJ/ZYTteeHole 項目前端頁面地址: ZyPLJ/TreeHoleVue (github.com) https://github.com/ZyPLJ/TreeHoleVue 目前項目測試訪問地址: http://tree ...
  • 話不多說,直接開乾 一.下載 1.官方鏈接下載: https://www.microsoft.com/zh-cn/sql-server/sql-server-downloads 2.在下載目錄中找到下麵這個小的安裝包 SQL2022-SSEI-Dev.exe,運行開始下載SQL server; 二. ...
  • 前言 隨著物聯網(IoT)技術的迅猛發展,MQTT(消息隊列遙測傳輸)協議憑藉其輕量級和高效性,已成為眾多物聯網應用的首選通信標準。 MQTTnet 作為一個高性能的 .NET 開源庫,為 .NET 平臺上的 MQTT 客戶端與伺服器開發提供了強大的支持。 本文將全面介紹 MQTTnet 的核心功能 ...
  • Serilog支持多種接收器用於日誌存儲,增強器用於添加屬性,LogContext管理動態屬性,支持多種輸出格式包括純文本、JSON及ExpressionTemplate。還提供了自定義格式化選項,適用於不同需求。 ...
  • 目錄簡介獲取 HTML 文檔解析 HTML 文檔測試參考文章 簡介 動態內容網站使用 JavaScript 腳本動態檢索和渲染數據,爬取信息時需要模擬瀏覽器行為,否則獲取到的源碼基本是空的。 本文使用的爬取步驟如下: 使用 Selenium 獲取渲染後的 HTML 文檔 使用 HtmlAgility ...
  • 1.前言 什麼是熱更新 游戲或者軟體更新時,無需重新下載客戶端進行安裝,而是在應用程式啟動的情況下,在內部進行資源或者代碼更新 Unity目前常用熱更新解決方案 HybridCLR,Xlua,ILRuntime等 Unity目前常用資源管理解決方案 AssetBundles,Addressable, ...
  • 本文章主要是在C# ASP.NET Core Web API框架實現向手機發送驗證碼簡訊功能。這裡我選擇是一個互億無線簡訊驗證碼平臺,其實像阿裡雲,騰訊雲上面也可以。 首先我們先去 互億無線 https://www.ihuyi.com/api/sms.html 去註冊一個賬號 註冊完成賬號後,它會送 ...
  • 通過以下方式可以高效,並保證數據同步的可靠性 1.API設計 使用RESTful設計,確保API端點明確,並使用適當的HTTP方法(如POST用於創建,PUT用於更新)。 設計清晰的請求和響應模型,以確保客戶端能夠理解預期格式。 2.數據驗證 在伺服器端進行嚴格的數據驗證,確保接收到的數據符合預期格 ...