3

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?

Muntasir
  • 798
  • 1
  • 14
  • 24
Ahmad
  • 1,462
  • 5
  • 17
  • 40
  • Have you tried console.log(data, price) just before your post request, to clarify where the issue comes from? – Yann Pellegrini Apr 05 '18 at 12:59
  • yes values are printing in console but it gives null in the server... – Ahmad Apr 05 '18 at 13:01
  • 1
    What are you using to write your server-side software? Note that it does not matter that you make the request with React. All clients will make the HTTP request in the exact same way no matter what language or framework they use. – Code-Apprentice Apr 05 '18 at 14:29
  • i am using java j2EE spring mvc framework for server side...but request is hitting to the server but parameters values are null as i described. – Ahmad Apr 06 '18 at 05:02
  • https://stackoverflow.com/questions/3831680/httpservletrequest-get-json-post-data you are sending json data which you can't read directly as form-data. – Atul Sharma Apr 09 '18 at 09:28
  • https://spring.io/guides/gs/handling-form-submission/ – ThomasRS Apr 09 '18 at 15:14

3 Answers3

1

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");
        }
    }
    
MuratOzkan
  • 2,599
  • 13
  • 25
Atul Sharma
  • 9,397
  • 10
  • 38
  • 65
  • from this line JSONObject jsonObject = HTTP.toJSONObject(jb.toString()); how to import JSONObject and HTTP ?? these are giving – Ahmad Apr 09 '18 at 10:08
  • You need to import corresponding jars.. `org.json` https://mvnrepository.com/artifact/org.json/json for json object – Atul Sharma Apr 09 '18 at 10:16
  • String price = jsonObject.get("price"); this line giving error as jsonObject.get("price") is not saving to price – Ahmad Apr 09 '18 at 10:38
  • 1
    i have done it from littlebit different method...but you gave me idea that axios sending json data so i am able to complete it dat is why i am accepting your answer... – Ahmad Apr 09 '18 at 12:24
1

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"));
Ben Cheng
  • 769
  • 10
  • 25
0

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;
    }

}
Herr Derb
  • 4,977
  • 5
  • 34
  • 62
  • where should i call request.getBody() ?? – Ahmad Apr 09 '18 at 09:14
  • Usually in your servlet. The same location where you did the call `request.getParameter` – Herr Derb Apr 09 '18 at 09:14
  • My bad. It's not `request.getBody()` check my updated answer – Herr Derb Apr 09 '18 at 09:18
  • i am not getting properly what you are trying to say....should i call String price = request.getInputStream("price") ??? i called it but it gives me error. – Ahmad Apr 09 '18 at 09:21
  • A request body is available as an InputStream (See [InputStream](https://docs.oracle.com/javase/7/docs/api/java/io/InputStream.html)), which of course is not castable directly to one of your objects. What you need to do, is to convert this `InputStream` to your objects. For this you will use the object mapper. – Herr Derb Apr 09 '18 at 09:25