application对象的使用
application对象在整个服务器生命期中都存在,它是一个全局对象。
application对象可以设置多个key-value值对形式的属性,这些属性对整个Web应用中的所有程序都能访问。
以下示例是application对象属性的设置与获取。
=======================================================
index.jsp用来设置application对象的属性
=======================================================
<%
request.setCharacterEncoding("utf-8");
String uname,email;
uname=request.getParameter("username");
email=request.getParameter("email");
if(uname!=null&&email!=null){
application.setAttribute("uname",uname);
application.setAttribute("email",email);
response.sendRedirect("showapp.jsp");
}
%>
<form action="index.jsp" method="POST">
用户名:<input type="text" name="username" value="" /><br>
E-mail:<input type="text" name="email" value="" /><br>
<input type="submit" value="提交" />
</form>
=======================================================
showapp.jsp用来获取application对象的属性
=======================================================
<%
String uname=(String)application.getAttribute("uname");
String email=(String)application.getAttribute("email");
if(uname!=null&&email!=null){
out.print("用户名:"+uname+"<br>");
out.print("E-mail:"+email+"<br>");
}else{
out.println("<h1>application中尚无用户信息!</h1>");
}
%>
Tomcat下虚拟目录的创建
一、在Tomcat的webapps目录下创建虚拟目录的方法
首先建一个文件夹,文件夹的名字即为虚拟目录的名字;
在其中建立WEB-INF子文件夹,然后创建web.xml文件(为了简单,可以直接将ROOT目录下的WEB-INF文件夹复制过来);
然后就可以建立一个JSP文件进行测试了。
二、在其他地方建立虚拟目录
建立文件夹的结构与上述方法相同。
打开server.xml文件,在其中找到</host>,在其上面一行加入如下语句:
<Context path="/ok1" debug="0" docBase="d:/ok1" reloadable="true"> </Context>
然后重启Tomcat服务器即可。
application实例——网页计数器
<%
String count=(String)application.getAttribute("count");
if(count==null){
count="1";
}else{
count=Integer.parseInt(count)+1+"";
}
application.setAttribute("count",count);
%>
<%="<h1>你是第"+count+"位到访者</h1><br>"%>