Ahmad
Ahmad

Reputation: 1474

How to receive form parameters values in server?

i have React JS application where i send post request to server with form submission using axios library.

client request:

sendData(data,price) {
    axios.post('http://localhost:8080/SampleJavaAPP/UserServer', {
    item: data,//these value
    price:price//these value
  })
  .then(function (response) {
      console.log(response);
  })
  .catch(function (error) {
    console.log(error);
  });
  }

i am not sure how to get these values into server i am doing in server for getting value like this

String name = request.getParameter("item");
        String price = request.getParameter("price");

        System.out.println("Result "+name + price);

But it gives null values in server. how to receive these values parameters in server?

Upvotes: 3

Views: 3287

Answers (3)

Ben Cheng
Ben Cheng

Reputation: 777

Request Body is not retrieved by request.getParameter(). You need to retrieve it by request.getReader().

String body = IOUtils.toString(request.getReader());

It is suggested to use Apache Commons IO to get Content first. As your request is in JSON format. You can use Jackson to convert the String into Map.

Map<String, String> map = mapper.readValue(body, new TypeReference<Map<String, String>>(){});
System.out.println(map.get("item"));
System.out.println(map.get("price"));

Upvotes: 1

Atul Sharma
Atul Sharma

Reputation: 10720

As Axios is sending Json data you will not be able to read its direct. There are 2 possible solutions:

  1. Either send data as form-data.

  2. Read & Parse JSON at servlet:

    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());
            String price = jsonObject.get("price"); // will return price value.
        } catch (JSONException e) {
            throw new IOException("Error parsing JSON request string");
        }
    }
    

Upvotes: 1

Herr Derb
Herr Derb

Reputation: 5387

request.getParameter()is referring to URL parameters ->myurl?someparameter=1

By doing request.getParameter("item"), your URL would need to look like http://localhost:8080/SampleJavaAPP/UserServer?item=myitem

What you are actually doing here

sendData(data,price) {
    axios.post('http://localhost:8080/SampleJavaAPP/UserServer', {
    item: data,//these value
    price:price//these value
}

is adding the objects to the request body, which is IMHO correct. There for you won't find any parameters item or price on your server side request object.

What you need to do, is to parse the requests body. With request.getInputStream() you can get the Inputstream. I suggest you use an object mapper which makes that really easy. See Intro to the Jackson ObjectMapper

In your servlet, you do something like this:

ObjectMapper objectMapper = new ObjectMapper();
MyItem myItem = objectMapper.readValue(request.getInputStream(), MyItem.class);

public class MyItem{

    String price;
    String item;

    public void setItem(String item) {
        this.item = item;
    }

    public void setPrice(String price) {
        this.price = price;
    }

    public String getItem() {
        return item;
    }

    public String getPrice() {
        return price;
    }

}

Upvotes: 0

Related Questions