London
London

Reputation: 15274

"Bad Request" when attempting to send array to spring mvc controller

I saw related questions and tried those none of those helped. I'm sending POST requst with jquery like this :

var data = {};          
            //this works every time and it's not issue
            var statusArray = $("#status").val().split(',');  
            var testvalue = $("#test").val();

                     data.test = testvalue;
            data.status = statusArray ;

             $.post("<c:url value="${webappRoot}/save" />", data, function() {
        })

On the controller side I've tried following :

public void saveStatus(ModelMap model, Principal principal, HttpSession session, final HttpServletResponse response, @RequestParam String test, @RequestBody String [] status) {

        //I never get to this point, but when I set statusArray to required false test variable is being populated correctly
        }


public void saveStatus(ModelMap model, Principal principal, HttpSession session, final HttpServletResponse response, @RequestParam String test, @RequestParam String [] status) {

        //I never get to this point, but when I set statusArray to required false test variable is being populated correctly
        }



public void saveStatus(ModelMap model, Principal principal, HttpSession session, final HttpServletResponse response, @RequestParam String test, @RequestParam("status") String [] status) {

        //I never get to this point, but when I set statusArray to required false test variable is being populated correctly
        }


public void saveStatus(ModelMap model, Principal principal, HttpSession session, final HttpServletResponse response, @RequestParam String test, @RequestParam(name="status") String [] status) {

        //I never get to this point, but when I set statusArray to required false test variable is being populated correctly
        }

none of these worked I'm wondering what I'm doing wrong, whatever I do I get Bad request

Upvotes: 1

Views: 2136

Answers (3)

NikhilK
NikhilK

Reputation: 191

I have also gone through the same problem of Bad request. I resolved it by doing the following code.
You can post an array to a controller by converting it into json string by JSON.stringify(array).
I have pushed muliple Objects into an array using push().

    var a = [];
    for(var i = 1; i<10; i++){
        var obj = new Object();
        obj.name = $("#firstName_"+i).val();
        obj.surname = $("#lastName_"+i).val();
        a.push(obj);
    }

    var myarray = JSON.stringify(a);
    $.post("/ems-web/saveCust/savecustomers",{myarray : myarray},function(e) {

    }, "json");

Controller :
You can use jackson for processing json string.
Jackson is a High-performance JSON processor Java library.

    @RequestMapping(value = "/savecustomers", method = RequestMethod.POST)
    public ServiceResponse<String> saveCustomers(ModelMap model, @RequestParam String myarray) {

        try{
            ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY, true); 
            List<DtoToMAP> parsedCustomerList = objectMapper.readValue(myarray, new TypeReference<List<DtoToMAP>>() { });
            System.out.println(" parsedCustomerList :: " + parsedCustomerList);
        }catch (Exception e) {  
            System.out.println(e);
        }
    }

Note : make sure that your dto should contain same variable name as you are posting with an array object.
in my case, my dto contains firstName,lastName as am posting with an array object.

Jackson Dependancy :

    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-core-asl</artifactId>
        <version>1.9.3</version>
    </dependency>
    <dependency>
        <groupId>org.codehaus.jackson</groupId>
        <artifactId>jackson-mapper-asl</artifactId>
        <version>1.9.3</version>
    </dependency>

Upvotes: 1

Matt
Matt

Reputation: 11805

I think your problem might be that to send an array to something you have to actually send the param multiple times.

In the case of a GET operation something like: ?status=FOO&status=BAR

I'm not sure spring would convert a comma separated string to an array for you automagically. You could however, add a PropertyEditor (see PropertyEditorSupport) to split the string on commas.

@InitBinder
public void initBinder(WebDataBinder binder) {
   binder.registerCustomEditor(String[].class, new PropertyEditorSupport() {
        @Override
        public String getAsText() {
            String value[] = (String[]) getValue();
            if (value == null) {
                return "";
            }
            else {
                return StringUtils.join(value, ",");
            }
        }

        @Override
        public void setAsText(String text) throws IllegalArgumentException {
            if (text == null || text.trim().length() == 0) {
                setValue(null);
            }
            else {
                setValue(StrTokenizer.getCSVInstance(text).getTokenArray());
            }
        }

    });
}

Note, i'm using commons-lang to both join and split the string, but you could easily just do it yourself using any means you want.

Once you do this, any time you want a parameter bound to a String[] from a single string, spring will automatically convert it for you.

Upvotes: 0

Pao
Pao

Reputation: 843

Your status param should be @RequestParam(value = "status[]") String[] status (Spring 3.1).

Upvotes: 1

Related Questions