Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving JSON Object Literal from HttpServletRequest

I am writing code that needs to extract an object literal posted to a servlet. I have studied the API for the HttpServletRequest object, but it is not clear to me how to get the JSON object out of the request since it is not posted from a form element on a web page.

Any insight is appreciated.

Thanks.

like image 573
DarthMaul Avatar asked Oct 10 '09 18:10

DarthMaul


People also ask

What is a JSON object literal?

JSON object literals are surrounded by curly braces {}. JSON object literals contains key/value pairs. Keys and values are separated by a colon. Keys must be strings, and values must be a valid JSON data type: string.

What is the difference between ServletRequest and HttpServletRequest?

ServletRequest provides basic setter and getter methods for requesting a Servlet, but it doesn't specify how to communicate. HttpServletRequest extends the Interface with getters for HTTP-communication (which is of course the most common way for communicating since Servlets mostly generate HTML).

How do I get a filter body request?

To obtain the request body you have to call getInputStream() . But again, this will make the inputStream unavailable to other filters and the handler.


2 Answers

are you looking for this ?

@Override protected void doPost(HttpServletRequest request, HttpServletResponse response)         throws ServletException, IOException {     StringBuilder sb = new StringBuilder();     BufferedReader reader = request.getReader();     try {         String line;         while ((line = reader.readLine()) != null) {             sb.append(line).append('\n');         }     } finally {         reader.close();     }     System.out.println(sb.toString()); } 
like image 119
user305224 Avatar answered Sep 20 '22 15:09

user305224


This is simple method to get request data from HttpServletRequest using Java 8 Stream API:

String requestData = request.getReader().lines().collect(Collectors.joining()); 
like image 38
Dmitry Stolbov Avatar answered Sep 22 '22 15:09

Dmitry Stolbov