자바 서블릿 관련 질문입니다.

googlejoa의 이미지

제가 자바는 전혀 모르는데요.(-.-)
자바 서블릿에서는 http 의 보통 특성과는 달리 변수값이 세션이 끊기지 않고 유지되나요?
아래코드를 이용해서 계속 카운트가 증가되는 것을 동적으로 읽는 경우를 보았는데..
아래에서 카운트(count) 값이 계속 증가될 수 있나요?(브라우저에서는 처음에 "reset"값만 보내고 그 후에는 그냥 요청만 하는 것 같더라구요. 그러면 count 값이 점점 증가되면서 해당하는 값이 브라우저로 전송되고..)

import java.io.*;
import java.net.*;
 
import javax.servlet.*;
import javax.servlet.http.*;
 
/**
 *
 * @author nate
 * @version
 */
public class DynamicUpdateServlet extends HttpServlet {
    private int counter = 1;
 
    /**
     * @param request servlet request
     * @param response servlet response
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        String res = "";
        String task = request.getParameter("task");
        String message = "";       
 
        if (task.equals("reset")) {
            counter = 1;
        } else {
            switch (counter) {
                case 1: message = "Steve walks on stage"; break;
                case 2: message = "iPods rock"; break;
                case 3: message = "Steve says Macs rule"; break;
                case 4: message = "Change is coming"; break;
                case 5: message = "Yes, OS X runs on Intel - has for years"; break;
                case 6: message = "Macs will soon have Intel chips"; break;
                case 7: message = "done"; break;
            }
            counter++;
        }
 
        res = "<message>" + message + "</message>";
 
        PrintWriter out = response.getWriter();
        response.setContentType("text/xml");
        response.setHeader("Cache-Control", "no-cache");
        out.println("<response>");
        out.println(res);
        out.println("</response>");
        out.close();
    }
 
    /** 
     * @param request servlet request
     * @param response servlet response
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {
        doGet(request, response);
    }
 
 
    /** Returns a short description of the servlet.
     */
    public String getServletInfo() {
        return "Short description";
    }
}

Necromancer의 이미지

클래스가 HttpServlet을 상속받았으므로
HttpServlet 생성자쪽을 확인하거나(싱글턴)
아니면 HttpServlet에서 내부적으로 쿠키나 세션 처리하는게 있을겁니다.
그걸 확인하셔야 합니다.

그리고 싱글턴이면 쿠키나 세션 안쓰고도 카운터 얼마든지 구현할 수 있습니다. (단 정확도는 떨어지죠)
클래스의 인스턴스가 VM내에 단 한개만 존재하기 때문이죠. 싱글턴 클래스는 생성자가 보통 private입니다.

Written By the Black Knight of Destruction

Written By the Black Knight of Destruction

dormael의 이미지

서블릿 컨테이너(톰캣과 같은)가 위의 서블릿 클래스의 인스턴스를 단 하나만 가지고 여러 요청에 대해 해당 메소드(doGet과 같은)를 호출하게 되어 있습니다.

한번 초기화된 단일한 인스턴스는 서블릿이 속한 컨텍스트가 종료되기 전까지 계속 메모리에 존재하게 됩니다.
멀티 쓰레드에 의해 접근이 되구요(현재 질문하신 내용만 이해하시려면 그냥 넘기셔도 될듯 합니다.)

해당 코드에서 counter++이 호출될 때마다 메모리에 존재하는 인스턴스의 멤버변수 counter의 값이 증가합니다.

즉, 위의 코드는 세션을 통한 보존이 아닌 서블릿의 특성(초기화 된 후 하나뿐인 인스턴스로 메모리 상에 존재하는)에 의한 보존으로 생각하셔야 할 것 같습니다.

다른 세션(웹브라우저)으로 접근하셔서 테스트 해보시면 이해하기가 더 쉬울듯 하네요.

-- Signature --
青い空大好き。
蒼井ソラもっと好き。
파란 하늘 너무 좋아.
아오이 소라 더좋아.

댓글 달기

Filtered HTML

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

BBCode

  • 텍스트에 BBCode 태그를 사용할 수 있습니다. URL은 자동으로 링크 됩니다.
  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param>
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.

Textile

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • You can use Textile markup to format text.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Markdown

  • 다음 태그를 이용하여 소스 코드 구문 강조를 할 수 있습니다: <code>, <blockcode>, <apache>, <applescript>, <autoconf>, <awk>, <bash>, <c>, <cpp>, <css>, <diff>, <drupal5>, <drupal6>, <gdb>, <html>, <html5>, <java>, <javascript>, <ldif>, <lua>, <make>, <mysql>, <perl>, <perl6>, <php>, <pgsql>, <proftpd>, <python>, <reg>, <spec>, <ruby>. 지원하는 태그 형식: <foo>, [foo].
  • Quick Tips:
    • Two or more spaces at a line's end = Line break
    • Double returns = Paragraph
    • *Single asterisks* or _single underscores_ = Emphasis
    • **Double** or __double__ = Strong
    • This is [a link](http://the.link.example.com "The optional title text")
    For complete details on the Markdown syntax, see the Markdown documentation and Markdown Extra documentation for tables, footnotes, and more.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 사용할 수 있는 HTML 태그: <p><div><span><br><a><em><strong><del><ins><b><i><u><s><pre><code><cite><blockquote><ul><ol><li><dl><dt><dd><table><tr><td><th><thead><tbody><h1><h2><h3><h4><h5><h6><img><embed><object><param><hr>

Plain text

  • HTML 태그를 사용할 수 없습니다.
  • web 주소와/이메일 주소를 클릭할 수 있는 링크로 자동으로 바꿉니다.
  • 줄과 단락은 자동으로 분리됩니다.
댓글 첨부 파일
이 댓글에 이미지나 파일을 업로드 합니다.
파일 크기는 8 MB보다 작아야 합니다.
허용할 파일 형식: txt pdf doc xls gif jpg jpeg mp3 png rar zip.
CAPTCHA
이것은 자동으로 스팸을 올리는 것을 막기 위해서 제공됩니다.