<context-param>的配置作用

本文详细解析了web.xml中<context-param>配置的作用,阐述了其如何在项目启动时被容器读取,并转化为键值对存储在ServletContext中,供监听器在初始化阶段使用,以实现如数据库连接等早期操作。

web.xml的配置中<context-param>配置作用

  1. 启动一个WEB项目的时候,容器(如:Tomcat)会去读它的配置文件web.xml.读两个节点: <listener></listener> 和 <context-param></context-param>
  2. 紧接着,容器创建一个ServletContext(上下文),这个WEB项目所有部分都将共享这个上下文.
  3. 容器将<context-param></context-param>转化为键值对,并交给ServletContext.
  4. 容器创建<listener></listener>中的类实例,即创建监听.
  5. 在监听中会有contextInitialized(ServletContextEvent args)初始化方法,在这个方法中获得ServletContext = ServletContextEvent.getServletContext();
    context-param的值 = ServletContext.getInitParameter(“context-param的键”);
  6. 得到这个context-param的值之后,你就可以做一些操作了.注意,这个时候你的WEB项目还没有完全启动完成.这个动作会比所有的Servlet都要早.
    换句话说,这个时候,你对<context-param>中的键值做的操作,将在你的WEB项目完全启动之前被执行.
  7. 举例.你可能想在项目启动之前就打开数据库.
    那么这里就可以在<context-param>中设置数据库的连接方式,在监听类中初始化数据库的连接.
  8. 这个监听是自己写的一个类,除了初始化方法,它还有销毁方法.用于关闭应用前释放资源.比如说数据库连接的关闭.
    如:
    web.xml配置文件:
&lt;!-- 加载spring的配置文件 -->
&lt;context-param>
    &lt;param-name>contextConfigLocation&lt;/param-name>
    &lt;param-value>/WEB-INF/applicationContext.xml,/WEB-INF/action-servlet.xml,/WEB-
INF/jason-servlet.xml&lt;/param-value>
&lt;/context-param>
&lt;listener>
    &lt;listener-class>org.springframework.web.context.ContextLoaderListener&lt;/listener-class>
&lt;/listener>
又如: --->自定义context-param,且自定义listener来获取这些信息
&lt;context-param>
    &lt;param-name>urlrewrite&lt;/param-name>
    &lt;param-value>false&lt;/param-value>
&lt;/context-param>
&lt;context-param>
    &lt;param-name>cluster&lt;/param-name>
    &lt;param-value>false&lt;/param-value>
&lt;/context-param>
&lt;context-param>
    &lt;param-name>servletmapping&lt;/param-name>
    &lt;param-value>*.bbscs&lt;/param-value>
&lt;/context-param>
&lt;context-param>
    &lt;param-name>poststoragemode&lt;/param-name>
    &lt;param-value>1&lt;/param-value>
&lt;/context-param>
&lt;listener>
    &lt;listener-class>com.laoer.bbscs.web.servlet.SysListener&lt;/listener-class>
&lt;/listener>

代码片段:

public class SysListener extends HttpServlet implements ServletContextListener {
private static final Log logger = LogFactory.getLog(SysListener.class);
public void contextDestroyed(ServletContextEvent sce) {
   //用于在容器关闭时,操作
}
//用于在容器开启时,操作
public void contextInitialized(ServletContextEvent sce) {
   String rootpath = sce.getServletContext().getRealPath("/");
   System.out.println("-------------rootPath:"+rootpath);
   if (rootpath != null) {
    rootpath = rootpath.replaceAll("\\\\", "/");
   } else {
    rootpath = "/";
   }
   if (!rootpath.endsWith("/")) {
    rootpath = rootpath + "/";
   }
   Constant.ROOTPATH = rootpath;
   logger.info("Application Run Path:" + rootpath);
   String urlrewrtie = sce.getServletContext().getInitParameter("urlrewrite");
   boolean burlrewrtie = false;
   if (urlrewrtie != null) {
    burlrewrtie = Boolean.parseBoolean(urlrewrtie);
   }
   Constant.USE_URL_REWRITE = burlrewrtie;
   logger.info("Use Urlrewrite:" + burlrewrtie);
   其它略之....
   }
}

打印结果:

  /*最终输出
   -------------rootPath:D:\tomcat_bbs\webapps\BBSCS_8_0_3\
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Application Run Path:D:/tomcat_bbs/webapps/BBSCS_8_0_3/
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Use Urlrewrite:true
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Use Cluster:false
   2009-06-09 21:51:46,526 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
SERVLET MAPPING:*.bbscs
   2009-06-09 21:51:46,573 [com.laoer.bbscs.web.servlet.SysListener]-[INFO]
Post Storage Mode:1
   */

context-param和init-param区别
web.xml里面可以定义两种参数:

  1. application范围内的参数,存放在servletcontext中,在web.xml中配置如下:
&lt;context-param>
           &lt;param-name>context/param&lt;/param-name>
           &lt;param-value>avalible during application&lt;/param-value>
&lt;/context-param>
  1. servlet范围内的参数,只能在servlet的init()方法中取得,在web.xml中配置如下:
&lt;servlet>
    &lt;servlet-name>MainServlet&lt;/servlet-name>
    &lt;servlet-class>com.wes.controller.MainServlet&lt;/servlet-class>
    &lt;init-param>
       &lt;param-name>param1&lt;/param-name>
       &lt;param-value>avalible in servlet init()&lt;/param-value>
    &lt;/init-param>
    &lt;load-on-startup>0&lt;/load-on-startup>
&lt;/servlet>

在servlet中可以通过代码分别取用:

package com.wes.controller;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
public class MainServlet extends HttpServlet ...{
    public MainServlet() ...{
        super();
     }
    public void init() throws ServletException ...{
         System.out.println("下面的两个参数param1是在servlet中存放的");
         System.out.println(this.getInitParameter("param1"));
         System.out.println("下面的参数是存放在servletcontext中的");
        System.out.println(getServletContext().getInitParameter("context/param"));
      }
}

第一种参数在servlet里面可以通过getServletContext().getInitParameter(“context/param”)得到
第二种参数只能在servlet的init()方法中通过this.getInitParameter(“param1”)取得.

&lt;?xml version="1.0" encoding="UTF-8"?> &lt;web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd" version="4.0"> &lt;display-name>AirlineBooking&lt;/display-name> &lt;welcome-file-list> &lt;welcome-file>index.jsp&lt;/welcome-file> &lt;/welcome-file-list> &lt;!-- 配置JSTL --> &lt;jsp-config> &lt;taglib> &lt;taglib-uri>http://java.sun.com/jsp/jstl/core&lt;/taglib-uri> &lt;taglib-location>/WEB-INF/lib/jstl-1.2.jar&lt;/taglib-location> &lt;/taglib> &lt;/jsp-config> &lt;filter> &lt;filter-name>AuthFilter&lt;/filter-name> &lt;filter-class>com.airline.filter.AuthFilter&lt;/filter-class> &lt;/filter> &lt;filter-mapping> &lt;filter-name>AuthFilter&lt;/filter-name> &lt;url-pattern>/booking/*&lt;/url-pattern> &lt;/filter-mapping> &lt;filter-mapping> &lt;filter-name>AuthFilter&lt;/filter-name> &lt;url-pattern>/user/*&lt;/url-pattern> &lt;/filter-mapping> &lt;!-- &lt;!– 应用显示名称 –>--> &lt;!-- &lt;display-name>OnlineShop&lt;/display-name>--> &lt;!-- &lt;!– 欢迎文件列表 –>--> &lt;!-- &lt;welcome-file-list>--> &lt;!-- &lt;welcome-file>index.jsp&lt;/welcome-file>--> &lt;!-- &lt;/welcome-file-list>--> &lt;!-- &lt;!– 会话超时配置(单位:分钟) –>--> &lt;!-- &lt;session-config>--> &lt;!-- &lt;session-timeout>30&lt;/session-timeout>--> &lt;!-- &lt;/session-config>--> &lt;!-- &lt;!– Servlet 配置 –>--> &lt;!-- &lt;servlet>--> &lt;!-- &lt;servlet-name>LoginServlet&lt;/servlet-name>--> &lt;!-- &lt;servlet-class>com.onlineshop.servlet.LoginServlet&lt;/servlet-class>--> &lt;!-- &lt;/servlet>--> &lt;!-- &lt;servlet>--> &lt;!-- &lt;servlet-name>RegisterServlet&lt;/servlet-name>--> &lt;!-- &lt;servlet-class>com.example.onlineshop.servlet.RegisterServlet&lt;/servlet-class>--> &lt;!-- &lt;/servlet>--> &lt;!-- &lt;!– Servlet 映射 –>--> &lt;!-- &lt;servlet-mapping>--> &lt;!-- &lt;servlet-name>LoginServlet&lt;/servlet-name>--> &lt;!-- &lt;url-pattern>/login_process.jsp&lt;/url-pattern>--> &lt;!-- &lt;/servlet-mapping>--> &lt;!-- &lt;servlet-mapping>--> &lt;!-- &lt;servlet-name>RegisterServlet&lt;/servlet-name>--> &lt;!-- &lt;url-pattern>/register_process.jsp&lt;/url-pattern>--> &lt;!-- &lt;/servlet-mapping>--> &lt;!-- &lt;!– 错误页面配置 –>--> &lt;!--&lt;!– &lt;error-page>–>--> &lt;!--&lt;!– &lt;error-code>404&lt;/error-code>–>--> &lt;!--&lt;!– &lt;location>/error/404.jsp&lt;/location>–>--> &lt;!--&lt;!– &lt;/error-page>–>--> &lt;!--&lt;!– &lt;error-page>–>--> &lt;!--&lt;!– &lt;error-code>500&lt;/error-code>–>--> &lt;!--&lt;!– &lt;location>/error/500.jsp&lt;/location>–>--> &lt;!--&lt;!– &lt;/error-page>–>--> &lt;!-- &lt;!– 上下文参数 –>--> &lt;!-- &lt;context-param>--> &lt;!-- &lt;param-name>jdbcDriver&lt;/param-name>--> &lt;!-- &lt;param-value>com.mysql.jdbc.Driver&lt;/param-value>--> &lt;!-- &lt;/context-param>--> &lt;!-- &lt;context-param>--> &lt;!-- &lt;param-name>jdbcUrl&lt;/param-name>--> &lt;!-- &lt;param-value>jdbc:mysql://localhost:3306/onlineshop&lt;/param-value>--> &lt;!-- &lt;/context-param>--> &lt;!-- &lt;!– 过滤器配置(可选) –>--> &lt;!--&lt;!– &lt;filter>–>--> &lt;!--&lt;!– &lt;filter-name>CharacterEncodingFilter&lt;/filter-name>–>--> &lt;!--&lt;!– &lt;filter-class>com.example.onlineshop.filter.CharacterEncodingFilter&lt;/filter-class>–>--> &lt;!--&lt;!– &lt;init-param>–>--> &lt;!--&lt;!– &lt;param-name>encoding&lt;/param-name>–>--> &lt;!--&lt;!– &lt;param-value>UTF-8&lt;/param-value>–>--> &lt;!--&lt;!– &lt;/init-param>–>--> &lt;!--&lt;!– &lt;/filter>–>--> &lt;!--&lt;!– &lt;filter-mapping>–>--> &lt;!--&lt;!– &lt;filter-name>CharacterEncodingFilter&lt;/filter-name>–>--> &lt;!--&lt;!– &lt;url-pattern>/*&lt;/url-pattern>–>--> &lt;!--&lt;!– &lt;/filter-mapping>–>--> &lt;/web-app>我这个配置有问题吗
06-16
PS C:\Users\Administrator> # 修正前(错误) >> } elseif (Get-Command dnf -极乐净土ErrorAction SilentlyContinue) { >> >> # 修正后 >> } elseif (Get-Command dnf -ErrorAction SilentlyContinue) { >> >> # 更新 Windows 下载 URL >> $curlUrl = "https://curl.se/windows/dl-8.8.0_5/curl-8.8.0_5-win64-mingw.zip" >> >> # 添加备用镜像源 >> $mirrorUrl = "https://curl.askapache.com/win64-mingw/curl-8.8.0_5-win64-mingw.zip" >> >> # 安装脚本中创建完整结构 >> $moduleDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" >> New-Item -Path "$moduleDir\Private" -ItemType Directory -Force | Out-Null >> New-Item -Path "$moduleDir\Public" -ItemType Directory -Force | Out-Null >> >> $moduleRoot = $PSScriptRoot >> >> # 检测是否在模块上下文中 >> if (-not $moduleRoot) { >> $moduleRoot = Split-Path -Parent $MyInvocation.MyCommand.Path >> } >> >> # 安全导入函数 >> if (Test-Path "$moduleRoot\Private") { >> Get-ChildItem -Path "$moduleRoot\Private\*.ps1" | ForEach-Object { >> . $_.FullName >> } >> } >> >> if (Test-Path "$moduleRoot\Public") { >> $publicFunctions = Get-ChildItem -Path "$moduleRoot\Public\*.ps1" >> foreach ($file in $publicFunctions) { >> . $_.FullName >> } >> } >> >> # 延迟导出(确保在模块上下文中) >> $exportFunctions = @( >> 'Get-CurlPath', >> 'Set-CurlPath', >> 'Get-CurlVersion', >> 'Invoke-SecureDownload' >> ) >> >> if ($ExecutionContext.SessionState.Module) { >> Export-ModuleMember -Function $exportFunctions >> } >> >> function Invoke-SecureDownload { >> param( >> [Parameter(Mandatory=$true)] >> [string]$Url, >> [Parameter(Mandatory=$true)] >> [string]$OutputPath, >> [string[]]$MirrorUrls = @(), >> [string]$ExpectedHash, >> [string]$HashAlgorithm = "SHA256" >> ) >> >> # 尝试多个镜像源 >> $urlList = @($Url) + $MirrorUrls >> $success = $false >> >> foreach ($currentUrl in $urlList) { >> try { >> # ... 下载逻辑 ... >> $success = $true >> break >> } >> catch { >> Write-Warning "下载失败 ($currentUrl): $_" >> } >> } >> >> if (-not $success) { >> throw "所有镜像源下载失败" >> } >> } >> >> # 创建模块目录结构 >> $moduleDir = "$env:USERPROFILE\Documents\WindowsPowerShell\Modules\CurlTools" >> New-Item -Path $moduleDir -ItemType Directory -Force | Out-Null >> New-Item -Path "$moduleDir\Private" -ItemType Directory -Force | Out-Null >> New-Item -Path "$moduleDir\Public" -ItemType Directory -Force | Out-Null >> >> # ===== 保存模块主文件 ===== >> @' >> # CurlTools.psm1 >> $moduleRoot = $PSScriptRoot >> if (-not $moduleRoot) { >> $moduleRoot = Split-Path -Parent $MyInvocation.MyCommand.Path >> } >> >> # 导入私有函数 >> if (Test-Path "$moduleRoot\Private") { >> Get-ChildItem -Path "$moduleRoot\Private\*.ps1" | ForEach-Object { >> . $_.FullName >> } >> } >> >> # 导入公共函数 >> if (Test-Path "$moduleRoot\Public") { >> $publicFiles = Get-ChildItem -Path "$moduleRoot\Public\*.ps1" >> foreach ($file in $publicFiles) { >> . $file.FullName >> } >> } >> >> # 延迟导出函数 >> if ($ExecutionContext.SessionState.Module) { >> Export-ModuleMember -Function @( >> 'Get-CurlPath', >> 'Set-CurlPath', >> 'Get-CurlVersion', >> 'Invoke-SecureDownload' >> ) >> } >> >> # 初始化模块 >> Initialize-Module | Out-Null >> '@ | Set-Content -Path "$moduleDir\CurlTools.psm1" -Force >> >> # ===== 保存私有函数 ===== >> # Private/InstallCurl.ps1 >> @' >> function Install-Curl { >> $platform = Get-Platform >> try { >> if ($platform -eq "Windows") { >> $tempDir = [System.IO.Path]::GetTempPath() >> $curlZip = Join-Path $tempDir "curl.zip" >> >> # 使用主镜像+备用镜像 >> $mirrors = @( >> "https://curl.se/windows/dl-8.8.0_5/curl-8.8.0_5-win64-mingw.zip", >> "https://curl.askapache.com/win64-mingw/curl-8.8.0_5-win64-mingw.zip" >> ) >> >> Invoke-SecureDownload -Url $mirrors[0] -OutputPath $curlZip -MirrorUrls $mirrors[1..($mirrors.Count-1)] >> >> Expand-Archive $curlZip -DestinationPath $tempDir -Force >> $installDir = Join-Path $tempDir "curl-8.8.0_5-win64-mingw\bin" >> return $installDir >> } >> else { >> # ... Linux/macOS 安装逻辑 ... >> } >> } >> catch { >> throw "无法自动安装curl: $_" >> } >> } >> '@ | Set-Content -Path "$moduleDir\Private\InstallCurl.ps1" -Force >> >> # ===== 保存公共函数 ===== >> # Public/GetCurlPath.ps1 >> @' >> function Get-CurlPath { >> Ensure-ModuleInitialized >> return $script:CurlPath >> } >> '@ | Set-Content -Path "$moduleDir\Public\GetCurlPath.ps1" -Force >> >> # ... 其他公共函数类似处理 ... >> >> # ===== 创建模块清单 ===== >> $manifest = @{ >> ModuleVersion = '2.1.0' >> RootModule = 'CurlTools.psm1' >> FunctionsToExport = @( >> 'Get-CurlPath', >> 'Set-CurlPath', >> 'Get-CurlVersion', >> 'Invoke-SecureDownload' >> ) >> CompatiblePSEditions = @('Desktop', 'Core') >> GUID = 'c0d1b1e1-1a2b-4c3d-8e4f-9a0b1c2d3e4f' >> Author = 'Your Name' >> Description = 'Powerful curl tools for PowerShell' >> } | ConvertTo-Json >> >> Set-Content -Path "$moduleDir\CurlTools.psd1" -Value $manifest -Force >> >> # 重新加载模块 >> Remove-Module CurlTools -ErrorAction SilentlyContinue >> Import-Module $moduleDir -Force -Verbose >> >> # 测试模块 >> if (Get-Module CurlTools) { >> Write-Host "✅ CurlTools 模块安装成功!" -ForegroundColor Green >> >> # 测试下载功能 >> try { >> $testUrl = "https://raw.githubusercontent.com/PowerShell/PowerShell/master/README.md" >> $outputPath = Join-Path $env:TEMP "PowerShell_README.md" >> Invoke-SecureDownload -Url $testUrl -OutputPath $outputPath >> Write-Host "✅ 测试下载成功: $outputPath" -ForegroundColor Green >> } >> catch { >> Write-Warning "⚠️ 下载测试失败: $_" >> } >> } >> else { >> Write-Error "❌ 模块安装失败" >> } >> >>
08-13
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值