http://click.aliyun.com/m/20661/

本文介绍了一种使用Servlet的init方法进行Web应用初始化配置的方法。通过在web.xml中配置InitServlet并在其中实现init方法,可以有效地集中管理Web项目的初始化配置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

摘要: 需求说明 做项目时,为了省事,起初把初始化的配置都放在每个类中 static加载,初始化配置一多,就想把它给整理一下,这里使用servlet中的init方法初始化。 web.xml说明 首先了解下web.

需求说明

做项目时,为了省事,起初把初始化的配置都放在每个类中 static加载,初始化配置一多,就想把它给整理一下,这里使用servlet中的init方法初始化。

web.xml说明

首先了解下web.xml中元素的加载顺序:

  • 启动web项目后,web容器首先回去找web.xml文件,读取这个文件

  • 容器会创建一个 ServletContext ( servlet 上下文),整个 web 项目的所有部分都将共享这个上下文

  • 容器将 转换为键值对,并交给 servletContext

  • 容器创建 中的类实例,创建监听器

  • 容器加载filter,创建过滤器, 要注意对应的filter-mapping一定要放在filter的后面

  • 容器加载servlet,加载顺序按照 Load-on-startup 来执行

完整加载顺序:ServletContext -> context-param -> listener-> filter -> servlet

配置实现

InitServlet.java:

/**
 * 初始化系统参数
 * 创建者 科帮网
 * 创建时间 2017年5月10日
 *
 */
public class InitServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    @Override
    public void init(){
        try {
            if(Constants.PAY_URL.size()==0){
                List<CommonEntity> listPayUrl = PropertiesListUtil.listPayUrl();
                for(CommonEntity entity:listPayUrl){
                    Constants.PAY_URL.put(entity.getEntityCode(), entity.getEntityName());
                }
            }
            LogUtil.info("佛祖保佑       永不宕机     永无BUG :初始化系统数据数量:"+Constants.PAY_URL.size());

            Configs.init("zfbinfo.properties");
            LogUtil.info("初始化支付宝配置信息");

            SDKConfig.getConfig().loadPropertiesFromSrc();
            LogUtil.info("初始化银联支付配置信息");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    /**
     * 重新加载配置文件
     * @Author  科帮网
     * @param request
     * @param response
     * @throws ServletException
     * @throws IOException 
     * @Date    2017年5月10日
     * 更新日志
     * 2017年5月10日 张志朋  首次创建
     *
     */
    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        Constants.PAY_URL = new ConcurrentHashMap<String, String>();
        List<CommonEntity> listPayUrl = PropertiesListUtil.listPayUrl();
        for(CommonEntity entity:listPayUrl){
            Constants.PAY_URL.put(entity.getEntityCode(), entity.getEntityName());
        }
        LogUtil.info("初始化系统数据数量:"+Constants.PAY_URL.size());
    }
    @Override
    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doGet(request, response);
    }
}

web.xml:(部分配置)

<!-- 初始基础化数据-->
    <servlet>
        <servlet-name>InitServlet</servlet-name>
        <servlet-class>com.acts.web.common.servlet.InitServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>InitServlet</servlet-name>
        <url-pattern>/InitServlet</url-pattern>
    </servlet-mapping>

servlet介绍

什么是servlet

servlet是sun公司为开发动态web而提供的一门技术,用户若想用发一个动态web资源(即开发一个Java程序向浏览器输出数据),需要完成以下2个步骤:

  1. 编写一个Java类,实现servlet接口。
  2. 把开发好的Java类部署到web服务器中。

按照一种约定俗成的称呼习惯,通常我们也把实现了servlet接口的java程序,称之为Servlet。

servlet的运行过程

  1. 浏览器发出请求,被web容器获取到
  2. Web服务器首先检查是否已经装载并创建了该Servlet的实例对象。如果是,则直接执行第④步,否则,执行第②步。

  3. 装载并创建该Servlet的一个实例对象,调用Servlet实例对象的init()方法。

  4. 创建一个用于封装HTTP请求消息的HttpServletRequest对象和一个代表HTTP响应消息的HttpServletResponse对象,然后调用Servlet的service()方法并将请求和响应对象作为参数传递进去。

  5. WEB应用程序被停止或重新启动之前,Servlet引擎将卸载Servlet,并在卸载之前调用Servlet的destroy()方法

servlet初始化

  • load-on-startup >=0 时,表示在web应用启动后立即加载,其中load-on-startup的值越小,表示加载的优先级越高,如果两个servlet的load-on-startup值相同,则其加载优先级有容器决定;

  • load-on-startup 未配置时,则该servlet的加载由容器决定;

配置load-on-startup后,servlet在startup后立即加载,但只是调用servlet的init()方法,用以初始化该servlet相关的资源。初始化成功后,该servlet可响应web请求;如未配置load-on-startup,容器一般在第一次响应web请求时,会先检测该servlet是否初始化,如未初始化,则调用servlet的init()先初始化,初始化成功后,再响应请求。

PS:一般我们在开发web应用时,都会配置这个参数,有两个好处:
1. 如果初始化过程失败,则容器会提示启动失败,此时我们能够提前知道相关错误;
2. 配置该参数相当于将初始化servlet的工作转移到容器启动过程,使得容器只要启动成功后,就可立即响应web请求。

关于load-on-startup一些官网说明:

If the value is a negative integer, or the element is not present, the container is free to load the servlet   
whenever it chooses. If the value is a positive  
integer or 0, the container must load and  initialize the servlet as the application is  deployed.   

注意

使用servlet时,一般都是继承httpServlet,然后分别实现doGet或者doPost方法,但是在这里面要注意的是,这servlet并不是线程安全的,多线程单实例执行的,当并发访问同一个资源的话(成员变量等等),就有可能引发线程安全问题。

小站:http://blog.52itstyle.com/

原文链接

 

------------------------------------------------------------ E:\soft\1\Anaconda\Scripts\pip-script.py run on 03/30/25 17:00:01 Downloading/unpacking click Getting page https://mirrors.aliyun.com/pypi/simple/click URLs to search for versions for click: * https://mirrors.aliyun.com/pypi/simple/click/ Analyzing links from page https://mirrors.aliyun.com/pypi/simple/click/ Skipping link https://mirrors.aliyun.com/pypi/packages/fa/37/45185cb5abbc30d7257104c434fe0b07e5a195a6847506c074527aa599ec/Click-7.0-py2.py3-none-any.whl#sha256=2335065e6395b9e67ca716de5f7526736bfa6ceead690adf616d925bdc622b13 (from https://mirrors.aliyun.com/pypi/simple/click/); unknown archive format: .whl Found link https://mirrors.aliyun.com/pypi/packages/f8/5c/f60e9d8a1e77005f664b76ff8aeaee5bc05d0a91798afd7f53fc998dbc47/Click-7.0.tar.gz#sha256=5b94b49521f6456670fdb30cd82a4eca9412788a93fa6dd6df72c94d5a8ff2d7 (from https://mirrors.aliyun.com/pypi/simple/click/), version: 7.0 Skipping link https://mirrors.aliyun.com/pypi/packages/82/e9/39bc04e46ac4dc16f60d3c95d2a8238f8a86a738ecab723755470e1486d1/click-0.1-py2.py3-none-any.whl#sha256=6ece7fdc438597979abb5e237cd42ec9b0ed9342acfa13aabd0d57dae5122f00 (from https://mirrors.aliyun.com/pypi/simple/click/); unknown archive format: .whl Found link https://mirrors.aliyun.com/pypi/packages/1a/65/bde2803d3f5d217fde361f7773d51d5c9b1332181f740bdd7adb2462607c/click-0.1.tar.gz#sha256=9f8290d502cf11fad5ccc64d19f2724abcbc11549e6a8e2cdafc530109f198b4 (from https://mirrors.aliyun.com/pypi/simple/click/), version: 0.1 Skipping link https://mirrors.aliyun.com/pypi/packages/ee/a5/97f43386352a0658f12842848c152479fce3162251c08339866da45e912e/click-0.2-py2.py3-none-any.whl#sha256=54c90326cb37daf23389b909fa593660db74d68861cbc36d871d8c7ccc2fe003 (from https://mirrors.aliyun.com/pypi/simple/click/); unknown archive format: .whl Found link https://mirrors.aliyun.com/pypi/packages/bb/aa/c8b583d8d7cc5e21c8da30de6d8c605652836b4ef33b2b57c37f6a017c09/cl
03-31
Looking in indexes: https://mirrors.aliyun.com/pypi/simple/ Collecting certifi==2019.3.9 (from -r requirements.txt (line 1)) Using cached https://mirrors.aliyun.com/pypi/packages/60/75/f692a584e85b7eaba0e03827b3d51f45f571c2e793dd731e598828d380aa/certifi-2019.3.9-py2.py3-none-any.whl (158 kB) Collecting chardet==3.0.4 (from -r requirements.txt (line 2)) Using cached https://mirrors.aliyun.com/pypi/packages/bc/a9/01ffebfb562e4274b6487b4bb1ddec7ca55ec7510b22e4c51f14098443b8/chardet-3.0.4-py2.py3-none-any.whl (133 kB) Collecting click==6.7 (from -r requirements.txt (line 3)) Using cached https://mirrors.aliyun.com/pypi/packages/34/c1/8806f99713ddb993c5366c362b2f908f18269f8d792aff1abfd700775a77/click-6.7-py2.py3-none-any.whl (71 kB) Collecting Flask==1.0.2 (from -r requirements.txt (line 4)) Using cached https://mirrors.aliyun.com/pypi/packages/7f/e7/08578774ed4536d3242b14dacb4696386634607af824ea997202cd0edb4b/Flask-1.0.2-py2.py3-none-any.whl (91 kB) Collecting Flask-WTF==0.14.2 (from -r requirements.txt (line 5)) Using cached https://mirrors.aliyun.com/pypi/packages/60/3a/58c629472d10539ae5167dc7c1fecfa95dd7d0b7864623931e3776438a24/Flask_WTF-0.14.2-py2.py3-none-any.whl (14 kB) Collecting idna==2.8 (from -r requirements.txt (line 6)) Using cached https://mirrors.aliyun.com/pypi/packages/14/2c/cd551d81dbe15200be1cf41cd03869a46fe7226e7450af7a6545bfc474c9/idna-2.8-py2.py3-none-any.whl (58 kB) Collecting itsdangerous==0.24 (from -r requirements.txt (line 7)) Using cached https://mirrors.aliyun.com/pypi/packages/dc/b4/a60bcdba945c00f6d608d8975131ab3f25b22f2bcfe1dab221165194b2d4/itsdangerous-0.24.tar.gz (46 kB) Preparing metadata (setup.py) ... done Collecting Jinja2==2.10 (from -r requirements.txt (line 8)) Using cached https://mirrors.aliyun.com/pypi/packages/7f/ff/ae64bacdfc95f27a016a7bed8e8686763ba4d277a78ca76f32659220a731/Jinja2-2.10-py2.py3-none-any.whl (126 kB) Requirement already satisfied: setuptools in c:\programdata\anaconda3\envs\3112\lib\site-packages (from -r requirements.txt (line 9)) (78.1.1) Collecting MarkupSafe (from -r requirements.txt (line 10)) Using cached https://mirrors.aliyun.com/pypi/packages/da/b8/3a3bd761922d416f3dc5d00bfbed11f66b1ab89a0c2b6e887240a30b0f6b/MarkupSafe-3.0.2-cp311-cp311-win_amd64.whl (15 kB) Collecting numpy==1.15.4 (from -r requirements.txt (line 11)) Using cached https://mirrors.aliyun.com/pypi/packages/2d/80/1809de155bad674b494248bcfca0e49eb4c5d8bee58f26fe7a0dd45029e2/numpy-1.15.4.zip (4.5 MB) Preparing metadata (setup.py) ... done Collecting pandas==0.23.4 (from -r requirements.txt (line 12)) Using cached https://mirrors.aliyun.com/pypi/packages/e9/ad/5e92ba493eff96055a23b0a1323a9a803af71ec859ae3243ced86fcbd0a4/pandas-0.23.4.tar.gz (10.5 MB) Preparing metadata (setup.py) ... error error: subprocess-exited-with-error × python setup.py egg_info did not run successfully. │ exit code: 1 ╰─> [15 lines of output] C:\Users\Administrator\AppData\Local\Temp\pip-install-mwx2ea8w\pandas_33f6702689674a99929697720e4cfb12\setup.py:12: DeprecationWarning: pkg_resources is deprecated as an API. See https://setuptools.pypa.io/en/latest/pkg_resources.html import pkg_resources C:\ProgramData\anaconda3\envs\3112\Lib\site-packages\setuptools\__init__.py:94: _DeprecatedInstaller: setuptools.installer and fetch_build_eggs are deprecated. !! ******************************************************************************** Requirements should be satisfied by a PEP 517 installer. If you are using pip, you can try `pip install --use-pep517`. ******************************************************************************** !! dist.fetch_build_eggs(dist.setup_requires) error in pandas setup command: 'install_requires' must be a string or iterable of strings containing valid project/version requirement specifiers; Expected end or semicolon (after version specifier) pytz >= 2011k ~~~~~~~^ [end of output] note: This error originates from a subprocess, and is likely not a problem with pip. error: metadata-generation-failed × Encountered error while generating package metadata. ╰─> See above for output. note: This is an issue with the package mentioned above, not pip. hint: See above for details.
08-03
non zero exit code 1 Python 3.11.2 pip 22.3.1 from F:\ESP32-1\Espressif\python_env\idf5.5_py3.11_env\Lib\site-packages\pip (python 3.11) WARNING: The following issue occurred while accessing the ESP-IDF version file in the Python environment: [Errno 2] No such file or directory: 'F:\\ESP32-1\\Espressif\\python_env\\idf5.5_py3.11_env\\idf_version.txt'. (Diagnostic information. It can be ignored.) Downloading https://dl.espressif.com/dl/esp-idf/espidf.constraints.v5.5.txt Destination: F:\ESP32-1\Espressif\espidf.constraints.v5.5.txt.tmp 0% 100% Done Looking in indexes: http://mirrors.aliyun.com/pypi/simple/ Requirement already satisfied: pip in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (22.3.1) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. WARNING: There was an error checking the latest version of pip. Looking in indexes: http://mirrors.aliyun.com/pypi/simple/ Requirement already satisfied: setuptools in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (71.0.0) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. WARNING: There was an error checking the latest version of pip. Looking in indexes: http://mirrors.aliyun.com/pypi/simple/, https://dl.espressif.com/pypi Ignoring importlib_metadata: markers 'python_version < "3.8"' don't match your environment Requirement already satisfied: setuptools in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 7)) (71.0.0) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: packaging in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 8)) (25.0) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: click in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 11)) (8.1.8) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: pyserial in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 12)) (3.5) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: cryptography in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 13)) (44.0.3) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: pyparsing in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 14)) (3.2.3) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: pyelftools in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 15)) (0.32) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: idf-component-manager~=2.2 in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 16)) (2.2.2) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. Requirement already satisfied: esp-coredump in f:\esp32-1\espressif\python_env\idf5.5_py3.11_env\lib\site-packages (from -r F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt (line 17)) (1.14.0) WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. ERROR: Cannot install esptool because these package versions have conflicting dependencies. The conflict is caused by: The user requested esptool The user requested (constraint) esptool~=4.10.dev1 To fix this you could try to: 1. loosen the range of package versions you've specified 2. remove package versions to allow pip attempt to solve the dependency conflict ERROR: ResolutionImpossible: for help visit https://pip.pypa.io/en/latest/topics/dependency-resolution/#dealing-with-dependency-conflicts WARNING: The repository located at mirrors.aliyun.com is not a trusted or secure host and is being ignored. If this repository is available via HTTPS we recommend you use HTTPS instead, otherwise you may silence this warning and allow it anyway with '--trusted-host mirrors.aliyun.com'. [notice] A new release of pip available: 22.3.1 -> 23.3.1 [notice] To update, run: F:\ESP32-1\Espressif\python_env\idf5.5_py3.11_env\Scripts\python.exe -m pip install --upgrade pip Upgrading pip... Upgrading setuptools... Installing Python packages Constraint file: F:\ESP32-1\Espressif\espidf.constraints.v5.5.txt Requirement files: - F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\requirements\requirements.core.txt Traceback (most recent call last): File "F:\ESP32-1\Espressif\frameworks\esp-idf-v5.5\tools\idf_tools.py", line 3592, in <module> main(sys.argv[1:]) File "F:\ESP32-1\Espressif\frameworks\esp-idf-v5.5\tools\idf_tools.py", line 3582, in main action_func(args) File "F:\ESP32-1\Espressif\frameworks\esp-idf-v5.5\tools\idf_tools.py", line 2914, in action_install_python_env subprocess.check_call(run_args, stdout=sys.stdout, stderr=sys.stderr, env=env_copy) File "subprocess.py", line 413, in check_call subprocess.CalledProcessError: Command '['F:\\ESP32-1\\Espressif\\python_env\\idf5.5_py3.11_env\\Scripts\\python.exe', '-m', 'pip', 'install', '--no-warn-script-location', '-r', 'F:/ESP32-1/Espressif/frameworks/esp-idf-v5.5/tools\\requirements\\requirements.core.txt', '--upgrade', '--constraint', 'F:\\ESP32-1\\Espressif\\espidf.constraints.v5.5.txt', '--extra-index-url', 'https://dl.espressif.com/pypi']' returned non-zero exit status 1.
最新发布
08-19
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值