티스토리 뷰

- 강의 : 인프런 스프링 MVC

- 인텔리제이 / 자바11

- 스프링 부트 환경에서 ㄱㄱ

(스프링부트가 톰캣 서버를 내장하고 있어 톰캣 설치 없이 서블릿 코드 실행 가능하기 때문)

 

 

 

hello.servlet.basic.HelloServlet

package hello.servlet.basic;
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(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("HelloServlet.service");
        System.out.println("request = " + request);
        System.out.println("response = " + response);
        String name = request.getParameter("username");
        System.out.println("name " + name) ;

        response.setContentType("text/plain");
        response.setCharacterEncoding("utf-8");
        response.getWriter().write("hello" + name);
    }
}

- 서블릿 클래스 구현시, HttpServelet 클래스를 상속받아야 서블릿으로 동작

- @WebServlet : 서블릿 어노테이션(name : 서블릿 이름, urlPatterns : 매핑될 URL)

 

 

 

localhost:8080 호출 결과

콘솔창

 

 

 

* 정리 

HTTP 요청 :

GET/hello?username=word HTTP/1.1

Host: localhost:8080

 

HTTP 응답 :

HTTP/1.1 200 OK

Content-Type : text/plain;charset=utf-8

Content-Length:11

 

hello word

 

 

 

 

* HttpServletRequest

- HTTP 요청 메세지를 개발자가 직접 파싱해도 되지만 불편하다

- 서블릿은 개발자 대신에 HTTP 요청 메세지를 파싱해준다

- 그리고 그 결과를 HttpServletRequest 객체에 담아서 제공

- HTTP 요청 메세지는 START LINE, 헤더, 바디로 나뉨

 

 

 

hello.servlet.basic.request.RequestHeaderServlet

package hello.servlet.basic.request;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

@WebServlet(name="requestHeaderServlet", urlPatterns = "/request-header")
public class RequestHeaderServlet extends HttpServlet {

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        printStartLine(request);
        printHeaders(request);
        printHeaderUtils(request);
        printEtc(request);
    } 

    private void printStartLine(HttpServletRequest request) {
        System.out.println("--- REQUEST-LINE - start ---");
        System.out.println("request.getMethod() = " + request.getMethod()); //GET
        System.out.println("request.getProtocal() = " + request.getProtocol()); //HTTP/1.1
        System.out.println("request.getScheme() = " + request.getScheme()); //http
        // http://localhost:8080/request-header
        System.out.println("request.getRequestURL() = " + request.getRequestURL());
        // /request-test
        System.out.println("request.getRequestURI() = " + request.getRequestURI());
        //username=hi
        System.out.println("request.getQueryString() = " + request.getQueryString());
        System.out.println("request.isSecure() = " + request.isSecure()); //https사용 유무
        System.out.println("--- REQUEST-LINE - end ---");
        System.out.println();
    }


    private void printHeaders(HttpServletRequest request){
        System.out.println("--- Headers - start ---");
        
        //옛날방법
//        Enumeration<String> headerName = request.getHeaderNames();
//        while (headerNames.hasMoreElements()){
//            String headerName = headerNames.nextElement();
//            System.out.println("headerName = " + headerName);
//        }
        request.getHeaderNames().asIterator()
                .forEachRemaining(headerName-> System.out.println("headerNames = " + headerName));

        System.out.println("--- Headers - end ---");
        System.out.println();
    }



    //Header 편리한 조회
    private void printHeaderUtils(HttpServletRequest request) {
        System.out.println("--- Header 편의 조회 start ---");
        System.out.println("[Host 편의 조회]");
        System.out.println("request.getServerName() = " +
                request.getServerName()); //Host 헤더
        System.out.println("request.getServerPort() = " +
                request.getServerPort()); //Host 헤더
        System.out.println();
        System.out.println("[Accept-Language 편의 조회]");
        request.getLocales().asIterator()
                .forEachRemaining(locale -> System.out.println("locale = " +
                        locale));
        System.out.println("request.getLocale() = " + request.getLocale());
        System.out.println();
        System.out.println("[cookie 편의 조회]");
        if (request.getCookies() != null) {
            for (Cookie cookie : request.getCookies()) {
                System.out.println(cookie.getName() + ": " + cookie.getValue());
            }
        }
        System.out.println();
        System.out.println("[Content 편의 조회]");
        System.out.println("request.getContentType() = " +
                request.getContentType());
        System.out.println("request.getContentLength() = " +
                request.getContentLength());
        System.out.println("request.getCharacterEncoding() = " +
                request.getCharacterEncoding());
        System.out.println("--- Header 편의 조회 end ---");
        System.out.println();
    }


    private void printEtc(HttpServletRequest request) {
        System.out.println("--- 기타 조회 start ---");
        System.out.println("[Remote 정보]");
        System.out.println("request.getRemoteHost() = " +
                request.getRemoteHost()); //
        System.out.println("request.getRemoteAddr() = " +
                request.getRemoteAddr()); //
        System.out.println("request.getRemotePort() = " +
                request.getRemotePort()); //
        System.out.println();
        System.out.println("[Local 정보]");
        System.out.println("request.getLocalName() = " +
                request.getLocalName()); //
        System.out.println("request.getLocalAddr() = " +
                request.getLocalAddr()); //
        System.out.println("request.getLocalPort() = " +
                request.getLocalPort()); //
        System.out.println("--- 기타 조회 end ---");
        System.out.println();
    }

}

- service를 public으로 받아오면 안된다

- 메소드로 뺄 부분들을 드래그 하고 ctrl + alt+ shift +T , Extract Mathod하면 간편

- while문을 람다로 간단하게

 

 

 

localhost:8080/request-header 날렸을때 콘솔창

댓글
최근에 올라온 글
최근에 달린 댓글
링크
Total
Today
Yesterday