In your web application, you're sending a POST request to a specific URL with JSON data, and you're using HttpServletRequest to access the POST data. However, when you enumerate the request parameters, you can only find the "cmd" parameter but not the JSON data.
Typically, you can obtain GET and POST parameters in a servlet using the request.getParameter("paramName") method. This works well when the POST data is encoded as key-value pairs with a content type of "application/x-www-form-urlencoded," as seen in standard HTML forms.
In your case, since you're sending a JSON data stream, you need to employ a custom decoder to process the raw data stream accessible from request.getReader(). Here's an example of how you can handle JSON POST processing:
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { StringBuffer jb = new StringBuffer(); String line = null; try { BufferedReader reader = request.getReader(); while ((line = reader.readLine()) != null) jb.append(line); } catch (Exception e) { /*report an error*/ } try { JSONObject jsonObject = HTTP.toJSONObject(jb.toString()); } catch (JSONException e) { // crash and burn throw new IOException("Error parsing JSON request string"); } // Work with the data using methods like... // int someInt = jsonObject.getInt("intParamName"); // String someString = jsonObject.getString("stringParamName"); // JSONObject nestedObj = jsonObject.getJSONObject("nestedObjName"); // JSONArray arr = jsonObject.getJSONArray("arrayParamName"); // etc... }
In summary, if you're dealing with JSON POST data, you need to use a custom decoder to process it directly from the request body, rather than relying on the built-in parameter enumeration mechanism.
The above is the detailed content of How to Retrieve JSON POST Data Using HttpServletRequest?. For more information, please follow other related articles on the PHP Chinese website!