@RequestParam and angularjs $http.post data retrieval

2.4k Views Asked by At

I am trying to send an array

arr=["xxx.yyy","zzz.vvv"]

to spring endpoint like this:

$http.post("url",arr)

spring side:

@PostMapping(value = "url")
    public Set<String> func(@RequestParam(name="arr") String[] arr) {

    }

however I keep on recieveing

org.springframework.web.bind.MissingServletRequestParameterException: Required String[] parameter 'arr' is not present

how can I acces the array by the parameter name? I need to send a few arrays, so I assume they could be referenced by their names, however @RequestParam doesn't seem to work

6

There are 6 best solutions below

0
On BEST ANSWER

From what I see from the spring documentation:

@RequestParam is for URL query parameters

@RequestBody is for parameters from body

As post send the information in the request body, try using the latest one:

@PostMapping(value = "url")
public Set<String> func(@RequestBody String[] arr) {

}

You may also need to modify the angular part as:

$http.post("url",{arr: arr})
0
On

Second parameters should be an object, array and secondArray represent the name of the parameters. yourArray and anotherArray will be your array inside the Angular App.

$http.post(url', {
           array: yourArray,
           secondArray: anotherArray,
    });

Then, on your BE side, you will refer to those value as array and secondArray as well.

0
On

You need to create a params object with arr as the key:

var params = {
    'arr': ["xxx.yyy","zzz.vvv"]
};

$http.post("url", params);
0
On

To send multiple arrays trough a post there should be an object on the spring side, e.g. ArrayWrapper that will hold 3 arrays and then an ArrayWrapper object should be sent trough angular, if you're using a library like jackson it will convert the object from requestbody to proper java object you can further process.

0
On
arr=["xxx.yyy","zzz.vvv"]
var sendData = {data:arr};

$http.post("url", sendData);

In spring you can get sendData. And when you are going to fetch values, you should give the key or index. Ex. arr[0], arr.name

0
On

Angular:

getUsuarioId(id:number): Observable<Usuario>{
    return this.http.post<Usuario>(`${this.url}usuarioId`, id, {headers: {'Content-Type':'application/json', 'id': `${id}`}} )
}

Java:

@PostMapping("/usuarioId")
public Usuario getUserId(@RequestHeader  Integer id) {
    return usuarioService.findByIdUsuario(id);
}

You can change the id variable to a json, as follows:

getUsuarioId(id:number): Observable<Usuario> {
    let params  = {
      'Content-Type':'application/json',
      'id':`${id}`
    }
    return this.http.post<Usuario>(`${this.url}usuarioId`, params, {headers: params})
}