尝试将阵列发送到spring mvc控制器时出现“Bad Request”

时间:2012-10-20 00:31:39

标签: java jquery spring spring-mvc

我看到了相关的问题,并尝试了那些没有帮助的人。我正在用这样的jquery发送POST请求:

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() {
        })

在控制器方面,我尝试过:

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
        }

这些都不起作用我想知道我做错了什么,无论我做什么Bad request

3 个答案:

答案 0 :(得分:1)

您的状态参数应为@RequestParam(value = "status[]") String[] status(春季3.1)。

答案 1 :(得分:1)

我也遇到了错误请求的相同问题。我通过以下代码解决了这个问题 您可以通过 JSON.stringify(array)将数组转换为json字符串,将数组发布到控制器。
我已经使用 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");

控制器:
您可以使用jackson处理json字符串 Jackson是一个高性能的JSON处理器Java库。

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

注意:请确保您的dto应包含与使用数组对象发布时相同的变量名称 在我的例子中,我的dto包含firstName,lastName作为发布数组对象。

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>

答案 2 :(得分:0)

我认为您的问题可能是将数组发送到您必须多次实际发送param的内容。

在GET操作的情况下,例如:?status = FOO&amp; status = BAR

我不确定spring会自动将逗号分隔的字符串转换为数组。但是,您可以添加PropertyEditor(请参阅PropertyEditorSupport)以在逗号上拆分字符串。

@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());
            }
        }

    });
}

请注意,我正在使用commons-lang来加入和拆分字符串,但您可以轻松地使用您想要的任何方式自行完成。

执行此操作后,只要您希望从单个字符串绑定到String []的参数,spring就会自动为您转换它。