一 put-application.jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>application测试</title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<!-- JSP声明 -->
<%!
int i;
%>
<!-- 将i值自加后放入application的变量内 -->
<%
application.setAttribute("counter",String.valueOf(++i));
%>
<!-- 输出i值 -->
<%=i%>
</body>
</html>
二 get-application.jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>application测试</title>
<meta name="website" content="http://www.crazyit.org" />
</head>
<body>
<!-- 直接输出application 变量值 -->
<%=application.getAttribute("counter")%>
</body>
</html>
三 Servlet代码
package lee;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.*;
@WebServlet(name="get-application",
urlPatterns={"/get-application"})
public class GetApplication extends HttpServlet
{
public void service(HttpServletRequest request,
HttpServletResponse response)throws IOException
{
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("<html><head><title>");
out.println("测试application");
out.println("</title></head><body>");
ServletContext sc = getServletConfig().getServletContext();
out.print("application中当前的counter值为:");
out.println(sc.getAttribute("counter"));
out.println("</body></html>");
}
}
四 测试