JSP九大内置对象详解全析(四):application对象

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文件中配置初始化参数:


<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>             
        <param-name>urlparam-name>
        <param-value>jdbc:mysql://localhost:3306/db_database15param-value>
    context-param>
    <context-param>         
        <param-name>nameparam-name>
        <param-value>rootparam-value>
    context-param>
    <context-param>         
        <param-name>passwordparam-name>
        <param-value>111param-value>
    context-param>
  <welcome-file-list>
    <welcome-file>index.jspwelcome-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+"/";
%>


<html>
  <head>
    <base href="<%=basePath%>">

    <title>My JSP 'index.jsp' starting pagetitle>
    <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">
    
  head>

  <body>
<%

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

你可能感兴趣的:(Servlet)