ServletContext示例:使用Servlet上下文保存访问人数
程序员文章站
2022-03-03 12:40:24
...
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class IndexServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public IndexServlet() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext ctx = this.getServletContext();
synchronized(this){
Integer counter = (Integer)ctx.getAttribute("UserNumber");
int tmp = 0;
if(counter==null){
counter = new Integer(1);
}else{
tmp=counter.intValue()+1;
counter = new Integer(tmp);
}
ctx.setAttribute("UserNumber", counter);
}
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>首页</title></head>");
out.println("<body>");
out.println("这是第一页<br>");
out.println("<a href='UserName'>人数统计</a>");
out.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UserName extends HttpServlet {
private static final long serialVersionUID = 1L;
public UserName() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
ServletContext ctx = this.getServletContext();
Integer counter = (Integer)ctx.getAttribute("UserNumber");
response.setContentType("text/html;charset=GBK");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>访问人数统计</title></head>");
out.println("<body>");
if(counter!=null){
out.println("已经有"+counter.intValue()+"人访问本网站");
}
else{
out.println("你是第一个访问本网站的");
}
out.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
上一篇: C3P0 配置spring数据源
下一篇: Ribbon首次调用超时