从视图中忽略ModelAttribute


问题内容

我有一个休息的应用程序,返回json /
xml。我使用杰克逊和jaxb进行转换。一些方法需要接受query_string。我已经使用@ModelAttribute将query_string映射到一个对象中,但这将对象强制进入了我的视图。我不希望该对象出现在视图中。

我想我需要使用@ModelAttribute以外的其他东西,但是我无法弄清楚如何进行绑定,但是不能修改视图。如果省略@ModelAttribute批注,则该对象将在视图中显示为变量名称(例如:“
sourceBundleRequest”)。

示例网址:

http://localhost:8080/rest/sourcebundles/?updateDate=20100501&label=urgent

控制器方式:

@RequestMapping(value = {"", "/"}, method = RequestMethod.GET)
public String getAll(@ModelAttribute("form") SourceBundleRequest sourceBundleRequest, BindingResult result, ModelMap model) throws ApiException {
    // Detect and report errors.
    if (result.hasErrors()) {
       // (omitted for clarity)
    }

    // Fetch matching data.
    PaginatedResponse<SourceBundle> sourceBundleResponse = null;
    try {
        int clientId = getRequestClientId();
        sourceBundleResponse = sourceBundleService.get(clientId, sourceBundleRequest);
    } catch (ApiServiceException e) {
        throw new ApiException(ApiErrorType.INTERNAL_ERROR, "sourceBundle fetch failed");
    }

    // Return the response.
    RestResponse<PaginatedResponse> restResponse = new RestResponse<PaginatedResponse>(200, "OK");
    restResponse.setData(sourceBundleResponse);
    model.addAttribute("resp", restResponse);
    // XXX - how do I prevent "form" from appearing in the view?
    return "restResponse";
}

示例输出:

"form": {
    "label": "urgent",
    "updateDate": 1272697200000,
    "sort": null,
    "results": 5,
    "skip": 0
},
"resp": {
    "code": 200,
    "status": "OK",
    "data": {
        "totalAvailable": 0,
        "resultList": [ ]
    }
}

所需输出:

"resp": {
    "code": 200,
    "status": "OK",
    "data": {
        "totalAvailable": 0,
        "resultList": [ ]
    }
}

省略@ModelAttribute(“ form”)

如果我只是省略@ModelAttribute(“ form”),我仍然会收到不期望的响应,但是传入的表单由对象名称命名。响应如下所示:

"resp": {
    "code": 200,
    "status": "OK",
    "data": {
        "totalAvailable": 0,
        "resultList": [ ]
    }
},
"sourceBundleRequest": {
    "label": "urgent",
    "updateDate": 1272697200000,
    "sort": null,
    "results": 5,
    "skip": 0
}

问题答案:

不知何故,我错过了最明显的解决方法。我专注于属性,却忘记了只能修改基础Map。

  // Remove the form object from the model map.
  model.remove("form");

如Biju建议的那样,省略@ModelAttribute,然后删除sourceBundleRequest对象,可能会更有效率。我怀疑@ModelAttribute有一些额外的开销。