@ServletComponentScan
@SpringBootApplication
public class ServletApplication {
public static void main(String[] args) {
SpringApplication.run(ServletApplication.class, args);
}
}
@WebServlet(name = "helloServlet", urlPatterns = "/hello")
public class HelloServlet extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("request = " + request);
System.out.println("response = " + response);
String username = request.getParameter("username");
System.out.println("username = " + username);
// http 헤더 정보
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
// http 메시디 바디 정보
response.getWriter().write("hi");
}
}
logging.level.org.apache.coyote.http11=debug
클라이언트의 HTTP 요청
WAS가 request, response 객체를 생성하여 요청 URL에 해당하는 서블릿에 전달, 서블릿 호출
service 메소드를 실행하고 response 객체에 처리한 데이터를 담음
WAS가 response 객체 정보를 기반으로 HTTP 응답 메시지 생성
클라이언트에게 HTTP 응답
HTTP 요청 메시지를 파싱
해서 HttpServletRequest 객체에 담아서 제공
GET /search?q=hello&hi=ko HTTP/1.1
URL()
URI()
Host: www.google.com
content-type
클라이언트 → 서버
데이터 전송 방법 3가지절대 이 3가지 방법을 벗어나지 않는다!
GET
쿼리 파라미터쿼리 파라미터
에 데이터를 포함해서 전달가장 많이 사용
username
=kim&username
=joo → kim 반환POST
HTML Formcontent-type
: application/x-www-form-urlencoded쿼리 파라미터 형식
으로 전달API
메시지 바디ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
JSON
Spring MVC는 기본으로 JSON 변환 라이브러리로 Jackson
라이브러리(ObjectMapper
)를 제공
private ObjectMapper objectMapper = new ObjectMapper();
ServletInputStream inputStream = request.getInputStream();
String messageBody = StreamUtils.copyToString(inputStream, StandardCharsets.UTF_8);
HelloData helloData = objectMapper.readValue(messageBody, HelloData.class);
System.out.println("helloData.userName : " + helloData.getUserName());
System.out.println("helloData.age : " + helloData.getAge());
objectMapper.readValue
(String, 타입);
HTTP 응답 메시지를 만드는데 사용
HTTP 응답 메시지
HTTP/1.1 200 OK
response.setStatus(HttpServletResponse.SC_OK);
Content-Type: text/html;charset=UTF-8
Content-Length: 3423
response.setHeader(”Content-Type”, “text/plain;charset=utf-8”);
PrintWriter writer = response.getWriter();
writer.write("ok");
// = response.setHeader("Content-Type", "text/plain;charset=utf-8");
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
// = response.setHeader("Set-Cookie", "myCookie=good; Max-Age=600");
Cookie cookie = new Cookie("myCookie", "good");
cookie.setMaxAge(600); //600초
response.addCookie(cookie);
//response.setStatus(HttpServletResponse.SC_FOUND); //302
// = response.setHeader("Location", "/basic/hello-form.html");
response.sendRedirect("/basic/hello-form.html");
response.setContentType("text/plain");
response.setCharacterEncoding("utf-8");
PrintWriter writer = response.getWriter();
writer.write("ok");
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>");
response.setContentType("application/json");
response.setCharacterEncoding("utf-8");
HelloData helloData = new HelloData();
helloData.setUserName("Kim");
helloData.setAge(20);
String result = objectMapper.writeValueAsString(helloData);
response.getWriter().write(result);
writeValueAsString
(…);💡 InputStream ——StreamUtils.copyToString()——> String(JSON) ——objectMapper.readValue
()——> Object
💡 Object——objectMapper.writeValueAsString
()——>String(JSON)