// java
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html; charset=utf-8");
resp.setCharacterEncoding("utf-8");
HttpSession session = req.getSession(false);
/*
*
* req.getSession(false);
* HttpSessiion 세션이 존재하면, 현재 HttpSession을 반환한다.
* 존재하지 않지 않으면, 그냥 null을 반환한다.
*
* req.getSession(ture);
* HttpSessiion 세션이 존재하면, 현재 HttpSession을 반환한다.
* 존재하지 않지 않으면, 새로 session을 생성한다.
*
* */
PrintWriter out = resp.getWriter();
out.println("<html>");
out.println("<head>");
out.println("<title>Hello</title>");
out.println("</head>");
out.println("<body>");
if(session == null) {
out.println("<p>세션이 존재하지 않습니다 세션을 시작합니다</p>");
// 세션 생성
session = req.getSession(true);
session.setMaxInactiveInterval(30);
session.setAttribute("visit", "1");
}
else {
String visitedStr = (String) session.getAttribute("visit");
int count = Integer.parseInt(visitedStr);
count++;
out.println("<p>방문횟수는 ");
out.println(count);
out.println(" 입니다</p>");
session.setAttribute("visit", Integer.toString(count));
}
out.println("<a href=\"hello\">다시 표시</a>");
out.println("</body>");
out.println("</html>");
out.close();
}
// html
<form action="hello" method="get">
<input type="submit" value="전송">
</form>