지금부터 설명할 내용은 API 방식이다! (HTTP API든, Restful API든 기반이 되는 내용)
1️⃣ 단순 텍스트
2️⃣ JSON
✔️ RequestBodyStringServlet
생성
package hello.servlet.basic.request;
import org.springframework.util.StreamUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@WebServlet(name = "requestBodyStringServlet", urlPatterns = "/request-body- string")
public class RequestBodyStringServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// request.getInputStream() : 메시지 바디의 내용을 바이트 코드로 바로 얻을 수 있음
ServletInputStream inputStream = request.getInputStream();
// byte 코드를 우리가 읽을 수 있는 문자(String)로 보려면 문자표 (Charset)를 지정해주어야 함
// 여기서는 UTF_8 Charset을 지정해줌
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
System.out.println("messageBody = " + messageBody);
response.getWriter().write("ok");
}
}
⬆️ postman 에서 결과가 잘 뜨는 것을 확인함 👍🏻 (content-type: text/plain
사용)
이번에는 HTTP API에서 주로 사용하는 JSON 형식으로 데이터를 전달해보자!
📌 JSON 형식 전송
- content-type :
application/json
- message body :
{"username": "hello", "age": 20}
- 결과 :
messageBody = {"username": "hello", "age": 20}
🤚🏻 JSON 형식으로 파싱할 수 있게 본격적인 코드 작성 전에 hello.servlet.basic.HelloData
에서 객체를 하나 생성하자 🤚🏻
✔️ RequestBodyJsonServlet
생성
package hello.servlet.basic.request;
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.servlet.basic.HelloData;
import org.springframework.util.StreamUtils;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
@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");
}
}
⬆️ postman 실행 결과 👍🏻
1️⃣ HTTP 응답 메시지 생성
2️⃣ HTTP 응답코드 지정
3️⃣ 헤더 생성
4️⃣ 바디 생성
hello.servlet.basic.response.ResponseHeaderServlet
생성
package hello.servlet.basic.response;
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.io.PrintWriter;
@WebServlet(name = "responseHeaderServlet", urlPatterns = "/response-header")
public class ResponseHeaderServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 응답 코드 (기본이 200)
response.setStatus(HttpServletResponse.SC_OK);
// 응답 헤더
response.setHeader("Content-Type", "text/plain;charset=utf-8");
response.setHeader("Cache-Control", "no-cache, no-store, must- revalidate");
response.setHeader("Pragma", "no-cache");
response.setHeader("my-header", "hello");
// content 편의 메서드
content(response);
// 쿠키 편의 메서드
cookie(response);
// redirect 편의 메서드
redirect(response);
// 메시지 바디
PrintWriter writer = response.getWriter();
writer.println("ok");
}
private void content(HttpServletResponse response) {
//Content-Type: text/plain;charset=utf-8
//Content-Length: 2
//response.setHeader("Content-Type", "text/plain;charset=utf-8");
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
//response.setContentLength(2); //(생략시 자동 생성)
}
private void cookie(HttpServletResponse response) {
//Set-Cookie: myCookie=good; Max-Age=600;
// response.setHeader("Set-Cookie", "myCookie=good; Max-Age=600");
Cookie cookie = new Cookie("myCookie", "good");
cookie.setMaxAge(600); //600초
response.addCookie(cookie);
}
private void redirect(HttpServletResponse response) throws IOException {
//Status Code 302
//Location: /basic/hello-form.html
//response.setStatus(HttpServletResponse.SC_FOUND); //302
//response.setHeader("Location", "/basic/hello-form.html");
response.sendRedirect("/basic/hello-form.html");
}
}
✔️ HTTP 응답 메시지는 주로 ⬇️아래와 같은 내용⬇️을 담아서 전달한다!
1️⃣ 단순 텍스트 응답
➡️ 앞에서 살펴봤기 때문에 생략함 (writer.println("ok");
)
2️⃣ HTML 응답
3️⃣ HTTP API - MessageBody JSON 응답
✔️ hello.servlet.web.response.ResponseHtmlServlet
생성
package hello.servlet.basic.response;
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;
import java.io.PrintWriter;
@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>");
}
}
⬆️ http://localhost:8080/response-html
로 실행했을 때 결과 👍🏻
📌 HTTP 응답으로 HTML을 반환할 때는 content-type을
text/html
로 지정해야 한다.
✔️ hello.servlet.web.response. ResponseJsonServlet
생성
package hello.servlet.basic.response;
import com.fasterxml.jackson.databind.ObjectMapper;
import hello.servlet.basic.HelloData;
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 = "responseJsonServlet", urlPatterns = "/response-json")
public class ResponseJsonServlet extends HttpServlet {
// Jackson 라이브러리가 제공하는 objectMapper.writeValueAsString() 를 사용하면,
// 객체를 JSON 문자로 변경 할 수 있음
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} 로 바꿔야 함 -> objectMapper 사용!
String result = objectMapper.writeValueAsString(data);
response.getWriter().write(result);
}
}
⬆️ http://localhost:8080/response-json
로 실행했을 때 결과 👍🏻
📌 HTTP 응답으로 JSON을 반환할 때는 content-type을
application/json
로 지정해야 한다.
서블릿은 또 다른 공간이었ㄷr.....^-^*