서블릿에서 HTTP Request Body 읽기

 

HTTP Request로 넘어온 값들 중 일부는

getParameter()나 getParameterValues()로 읽을 수 없는 경우가 있다. 

 

POST 메서드를 사용하면서 CONTENT-TYPE이 "application/json" 형식일 때 발생하는데, 

이를 RequestBody post data라고 하며 이러한 값은 

Request.getInputStream() 혹은 Request.getReader()를 통해 직접 읽어와야 한다고 한다.

 

아래 ajax에서 전송한 값은 RequestBody post data이다. 

<script type="text/javascript">
  $(document).ready(function() {
    $.ajax({
      type: "post",
      url: "<%=request.getContextPath()%>/ajaxtest.action?id=1",
      data: '[{"name1":"value1", "name2":"value2"}, {"name1":"value3", "name2":"value4"}]',
      dataType: "json",
      contentType: 'application/json; charset=utf-8',
      success: function(data) {
        ob = data;
      },
      error: function(jqXHR, textStatus, errorThrown) {
        console.log(jqXHR);
        console.log(textStatus);
        console.log(errorThrown);
      }
    });
  });
</script>

 

Servlet 에서 아래처럼 작성하여 읽을 수 있다.

package com.test;
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
public class Dispatcher extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
 
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        process(req, resp);
    }
 
    protected void process(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        System.out.println(getBody(req));
    }
    
    public static String getBody(HttpServletRequest request) throws IOException {
 
        String body = null;
        StringBuilder stringBuilder = new StringBuilder();
        BufferedReader bufferedReader = null;
 
        try {
            InputStream inputStream = request.getInputStream();
            if (inputStream != null) {
                bufferedReader = new BufferedReader(new InputStreamReader(inputStream));
                char[] charBuffer = new char[128];
                int bytesRead = -1;
                while ((bytesRead = bufferedReader.read(charBuffer)) > 0) {
                    stringBuilder.append(charBuffer, 0, bytesRead);
                }
            }
        } catch (IOException ex) {
            throw ex;
        } finally {
            if (bufferedReader != null) {
                try {
                    bufferedReader.close();
                } catch (IOException ex) {
                    throw ex;
                }
            }
        }
 
        body = stringBuilder.toString();
        return body;
    }
}

<결과: Console>

[{"name1":"value1", "name2":"value2"}, {"name1":"value3", "name2":"value4"}] 

 

 

 

+ Recent posts