1、application对象概述

    application对象作用范围是整个项目,该对象提供了项目环境属性的访问方法。比如在web.xml文件中,提供的初始化参数(< context-parama>标签),连接数据库的URL、用户名、密码。对应javax.servlet.ServletConfig.class对象。application对象常用的方法如下:

方法 返回值 说明
getAttribute(String name) Object 通过关键字返回保存在application对象中的值
getAttributeNames() Enumeration 获得所有application对象使用的属性名
setAttribute(String key,Object obj) void 指定一个名称,将一个对象保存在application
getMajorVersion() int 获得服务器支持的Servlet版本号
getServletInfo() String 获得JSP引擎相关信息
removeAttribute(String name) void 删除application对象中指定名称的属性
getRealPath() String 返回虚拟路径的真实路径
getInitParameter(String name) String 获得指定name的参数值

2、实例示范:

web.xml文件中配置初始化参数:

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" 
    xmlns="http://java.sun.com/xml/ns/j2ee" 
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
    xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee 
    http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <context-param>             <!-- 定义连接数据库URL -->
        <param-name>url</param-name>
        <param-value>jdbc:mysql://localhost:3306/db_database15</param-value>
    </context-param>
    <context-param>         <!-- 定义连接数据库用户名 -->
        <param-name>name</param-name>
        <param-value>root</param-value>
    </context-param>
    <context-param>         <!-- 定义连接数据库mim -->
        <param-name>password</param-name>
        <param-value>111</param-value>
    </context-param>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

在index.jsp页面访问初始化参数:

<%@ page language="java" import="java.util.*" pageEncoding="gbk" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting page</title>
    <meta http-equiv="pragma" content="no-cache">
    <meta http-equiv="cache-control" content="no-cache">
    <meta http-equiv="expires" content="0">    
    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
    <meta http-equiv="description" content="This is my page">
    <!--
    <link rel="stylesheet" type="text/css" href="styles.css">
    -->
  </head>

  <body>
<%

   String url = application.getInitParameter("url");    //获取初始化参数,与web.xml文件中内容对应
   String name = application.getInitParameter("name");
   String password = application.getInitParameter("password");
   out.println("URL: "+url+"<br>");
   out.println("name: "+name+"<br>");
   out.println("password: "+password+"<br>");
%>

  </body>
</html>