Igor Shashkin Igor Shashkin - 6 months ago 96
Java Question

Send empty array from ajax to jersey web server

I try to send array of integers from ajax to jersey web service.

javascript

var myFoods = [];

// adding items via push

$.ajax({
url: "ws/food/" + idParam + "/recomendation",
type: "POST",
data: {'foods[]': myFoods,
async: false,
});


web service

@POST
@Path("/{id}/recomendation")
public void updateRecomendations(
@PathParam("id")
Long id,

@FormParam("foods[]")
List<Long> recomendedFoodIds
) {
...
}


With non empty arrays this code work good but if myFoods is empty i have error

"HTTP Status 500 - java.lang.IllegalStateException: The @FormParam is utilized when the content type of the request entity is not application/x-www-form-urlencoded"


How to fix it?

Answer

I solved the problem with this:

@POST
@Path("/{id}/recomendation")
public void updateRecomendations(
        Form form,

        @PathParam("id")
        Long id
        ) {
        List<Long> foods = getFoodIdsFromForm(form);

        ...
    }

private List<Long> getFoodIdsFromForm(Form form) {
    Map parametrsMap = form.asMap();
    final List<Long> foodIds = new ArrayList<Long>();
    if (parametrsMap.get("foods[]") != null) {
        List<String> idsString = (List<String>)parametrsMap.get("foods[]");
        for (String id : idsString) {
            foodIds.add(Long.parseLong(id));
        }
    }

    return foodIds;
}
Comments