개발/Servlet, JSP

Spring - Servlet

잇(IT) 2023. 6. 13. 18:34
728x90

- 스프링 부트 서블릿 환경 구성

- @ServletComponentScan

- 스프링 부트는 서블릿을 직접 등록해서 사용할 수 있도록 @ServletComponentScan 을 지원한다. 다음과 같이 추가하자.

@ServletComponentScan // 서블릿 자동 등록
@SpringBootApplication
public class ServletApplication {

	public static void main(String[] args) {
		SpringApplication.run(ServletApplication.class, args);
	}

}

 

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 username = request.getParameter("username");
        System.out.println("username = " + username);

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

- @WebServlet 서블릿 애노테이션

   - name: 서블릿 이름

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

protected void service(HttpServletRequest request, HttpServletResponse response)

- 서블릿 컨테이너 동작 방식

* HTTP 응답에서 Content-Length는 웹 애플리케이션 서버가 자동으로 생성해준다.


- HttpServletRequest

- HTTP 요청 메시지를 개발자가 직접 파싱해서 사용해도 되지만, 매우 불편할 것이다. 서블릿은 개발자가 HTTP 요청 메시지를 편리하게 사용할 수 있도록 개발자 대신에 HTTP 요청 메시지를 파싱한다. 그리고 그 결과를 HttpServletRequest 객체에 담아서 제공한다.

 

- 임시 저장소 기능

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

   - 저장: request.setAttribute(name, value)

   - 조회: request.getAttribute(name)


- HTTP 요청 데이터

 

- 주로 다음 3가지 방법을 사용한다.

1. GET - 쿼리 파라미터

- /url?username=hello&age=20

- 메시지 바디 없이, URL의 쿼리 파라미터에 데이터를 포함해서 전달

- 예) 검색, 필터, 페이징등에서 많이 사용하는 방식

2. POST - HTML Form

- content-type: application/x-www-form-urlencoded

- 메시지 바디에 쿼리 파리미터 형식으로 전달 username=hello&age=20

- 예) 회원 가입, 상품 주문, HTML Form 사용

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

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

- 데이터 형식은 주로 JSON 사용 : POST, PUT, PATCH


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

- 쿼리 파라미터는 URL에 다음과 같이 ? 를 시작으로 보낼 수 있다. 추가 파라미터는 & 로 구분하면 된다.

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

String username = request.getParameter("username"); //단일 파라미터 조회

Enumeration<String> parameterNames = request.getParameterNames(); //파라미터 이름들 모두 조회

Map<String, String[]> parameterMap = request.getParameterMap(); //파라미터를 Map으로 조회

String[] usernames = request.getParameterValues("username"); //복수 파라미터 조회

- HTTP 요청 데이터 - POST HTML Form

- 특징

- content-type: application/x-www-form-urlencoded

- 메시지 바디에 쿼리 파리미터 형식으로 데이터를 전달한다. username=hello&age=20

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<form action="/request-param" method="post">
    username: <input type="text" name="username" />
    age: <input type="text" name="age" />
    <button type="submit">전송</button>
</form>
</body>
</html>

- application/x-www-form-urlencoded 형식은 앞서 GET에서 살펴본 쿼리 파라미터 형식과 같다.

- 따라서 쿼리 파라미터 조회 메서드를 그대로 사용하면 된다.

- 클라이언트(웹 브라우저) 입장에서는 두 방식에 차이가 있지만, 서버 입장에서는 둘의 형식이 동일하므로, request.getParameter() 로 편리하게 구분없이 조회할 수 있다.

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


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

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

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

- 데이터 형식은 주로 JSON 사용

- POST, PUT, PATCH

 

- HTTP 메시지 바디의 데이터를 InputStream을 사용해서 직접 읽을 수 있다

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

        System.out.println("messageBody = " + messageBody);

        response.getWriter().write("OK");

    }
}


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

 

- JSON 형식으로 파싱할 수 있게 객체를 하나 생성해야 한다.

@Getter
@Setter
public class HelloData {

    private String username;
    private int age;

}
@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.getUsername() = " + helloData.getUsername());
        System.out.println(

                 "helloData.getAge() = " + helloData.getAge());

        response.getWriter().write("OK");
    }
}

- JSON 결과를 파싱해서 사용할 수 있는 자바 객체로 변환하려면 Jackson, Gson 같은 JSON 변환 라이브러리를 추가해서 사용해야 한다. 스프링 부트로 Spring MVC를 선택하면 기본으로 Jackson 라이브러리( ObjectMapper )를 함께 제공한다.

 

 

 

 

 

 

 

 

 

 

 

출처 : 인프런 - 우아한 형제들 기술이사 김영한의 스프링 완전 정복 (스프링 핵심원리 - 기본 편)

728x90