概述
1、application对象即应用 程序上下文对象,表示当前应用程序运行环境,用以获取应用程序上下文环境中的信息
2、application对象在容器启动时实例化,在容器关闭时销毁。作用域为整个Web容器的生命周期
3、application对象实现了javax.servlet.ServletContext接口,具有ServletContext接口的所有功能。application对象常用方法如下:
☞void setAttribute(String name,Object value) 以名/值对的方式存储application属性
☞Object getAttribute(String name) 根据属性名获取属性值
☞void removeAttribute(String name) 根据属性名从application域中移除属性
实例演示
演示使用application对象实现一个页面留言板
guest.jsp:
<%@page import="java.util.Vector"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>留言板</title>
<script type="text/javascript">
function validate(){
var uname = document.getElementById("username");
var message = document.getElementById("message");
if(uname.value == ""){
alert("请输入您的名字!");
uname.focus();
return false;
}else if(message.value == ""){
alert("请填写留言");
message.focus();
return false;
}
return true;
}
</script>
</head>
<body>
<p>请留言</p>
<form action="guest.jsp" method="post" onsubmit="return validate();">
<p>
输入您的名字:<input name="username" id="username" type="text"/>
</p>
<p>
输入您的留言:
<textarea name="message" id="message" rows="3" cols="50"></textarea>
</p>
<p>
<input type="submit" value="提交留言">
</p>
</form>
<hr>
<p>留言内容</p>
<%
request.setCharacterEncoding("UTF-8");
//获取留言信息
String username = request.getParameter("username");
String message = request.getParameter("message");
//从application域属性messageBook中获取留言板
Vector<String> book = (Vector<String>)application.getAttribute("messageBook");
if(book == null){//若留言板不存在则新建一个
book = new Vector<String>();
}
//判断用户是否提交了留言,若提交信息加入留言板,存入application域属性中
if(username != null && message != null){
String info = username + "#" + message;
book.add(info);
application.setAttribute("messageBook",book);
}
//遍历输出所有用户留言
if(book.size() > 0){
for(String mess : book){
//字符串的拆分
String[] arr = mess.split("#");
out.print("<p>姓名"+arr[0]+"<br>留言:"+ arr[1]+"</p>");
}
}else{
out.print("还没有留言!");
}
%>
</body>
</html>