I have a Spring Boot app I'm writing that uses Angular for the front end.
One REST API accepts an array of strings as input:
@RequestMapping(value = "/import", method = RequestMethod.POST)
@CrossOrigin
public void importComicFiles(@RequestParam("filenames") String[] filenames)
{
for (String filename : filenames) { ... }
}
When the front end sends an array of string values using the following:
importFiles(filenames: string[]): Observable<Response> {
const formData: FormData = new FormData();
for (let index = 0; index < filenames.length; index++) {
formData.append('filenames', filenames[index]);
}
return this.http.post(`${this.apiUrl}/files/import`, formData);
}
then the Java code receives each string as a separate element in the array. Even if those strings have spaces in them.
HOWEVER, when the importFiles method is called with a single string then the Java code behaves as if the value received is an array spit on a single space at the end of the string. An example input string is:
/Users/mcpierce/Google Drive/comics/DC/2018-01-17/Superman Vol.2016 #39 (March, 2018).cbz
Java treats this string as if it were two strings:
/Users/mcpierce/Google Drive/comics/DC/2018-01-17/Superman Vol.2016 #39 (March,
and
2018).cbz
If I change the Java code to just treat the filenames parameter as a string (rather than as a List or a String[]) then I get the whole string. If it's more than one then each is separated by a common (,).
Any ideas?
I would say Spring is operating just fine. But the way we use the request params is wrong. Spring delimits the request parameters and injects as array.
GET http://example.com?filenames=1,2,3,4
Above can be injected into @RequestParam("filenames[]") String[] filenames
with each one entry in array.
In your case it would be treated as different entries coz of the comma. Try posting it as request body object instead as a request param and use to get the array?
您也可以尝试在参数值中添加[]。
@RequestParam("filenames[]") String[] filenames
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.