我試圖爲每個會話的獲取請求創建一個計數器,然後我最終創建了它,但是,我有一個問題,以便了解邏輯的底部是如何工作的。這裏是我的代碼:Java Servlets session.getAttribute和setAttribute
public class FirstServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
final String COUNTER = "Counter";
/**
* @see HttpServlet#HttpServlet()
*/
public FirstServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
PrintWriter out = resp.getWriter();
int count = 1;
Integer i = (Integer) session.getAttribute(COUNTER);
if(i != null){
count = i.intValue() +1;
}
session.setAttribute(COUNTER, new Integer(count));
out.println("<html>");
out.println("<head>");
out.println("<title>Session Counter</title>");
out.println("</head>");
out.println("<body>");
out.println("Your session ID is <b>" + session.getId());
out.println("</b> and you have hit this page <b>" + count
+ "</b> time(s) during this browser session");
}
這裏有幾個問題:
Integer i = (Integer) session.getAttribute(COUNTER);
if(i != null){
count = i.intValue() +1;
}
因爲我在做我的整數,然後澆鑄成整數,這是否意味着沒有字符串值的事它會總是有一個int值爲0? (因爲COUNTER是字符串類型)
我的第二個問題是:爲什麼我必須在使用session.setAttribute()之後才能打印新值。我的邏輯如下。正如我們知道每個servlet只實例化一次 - 我得到的屬性(session.getAttribute(COUNTER)),檢查我是否不同於空,然後增加它,如果我評論setAttribute我將無法看到新的遞增值。爲什麼我必須重新設置才能獲得正確的價值?當我按刷新時,我正在做一個新的獲取請求,它採用了COUNTER的舊值(例如2),然後檢查它是否爲空並將其增加1.我不明白爲什麼我必須使用session.setAttribute再次...
謝謝!