서블릿
HttpServletRequest
HttpservletRequest 받기
@WebServlet(name = "requestHeaderServlet", urlPatterns = "/request-header")
public class RequestHandler extends HttpServlet {
@Override
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
printStartLine(request);
printHeaders(request);
}
private void printStartLine(HttpServletRequest request){
System.out.println("request.getMethod() = " + request.getMethod());
System.out.println("request.getProtocol() = " + request.getProtocol());
}
private void printHeaders(HttpServletRequest request){
System.out.println("---header start---");
request.getHeaderNames().asIterator()
.forEachRemaining(headerName -> System.out.println(headerName + ": " + headerName));
System.out.println("--- Headers - end ---");
System.out.println();
}
}
- request.InputStream으로 바디를 받을 수 있다.
HttpservletRequest 받아서 json 파싱후 확인
@WebServlet(name = "requestBodyJsonServlet", urlPatterns = "/request-body-json")
public class RequestBodyJsonServlet extends HttpServlet {
private ObjectMapper objectMapper = new ObjectMapper();
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream inputStream = req.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());
resp.getWriter().write("ok");
}
}
- ObjectMapper를 통해 key&value형태의json string을 받을 수 있다.