본문 바로가기
Spring/MVC 1편

서블릿

by JHyun0302 2023. 8. 4.
728x90

※ 스프링 부트 서블릿 환경 구성: @ServletComponentScan

 

@ServletComponentScan //서블릿 자동 등록 
@SpringBootApplication
public class ServletApplication {
	public static void main(String[] args) {
		SpringApplication.run(ServletApplication.class, args);
	}
}

 

 

@ WebServlet(name = "helloServlet", urlPatterns = "/hello")

  • name: 서블릿 이름
  • urlPatterns: URL 매핑

 

 

HTTP 요청을 통해 매핑된 URL이 호출되면 서블릿 컨테이너는 다음 메서드를 실행한다. 

protected void service(HttpServletRequest request, HttpServletResponse response)

 

 

 

 

참고: HTTP 요청 메시지 로그로 확인하기(application.properties)

    logging.level.org.apache.coyote.http11=debug

 

 

 

 

 

웹 애플리케이션 서버의 요청 응답 구조

 

 

 

 참고:  http://localhost:8080 호출시 index.html 페이지 열림 (main/webapp/index.html)

 

 

 


 HttpServletRequest

 

 HttpServletRequest 역할

서블릿은 개발자 대신에 HTTP 요청 메시지를 파싱한다. 그 결과를 HttpServletRequest 객체에 담아서 제공한다.

 

 

 

 

START LINE

  • HTTP 메소드
  • URL
  • 쿼리 스트링
  • 스키마, 프로토콜

 

헤더

  • 헤더 조회

 

바디

  • form 파라미터 형식 조회
  • message body 데이터 직접 조회

 

임시 저장소 기능 : HTTP 요청이 시작부터 끝날 때 까지 유지되는 임시 저장소 기능

  • 저장: request.setAttribute(name, value)
  • 조회: request.getAttribute(name)

 

세션 관리 기능

  • request.getSession(create: true)

 

 

 

 참고: 로컬에서 테스트하면 IPv6 정보가 나오는데, IPv4 정보를 보고 싶으면 다음 옵션을 VM options넣어주면 된다.

-Djava.net.preferIPv4Stack=true

 

 

 


HTTP 요청 데이터 - 개요

 

 

1. GET - 쿼리 파라미터

  • /url?username=hello&age=20
  • 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달
  • ex) 검색, 필터, 페이징등에서 많이 사용하는 방식

 

 

2. POST - HTML Form

  • content-type: application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파리미터 형식으로 전달 username=hello&age=20
  • ex) 회원 가입, 상품 주문, HTML Form 사용

 

 

3. HTTP message body에 데이터를 직접 담아서 요청

  • HTTP API에서 주로 사용, JSON, XML, TEXT

데이터 형식은 주로 JSON 사용

  • POST, PUT, PATCH

  


HTTP 요청 데이터 - GET 쿼리 파라미터

 

 

메시지 바디 없이, URL쿼리 파라미터를 사용해서 데이터를 전달가능

ex) 검색, 필터, 페이징 등에서 많이 사용

 

 

ex) http://localhost:8080/request-param?username=hello&username=kim&age=20

String username = request.getParameter("username");
System.out.println("request.getParameter(username) = " + username);

String age = request.getParameter("age");
 System.out.println("request.getParameter(age) = " + age);
 
 System.out.println("[이름이 같은 복수 파라미터 조회]");
 String[] usernames = request.getParameterValues("username");

 

 


HTTP 요청 데이터 - POST HTML Form

 

 

※  특징

  • content-type: application/x-www-form-urlencoded
  • 메시지 바디에 쿼리 파리미터 형식으로 데이터를 전달한다. username=hello&age=20

 

 

☆ request.getParameter() GET URL 쿼리 파라미터 형식도 지원하고, POST HTML Form 형식도 둘 다 지원한다.

 

 

 

 


HTTP 요청 데이터 - API 메시지 바디 - 단순 텍스트

 

 

※ HTTP message body에 데이터를 직접 담아서 요청

  • HTTP API에서 주로 사용, JSON, XML, TEXT
  • 데이터 형식은 주로 JSON 사용
  • POST, PUT, PATCH

 

 

 

@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body-string")
public class RequestBodyStringServlet extends HttpServlet {
    
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    ServletInputStream inputStream = request.getInputStream();
    String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
    
    System.out.println("messageBody = " + messageBody);
    response.getWriter().write("ok");
    }
}

 

 

문자 전송

  • POST http://localhost:8080/request-body-string
  • content-type: text/plain
  • message body: hello
  • 결과: messageBody = hello

 


HTTP 요청 데이터 - API 메시지 바디 - JSON

 

 

@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {
private ObjectMapper objectMapper = new ObjectMapper();

	@Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        ServletInputStream inputStream = request.getInputStream();
        String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
           
        System.out.println("messageBody = " + messageBody);
        HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
        
        System.out.println("helloData.username = " + helloData.getUsername());
        System.out.println("helloData.age = " + helloData.getAge());
        
        response.getWriter().write("ok");
	}
}

 

 

JSON 형식 전송

  • POST http://localhost:8080/request-body-json
  • content-type: application/json
  • message body: {"username": "hello", "age": 20}
  • 결과: messageBody = {"username": "hello", "age": 20}

 

◎ 참고: Spring MVC를 선택하면 Jackson 라이브러리( ObjectMapper )를 함께 제공 (JSON 변환 라이브러리)



 

 


HttpServletResponse - 기본 사용법

 

 

 

HTTP 응답 메시지 생성

  • HTTP 응답코드 지정
  • 헤더 생성
  • 바디 생성

 

편의 기능 제공

  • Content-Type, 쿠키, Redirect

 

 


HTTP 응답 데이터 - 단순 텍스트, HTML

 

 

1. 단순 텍스트 응답

  •  writer.println("ok"); 

 

2. HTML 응답

 


3. HTTP API - MessageBody JSON 응답

 

 

 

 


HTTP 응답 데이터 - HTML 응답

 

 

@WebServlet(name = "responseHtmlServlet", urlPatterns = "/response-html")
public class ResponseHtmlServlet extends HttpServlet {

	@Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    //Content-Type: text/html;charset=utf-8
    response.setContentType("text/html");
    response.setCharacterEncoding("utf-8");
    
    PrintWriter writer = response.getWriter(); 
    writer.println("<html>"); 
    writer.println("<body>");
    writer.println(" <div>안녕?</div>"); 
    writer.println("</body>"); 
    writer.println("</html>");
    } 
}

 

 

HTML을 반환할 때는 content-typetext/html 로 지정해야 한다.

 

 

 

 


HTTP 응답 데이터 - API JSON

 

 

@WebServlet(name = "responseJsonServlet", urlPatterns = "/response-json")
public class ResponseJsonServlet extends HttpServlet {
private ObjectMapper objectMapper = new ObjectMapper();
   
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    
    //Content-Type: application/json
    response.setHeader("content-type", "application/json");
    response.setCharacterEncoding("utf-8");
    
    HelloData data = new HelloData();
    data.setUsername("kim");
    data.setAge(20);

    //{"username":"kim","age":20}
    String result = objectMapper.writeValueAsString(data);
    response.getWriter().write(result);
    } 
}

 

 

 HTML을 반환할 때는 content-typeapplication/json 로 지정해야 한다.

 

◎ 참고: Jackson 라이브러리가 제공하는 objectMapper.writeValueAsString() 를 사용하면 객체를 JSON 문자로 변경할 수 있다.

반응형

'Spring > MVC 1편' 카테고리의 다른 글

스프링 MVC - 웹 페이지 만들기  (0) 2023.08.05
스프링 MVC - 기본 기능  (0) 2023.08.05
MVC 프레임워크 구조 이해  (0) 2023.08.05
서블릿, JSP, MVC 패턴  (0) 2023.08.04