JSP具体篇——application

application对象

application对象用于保存全部应用程序中的共同拥有数据。它在server启动时自己主动创建。在server停止时自己主动销毁。

application对象没有被销毁时,全部用户都能够共享该application对象。与session相比,application 对象的生命周期更长,类似于“全局变量”

1.訪问应用程序初始化參数

application提供了相应用程序初始化參数进行訪问的方法。

应用程序初始化參数在web.xml文件里进行设置。web.xml文件位于Web应用所在的文件夹下的WEB-INF子文件夹中。在web.xml中通过<context-param>标记配置应用程序的初始化參数。

 

范例:

 

web.xml中配置了MySQL数据库所需的url參数,实比例如以下:

<context-param>

<param-name>url</param-name>

<param-value>jdbc:mysql:127.0.0.1:3306/db_database</param-value>

</context-param>

application对象提供了两种方法訪问应用程序的初始化參数。分别介绍例如以下:

 

a.getInitParameter()方法:

该方法用户返回已经命名的參数值。语法格式例如以下:

application.getInitParameter(String name);

使用此方法获取上面web.xml文件里的url參数的值。可使用以下的代码

application.getInitParameter(“url”);

 

b.getAttributeNames()方法

application.getAttributeNames()返回以定义的应用程序初始化參数名的枚举,语法格式例如以下:

application.getAttributeNames();

范例:

web.xml文件例如以下:

<?xml version="1.0" encoding="UTF-8"?

>

<web-app version="3.0" 

xmlns="http://java.sun.com/xml/ns/javaee" 

xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 

xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 

http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">

  <display-name></display-name>

  <welcome-file-list>

    <welcome-file>index.jsp</welcome-file>

  </welcome-file-list>

  

<context-param>

<param-name>url</param-name>

<param-value>jdbc:mysql:127.0.0.1:3306/db_database</param-value>

</context-param>

 

</web-app>

 

result.jsp文件里取得应用程序的初始化參数。

<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%@ page import="java.util.*" %>

<%

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 'result.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/csshref="styles.css">

-->

 

  </head>

  

  <body>

    <%

     Enumeration enumeration = application.getInitParameterNames();

     while(enumeration.hasMoreElements())

     {

     String name = (String)enumeration.nextElement();

     String value = (String)application.getInitParameter(name);

     out.println(name);

     out.println(value);

     }

     %>

  </body>

</html>

2.管理应用程序的环境属性

application对象管理应用程序环境属性的方法例如以下:

getAttributeNames():获取全部application对象使用的属性名

 

getAttribute(String name):application对象中获取指定的对象名的值

 

setAttribute(String key,Object obj):设置application对象的属性的值

 

removeAttribute(String name):application对象中去掉指定的名称的属性




posted on 2017-04-27 17:55  blfbuaa  阅读(214)  评论(0编辑  收藏  举报