简体   繁体   中英

Cannot bind data to ModelAttribute list properties in spring mvc

I'm using spring mvc and ajax to request data from server

This is my ModelAttribute class

@Data
public class PromotionSettingCriteria extends BaseRequest{

    private Long[] promotionIds;

    private Long promotionId;

}

This is my ajax request

$.ajax({
                url: path + '/promotion/setting/search.htm',
                type: 'POST',
                data: {
                    promotionIds: promotionIds,
                    promotionId: promotionIds[0],
                },
                success: function (response) {
                    let settingResponse = JSON.parse(response);
                    console.log('Promotion setting', response);
                    if (settingResponse.status == '1') {
                        // console.log(response)
                    }
                },
                error: function () {
                    console.log("Promotion setting error");
                }
            })

The Controller class

@Controller
@RequestMapping("/promotion")
public class PromotionController extends BaseController {
@RequestMapping(value = "/setting/search", method = RequestMethod.POST)
    @ResponseBody
    public Object searchPromotionSetting(HttpServletRequest request,@ModelAttribute PromotionSettingCriteria criteria) {

        try{

            Map<String, Object> requestParams = getRequestParams(request);

            if (criteria != null && criteria.getPromotionIds() == null){
                throw new ServiceException("Promotion Setting Criteria Cannot be NULL");
            }

            List<PromotionSetting> resultData = promotionSettingService.getPromotionSettingByCriteria(criteria);

            return RequestUtil.createSuccessResponse(resultData);

        }catch (Exception e){
            return RequestUtil.createFailResponse(e);
        }

    }
}

This is part of the request from browser在此处输入图像描述

when I am not passing promotionIds, the controller works fine and bind the promotionId property But when I passing promotionIds it shows java.lang.NumberFormatException: For input string: ""

[analyze][DEBUG] [2020-07-31 17:35:18] org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(134) | Resolving exception from handler [com.analyze.controller.PromotionController@1af465c7]: java.lang.NumberFormatException: For input string: ""
[analyze][DEBUG] [2020-07-31 17:35:18] org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(134) | Resolving exception from handler [com.analyze.controller.PromotionController@1af465c7]: java.lang.NumberFormatException: For input string: ""
[analyze][DEBUG] [2020-07-31 17:35:18] org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(134) | Resolving exception from handler [com.analyze.controller.PromotionController@1af465c7]: java.lang.NumberFormatException: For input string: ""
[analyze][DEBUG] [2020-07-31 17:35:18] org.springframework.web.servlet.FrameworkServlet.processRequest(989) | Could not complete request
java.lang.NumberFormatException: For input string: ""

How can I let controller bind the list property in the ModelAttribute class?

Update your ajax request

$.ajax({
    url: path + '/promotion/setting/search.htm',
    type: 'POST',
    contentType: "application/json",
    data: JSON.stringify({
        promotionIds: promotionIds,
        promotionId: promotionIds[0],
    }),
    dataType: "json",
    success: function (response) {
        let settingResponse = JSON.parse(response);
        console.log('Promotion setting', response);
        if (settingResponse.status == '1') {
            // console.log(response)
        }
    },
    error: function () {
        console.log("Promotion setting error");
    }
})

Also, you need to update your Controller method, replace @ModelAttribute with @RequestBody

@RequestMapping(value = "/setting/search", method = RequestMethod.POST)
@ResponseBody
public Object searchPromotionSetting(HttpServletRequest request, @RequestBody PromotionSettingCriteria criteria) {
    // your code here
}
  • content-type: "application/json" indicas that you are going to send json
  • dataType: "json" you are expecting json as a response
  • data: JSON.stringify({...}) converting your js object to string

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM