Called by the server (via the service method) to allow a servlet to handle a OPTIONS request. The OPTIONS request determines which HTTP methods the server supports and returns an appropriate header. For example, if a servlet overrides doGet, this method returns the following header:

Allow: GET, HEAD, TRACE, OPTIONS

There's no need to override this method unless the servlet implements new HTTP methods, beyond those implemented by HTTP 1.1.

Parameters:
req the HttpServletRequest object that contains the request the client made of the servlet
resp the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
java.io.IOException if an input or output error occurs while the servlet is handling the OPTIONS request
javax.servlet.ServletException if the request for the OPTIONS cannot be handled
    protected void doOptions(HttpServletRequest reqHttpServletResponse resp)
        throws ServletExceptionIOException
    {
//아까 분석한 대로 내가 재정의한 HttpServlet 파생 클래스부터 HttpServelt 이전 까지 정의도니 내가
//"재정의한" 메서드들 리턴.
        Method[] methods = getAllDeclaredMethods(this.getClass());
        
        boolean ALLOW_GET = false;
        boolean ALLOW_HEAD = false;
        boolean ALLOW_POST = false;
        boolean ALLOW_PUT = false;
        boolean ALLOW_DELETE = false;
        boolean ALLOW_TRACE = true;
        boolean ALLOW_OPTIONS = true;
        
        for (int i=0; i<methods.lengthi++) {
            String methodName = methods[i].getName();

     //너무 직관적인 코드니 생략. get은 <a> <img>였나? 이미지나 문자 보낼때 자동으로
     //get메서드 실행되고, 그외엔 보안등 강점을 이유로 대부분 post로 사용한다고
    //했었던 기억이 뇌리를 스침..
            if (methodName.equals("doGet")) {
                ALLOW_GET = true;
                ALLOW_HEAD = true;
            } else if (methodName.equals("doPost")) {
                ALLOW_POST = true;
            } else if (methodName.equals("doPut")) {
                ALLOW_PUT = true;
            } else if (methodName.equals("doDelete")) {
                ALLOW_DELETE = true;
            }
            
        }
        
        // we know "allow" is not null as ALLOW_OPTIONS = true
        // when this method is invoked

//오 위에서 직관적이라 표현한 부분이 아래의 처리를 위해서 그런거였구나..
//내가 재정의한 메서드를 통해 나만의 스타일로 스크립트 문자열을 만들어주고 있는듯?
        StringBuilder allow = new StringBuilder();
        if (ALLOW_GET) {
            allow.append();
        }
        if (ALLOW_HEAD) {
            if (allow.length() > 0) {
                allow.append(", ");
            }
            allow.append();
        }
        if (ALLOW_POST) {
            if (allow.length() > 0) {
                allow.append(", ");
            }
            allow.append();
        }
        if (ALLOW_PUT) {
            if (allow.length() > 0) {
                allow.append(", ");
            }
            allow.append();
        }
        if (ALLOW_DELETE) {
            if (allow.length() > 0) {
                allow.append(", ");
            }
            allow.append();
        }
        if (ALLOW_TRACE) {
            if (allow.length() > 0) {
                allow.append(", ");
            }
            allow.append();
        }
        if (ALLOW_OPTIONS) {
            if (allow.length() > 0) {
                allow.append(", ");
            }
            allow.append();
        }
        
        resp.setHeader("Allow"allow.toString());
    }
    
    
    
Called by the server (via the service method) to allow a servlet to handle a TRACE request. A TRACE returns the headers sent with the TRACE request to the client, so that they can be used in debugging. There's no need to override this method.

Parameters:
req the HttpServletRequest object that contains the request the client made of the servlet
resp the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
java.io.IOException if an input or output error occurs while the servlet is handling the TRACE request
javax.servlet.ServletException if the request for the TRACE cannot be handled
    protected void doTrace(HttpServletRequest reqHttpServletResponse resp
        throws ServletExceptionIOException
    {
        
        int responseLength;
//캐리지 리턴과 라인 넥스트의 조합? 한칸 내리고 제일 앞으로 땡기고? 타이핑?
// == 엔터키를 쳣을때 입력되는 값을 의미한다. (엔터치면 \r\n 이 들어옴)
        String CRLF = "\r\n";

// TRACE 도 스크립트 언어인듯함? 유저의 url주소 적어주고, 유저가 보낸 프로토콜(일반적으론 http)
//적어주고
        StringBuilder buffer = new StringBuilder("TRACE ").append(req.getRequestURI())
            .append(" ").append(req.getProtocol());
//대충 .jsp파일 만들었을때 제일 앞에 위치하던.. 이 정보를 만드는 과정 아닐까? 싶은데..
//아직 기본개념및 이해가 부족하다...
/*
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

*/
        Enumeration<StringreqHeaderEnum = req.getHeaderNames();
        whilereqHeaderEnum.hasMoreElements() ) {
            String headerName = reqHeaderEnum.nextElement();
            buffer.append(CRLF).append(headerName).append(": ")
                .append(req.getHeader(headerName));
        }
        buffer.append(CRLF);
        responseLength = buffer.length();
        resp.setContentType("message/http");
        resp.setContentLength(responseLength);
        ServletOutputStream out = resp.getOutputStream();
        out.print(buffer.toString());
    }


    
Receives standard HTTP requests from the public service method and dispatches them to the doXXX methods defined in this class. This method is an HTTP-specific version of thejavax.servlet.Servlet.service(javax.servlet.ServletRequest,javax.servlet.ServletResponse) method. There's no need to override this method.

Parameters:
req the HttpServletRequest object that contains the request the client made of the servlet
resp the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
java.io.IOException if an input or output error occurs while the servlet is handling the HTTP request
javax.servlet.ServletException if the HTTP request cannot be handled
See also:
javax.servlet.Servlet.service(javax.servlet.ServletRequest,javax.servlet.ServletResponse)
    protected void service(HttpServletRequest reqHttpServletResponse resp)
        throws ServletExceptionIOException
    {
//유저가 보낸 요청 메서드는 무엇이냐? get?post?
        String method = req.getMethod();
        if (method.equals()) {


//getLastModified가 뭐였지? part1에 있던건가.. part1에서 잘라왔음.
/*
<div class="line" id="line-245" style="font-family: 'Lucida Grande', Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: -2px 0px 0px; padding: 0px 0px 0px 10px; color: rgb(68, 29, 42); white-space: normal;"><div class="lnml" id="lnml-245" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px; display: inline;"></div><div class="ln" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px 6px; display: inline;">
245
</div><div class="lnmr" id="lnmr-245" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px; display: inline;"></div><pre style="margin-top: 0px; margin-bottom: 0px; display: inline;">    protected long getLastModified(HttpServletRequest req) {</pre></div><div class="line" id="line-246" style="font-family: 'Lucida Grande', Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: -2px 0px 0px; padding: 0px 0px 0px 10px; color: rgb(68, 29, 42); white-space: normal;"><div class="lnml" id="lnml-246" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px; display: inline;"></div><div class="ln" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px 6px; display: inline;">
246
</div><div class="lnmr" id="lnmr-246" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px; display: inline;"></div><pre style="margin-top: 0px; margin-bottom: 0px; display: inline;">        return -1;</pre></div><div class="line" id="line-247" style="font-family: 'Lucida Grande', Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: -2px 0px 0px; padding: 0px 0px 0px 10px; color: rgb(68, 29, 42); white-space: normal;"><div class="lnml" id="lnml-247" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px; display: inline;"></div><div class="ln" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px 6px; display: inline;">
247
</div><div class="lnmr" id="lnmr-247" style="font-family: 돋움, dotum, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: 0px; padding: 0px; display: inline;"></div><pre style="margin-top: 0px; margin-bottom: 0px; display: inline;">    }
</pre></div><div class="line" id="line-247" style="font-family: 'Lucida Grande', Tahoma, Verdana, Arial, Helvetica, sans-serif; font-size: 12px; list-style: none; margin: -2px 0px 0px; padding: 0px 0px 0px 10px; color: rgb(68, 29, 42); white-space: normal;"><pre style="margin-top: 0px; margin-bottom: 0px; display: inline;">*/</pre></div>


            long lastModified = getLastModified(req);
//수정된 서블릿은 부가적 작업을 건너뛰네?
            if (lastModified == -1) {
                // servlet doesn't support if-modified-since, no reason
                // to go through further expensive logic
                doGet(reqresp);
            } else {
//어떤 경우에 일로 빠지는 거지? (maybeSetlastModified()가 변경하는건가?)
//나머진 내일 분석!!!!!
                long ifModifiedSince = req.getDateHeader();
                if (ifModifiedSince < lastModified) {
                    // If the servlet mod time is later, call doGet()
                    // Round down to the nearest second for a proper compare
                    // A ifModifiedSince of -1 will always be less
                    maybeSetLastModified(resplastModified);
                    doGet(reqresp);
                } else {
                    resp.setStatus(.);
                }
            }
        } else if (method.equals()) {
            long lastModified = getLastModified(req);
            maybeSetLastModified(resplastModified);
            doHead(reqresp);
        } else if (method.equals()) {
            doPost(reqresp);
            
        } else if (method.equals()) {
            doPut(reqresp);
            
        } else if (method.equals()) {
            doDelete(reqresp);
            
        } else if (method.equals()) {
            doOptions(req,resp);
            
        } else if (method.equals()) {
            doTrace(req,resp);
            
        } else {
            //
            // Note that this means NO servlet supports whatever
            // method was requested, anywhere on this server.
            //
            String errMsg = .getString("http.method_not_implemented");
            Object[] errArgs = new Object[1];
            errArgs[0] = method;
            errMsg = MessageFormat.format(errMsgerrArgs);
            
            resp.sendError(.errMsg);
        }
    }
    
    /*
     * Sets the Last-Modified entity header field, if it has not
     * already been set and if the value is meaningful.  Called before
     * doGet, to ensure that headers are set before response data is
     * written.  A subclass might have set this header already, so we
     * check.
     */
    private void maybeSetLastModified(HttpServletResponse resp,
                                      long lastModified) {
        if (resp.containsHeader())
            return;
        if (lastModified >= 0)
            resp.setDateHeader(lastModified);
    }
   
    
    
Dispatches client requests to the protected service method. There's no need to override this method.

Parameters:
req the HttpServletRequest object that contains the request the client made of the servlet
res the HttpServletResponse object that contains the response the servlet returns to the client
Throws:
java.io.IOException if an input or output error occurs while the servlet is handling the HTTP request
javax.servlet.ServletException if the HTTP request cannot be handled
See also:
javax.servlet.Servlet.service(javax.servlet.ServletRequest,javax.servlet.ServletResponse)
    @Override
    public void service(ServletRequest reqServletResponse res)
        throws ServletExceptionIOException
    {
        HttpServletRequest  request;
        HttpServletResponse response;
        
        if (!(req instanceof HttpServletRequest &&
                res instanceof HttpServletResponse)) {
            throw new ServletException("non-HTTP request or response");
        }
        request = (HttpServletRequestreq;
        response = (HttpServletResponseres;
        service(requestresponse);
    }
/*
 * A response that includes no body, for use in (dumb) "HEAD" support.
 * This just swallows that body, counting the bytes in order to set
 * the content length appropriately.  All other methods delegate directly
 * to the wrapped HTTP Servlet Response object.
 */
// file private
    private static final ResourceBundle lStrings
        = ResourceBundle.getBundle("javax.servlet.http.LocalStrings");
    private NoBodyOutputStream noBody;
    private PrintWriter writer;
    private boolean didSetContentLength;
    private boolean usingOutputStream;
    // file private
        super(r);
         = new NoBodyOutputStream();
    }
    // file private
    void setContentLength() {
        if (!) {
            if ( != null) {
                .flush();
            }
            setContentLength(.getContentLength());
        }
    }
    @Override
    public void setContentLength(int len) {
        super.setContentLength(len);
         = true;
    }
    @Override
    public void setContentLengthLong(long len) {
        super.setContentLengthLong(len);
         = true;
    }
    @Override
    public void setHeader(String nameString value) {
        super.setHeader(namevalue);
        checkHeader(name);
    }
    @Override
    public void addHeader(String nameString value) {
        super.addHeader(namevalue);
        checkHeader(name);
    }
    @Override
    public void setIntHeader(String nameint value) {
        super.setIntHeader(namevalue);
        checkHeader(name);
    }
    @Override
    public void addIntHeader(String nameint value) {
        super.addIntHeader(namevalue);
        checkHeader(name);
    }
    private void checkHeader(String name) {
        if ("content-length".equalsIgnoreCase(name)) {
             = true;
        }
    }
    @Override
    public ServletOutputStream getOutputStream() throws IOException {
        if ( != null) {
            throw new IllegalStateException(
                .getString("err.ise.getOutputStream"));
        }
         = true;
        return ;
    }
    @Override
        if () {
            throw new IllegalStateException(
                .getString("err.ise.getWriter"));
        }
        if ( == null) {
            OutputStreamWriter w = new OutputStreamWriter(
                getCharacterEncoding());
             = new PrintWriter(w);
        }
        return ;
    }
/*
 * Servlet output stream that gobbles up all its data.
 */
// file private
    private static final String LSTRING_FILE =
        "javax.servlet.http.LocalStrings";
    private static ResourceBundle lStrings =
        ResourceBundle.getBundle();
    private int contentLength = 0;
    // file private
    NoBodyOutputStream() {}
    // file private
    int getContentLength() {
        return ;
    }
    @Override
    public void write(int b) {
        ++;
    }
    @Override
    public void write(byte buf[], int offsetint len)
        throws IOException
    {
        if (buf == null) {
            throw new NullPointerException(
                    .getString("err.io.nullArray"));
        }
        if (offset < 0 || len < 0 || offset+len > buf.length) {
            String msg = .getString("err.io.indexOutOfBounds");
            Object[] msgArgs = new Object[3];
            msgArgs[0] = Integer.valueOf(offset);
            msgArgs[1] = Integer.valueOf(len);
            msgArgs[2] = Integer.valueOf(buf.length);
            msg = MessageFormat.format(msgmsgArgs);
            throw new IndexOutOfBoundsException(msg);
        }
         += len;
    }
    public boolean isReady() {
        return false;
    }
    public void setWriteListener(WriteListener writeListener) {
    }


'프로그래밍 > JSP' 카테고리의 다른 글

jsp에서 빈의 사용3  (0) 2014.01.01
jsp에서 빈의 사용2  (0) 2014.01.01
빈을 이용한 컴포넌트 방식의 설계1  (0) 2014.01.01
jsp 스크립트  (0) 2014.01.01
javax.servlet.http.HttpServlet 소스코드 part1 (2013/11/27)  (0) 2014.01.01
by givingsheart 2014. 1. 1. 15:10