관심쟁이 영호
[#3 Spring Boot 정주행] HttpServletRequest, HttpServletResponse 이용해보자! ㅣ 서블릿 체험 본문
[#3 Spring Boot 정주행] HttpServletRequest, HttpServletResponse 이용해보자! ㅣ 서블릿 체험
관심쟁이 영호 2021. 9. 9. 17:39오늘은 이전 포스팅에서 다루었던 서블릿을 코드로 직접 확인하자!
목차
- 프로젝트 생성
- HttpServletRequest 확인
- HttpServletResponse 확인
프로젝트 생성
스프링으로 시작할 것이다.
1. 스프링 부트 프로젝트 생성
https://start.spring.io/ 에서 프로젝트를 생성한다.
Project : Gradle
Language : Java
Packaging : war
Dependencies : spring web, lombok
나머지는 있는 그대로 만들자!
ide 툴로 해당 폴더의 build.gradle을 open 해준다.
생성된 gradle 코드는 다음과 같다.
plugins {
id 'org.springframework.boot' version '2.5.4'
id 'io.spring.dependency-management' version '1.0.11.RELEASE'
id 'java'
id 'war'
}
group = 'start'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = '11'
configurations {
compileOnly {
extendsFrom annotationProcessor
}
}
repositories {
mavenCentral()
}
dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web'
compileOnly 'org.projectlombok:lombok'
annotationProcessor 'org.projectlombok:lombok'
providedRuntime 'org.springframework.boot:spring-boot-starter-tomcat'
testImplementation 'org.springframework.boot:spring-boot-starter-test'
}
test {
useJUnitPlatform()
}
2. @ServeletComponent 등록
ServletApplication.java (start.io 에서 입력한 name에 따라 이름이 다르다!)
@SpringBootApplication
@ServletComponentScan
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
}
3. HttpServlet 생성
서블릿이 오면 전담할 클래스가 필요하다.
@WebServlet(name = "ServletTest", urlPatterns = "/servlet")
public class HttpServletTest extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.service(req, resp);
}
};
- urlPatterns에 맞추어 http 요청이 들어오면 서블릿 컨테이너는 해당 클래스의 service 메서드를 실행한다.
- 이때, http의 내용을 파싱 하여 HttpServletRequest, HttpServletResponse 객체로 넘겨준다.
그럼 해당 Request와 Response를 확인해보자.
HttpServletRequest 확인하기
Request는 사용자의 요청을 말한다. 여기에서는 Http 내용을 말한다!
코드는 다음과 같이 구성했다.
HttpServletTest.java
@WebServlet(name = "ServletTest", urlPatterns = "/servlet")
public class HttpServletTest extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("request : " + req);
System.out.println("parameter : " + req.getParameter("id"));
System.out.println("ContextPath : " + req.getContextPath());
System.out.println("Cookies : " + req.getCookies());
System.out.println("Method : " + req.getMethod());
System.out.println("RequestURI : " + req.getRequestURI());
System.out.println("ContentLength : " + req.getContentLength());
}
};
이제 크롬을 켜서 다음 uri로 요청을 보내보자!
http://localhost:8080/servlet?id=abc123
그리고 콘솔창을 확인해보자.
request : org.apache.catalina.connector.RequestFacade@1787a475
parameter : abc123
ContextPath :
Cookies : null
Method : GET
RequestURI : /servlet
ContentLength : -1
위와 같이 콘솔창에 출력되는 것을 확인할 수 있다.
그렇다. 서블릿 컨테이너가 http 요청을 알아서 올바르게 잘라준다.
우리는 get@()만 호출하면 원하는 데이터를 얻을 수 있다!
너무 편하다!
HttpServletResponse
그럼 반대로 우리가 Http 형식으로 String을 만들어야 한다.
이 또한 만만치 않은 작업이다. 띄어쓰기, 알파벳, 대소문자 중에 1개라도 틀리면 올바른 요청이 아니기 때문이다!
그래서 이번에도 서블릿 컨테이너를 통해 Http Response를 생성해보자!
코드는 다음과 같다.
HttpServletTest.java
@WebServlet(name = "ServletTest", urlPatterns = "/servlet")
public class HttpServletTest extends HttpServlet {
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("response : " + resp);
resp.setContentType("text/plain");
System.out.println("set content-type : " + resp.getContentType());
}
};
그럼 다음 내용으로 요청하고 콘솔창을 보자!
http://localhost:8080/servlet
크롬 브라우저를 통해서 http response를 살펴보았다.
다음과 같은 내용이 왔다.
Request URL: http://localhost:8080/servlet
Request Method: GET
Status Code: 200
Remote Address: [::1]:8080
Referrer Policy: strict-origin-when-cross-origin
Connection: keep-alive
Content-Length: 0
Content-Type: text/plain
Date: Thu, 09 Sep 2021 08:33:42 GMT
Keep-Alive: timeout=60
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9
Accept-Encoding: gzip, deflate, br
Accept-Language: ko-KR,ko;q=0.9,en-US;q=0.8,en;q=0.7
Connection: keep-alive
Host: localhost:8080
sec-ch-ua: "Google Chrome";v="93", " Not;A Brand";v="99", "Chromium";v="93"
sec-ch-ua-mobile: ?0
sec-ch-ua-platform: "Windows"
Sec-Fetch-Dest: document
Sec-Fetch-Mode: navigate
Sec-Fetch-Site: none
Sec-Fetch-User: ?1
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/93.0.4577.63 Safari/537.36
정말 길다..
서블릿 컨테이너가 저 많은 내용을 알아서 붙여서 보내주었다!
정말 편리하다.
위에서 확인했듯이, 서블릿 컨테이너를 이용함으로 인해서 http 요청 및 http 응답을 아주 편하게 이용할 수 있다.
'Bank-End > Spring Boot' 카테고리의 다른 글
[#5 Spring Boot 정주행] HTTP로 HTML을 응답해보자! (0) | 2021.09.10 |
---|---|
[#4 Spring Boot 정주행] Http에 대해서 알아보자! (0) | 2021.09.10 |
[#2 Spring Boot 정주행] 웹 기본 구조, 서블릿, HTTP (0) | 2021.09.09 |
[#1 Spring Boot 정주행] Spring & Spring Boot가 무엇인가? (0) | 2021.09.09 |
[Spring Boot] Model 과 ModelAndView 차이. (1) | 2021.08.04 |