- 在API中对应的接口:servletcontext 相当于整个webapp在运行过程中的表现
- 类似在设置全局变量
我们来看一个小例子
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
public class TestServletContext extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
PrintWriter out = resp.getWriter();
ServletContext application = this.getServletContext();
Integer accessCount = (Integer) application.getAttribute("accessCount");
if (accessCount == null){
accessCount = new Integer(0);
}else {
accessCount = new Integer(accessCount.intValue()+1);
}
application.setAttribute("accessCount",accessCount);
out.println(accessCount);
}
}
- 补充小知识点:
当servlet在某个包里的时候,在配置web.xml的时候一定要写全了,即在servlet-class名字处写清楚包名.xxx
请求转发,页面跳转之类,等我们学过jsp在开始
网友评论