ケーススタディ:
原理:initメソッドは、サーブレット・オブジェクトを作成するときに一度だけ実行されます
- ユーザ第一訪問サーブレットは、
(一度だけ)記録セッション数カウントキー値ペアを格納する、のServletContextドメインオブジェクトを取得し、initメソッドをオーバーライドする
doGetメソッドでは、カウント記憶され、取得したドメインオブジェクト
バックユーザに応答をカウントすると
カウント++
のServletContextドメインに格納されているオブジェクトをカウントします - サーブレットではないユーザがアクセス初めて
doGetメソッドでは、カウントに格納されたドメインオブジェクトに入った
ユーザーに応答をカウントする
カウント++
のServletContext領域に格納されたオブジェクトをカウントします
コードの実装:
package com.ccc.demo01ServletContext;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
@WebServlet(urlPatterns = "/count")
public class Demo06CountServlet extends HttpServlet {
//重写init方法,获取ServletContext域对象,存储一个键值对count记录访问次数(只会执行一次)
@Override
public void init() throws ServletException {
ServletContext context = getServletContext();
context.setAttribute("count",1);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//在doGet方法中,获取到域对象中存储的count
ServletContext context = getServletContext();
int count = (int)context.getAttribute("count");
//把count给用户响应回去
response.getWriter().write("welcome\t"+count);
//count++
count++;
//把count存储到ServletContext域对象
context.setAttribute("count",count);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
ダイレクト出力数が動作しない場合など、
response.getWriter().write(count);
ブラウザは整数を知らないので、あなただけにそれを回すことができ、文字列の出力仕事。例えば、目の前にあるかのスペースの後ろ
response.getWriter().write(" "+count);