Java 将restful ajax请求映射到spring

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2828968/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 13:21:44  来源:igfitidea点击:

Mapping restful ajax requests to spring

javaajaxspringspring-mvcrest

提问by Diones

I have this piece of code:

我有这段代码:

@RequestMapping(value = "/test.json", method = RequestMethod.GET)
@ResponseStatus(HttpStatus.OK)
public @ResponseBody Object[] generateFile(@RequestParam String tipo) {
    Object[] variaveis = Variavel.getListVariavelByTipo(tipo);
    return variaveis;
}

As far as I know it should take a request to test.json?tipo=H and return the JSON representation of Variavel[], however when I make such request I get:

据我所知,它应该请求 test.json?tipo=H 并返回 Variavel[] 的 JSON 表示,但是当我提出这样的请求时,我得到:

HTTP Status 406 -

HTTP 状态 406 -

type Status report

类型状态报告

message

信息

descriptionThe resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers ()

描述此请求标识的资源只能生成具有根据请求“接受”标头不可接受的特征的响应 ()

By using the following function I can get the expected json:

通过使用以下函数,我可以获得预期的 json:

@RequestMapping(value = "/teste.json")
public void testeJson(Model model, @RequestParam String tipo) {
    model.addAttribute("data", Variavel.getListVariavelByTipo("H"));
}

What I'm doing wrong?

我做错了什么?

采纳答案by axtavt

@RequestBody/@ResponseBodyannotations don't use normal view resolvers, they use their own HttpMessageConverters. In order to use these annotations, you should configure these converters in AnnotationMethodHandlerAdapter, as described in the reference(you probably need MappingHymansonHttpMessageConverter).

@RequestBody/@ResponseBody注释不使用普通的视图解析器,它们使用自己的HttpMessageConverters。为了使用这些注释,您应该在 中配置这些转换器AnnotationMethodHandlerAdapter,如参考所述(您可能需要MappingHymansonHttpMessageConverter)。