【问题标题】:How to configure AJAX/JSON in Spring (with Jackson)?如何在 Spring 中配置 AJAX/JSON(使用 Jackson)?
【发布时间】:2017-02-17 15:33:08
【问题描述】:

我已经问过如何在here 上使用 Spring MVC 重新加载 JSP 页面的特定部分。
我需要使用 AJAX 将一个值传递给我的控制器,但这并没有真正起作用。但我可以在没有 JSON 的情况下解决它。

我想要什么?

我希望能够将此确切值作为 JSON 字符串传递,因为无论如何我都需要让 JSON 为更多功能工作,而且我很好奇为什么它对我不起作用。

目前我收到错误:415(不支持的媒体类型)

我的代码:

MainController.java

@RestController
public class MainController {
    // Delivers the refresh-information for the ajax request, when the detail view gets reloaded
    @RequestMapping(value = "/refreshDetail", method = RequestMethod.POST, consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.TEXT_HTML_VALUE)
    private ModelAndView refreshDetailView(@RequestBody IdObject id, ModelMap model){

        DetailViewBean dvb = Dao.getDetailViewData(id.getId());
        model.addAttribute("detailSearchResultPerson", SupportMethods.getDetailViewDataRecordsPerson(dvb));
        model.addAttribute("detailSearchResultCompany", SupportMethods.getDetailViewDataRecordsCompany(dvb));
        /*
        getDetailViewDataRecords: Array of single Data Records (Label & Data)
        getDetailViewData: Bean with fetched Data from the DB
        */

        return new ModelAndView("detailView", model);
    }

}

main.js(ajax 请求)

$.ajax({
    type: "POST",
    accept:"text/html",
    contentType: "json/application;charset=UTF-8",
    dataType: "html",
    url: "/refreshDetail",
    data: JSON.stringify({"id": id}),
    success: function(response) {
        $(".containerDetailView").html(response);
    }
});

IdObject.java

public class IdObject {
    int id;

    public IdObject(int id) {
        this.id = id;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

WebInit.java

protected Class<?>[] getRootConfigClasses() {
    return new Class<?>[]{RootConfig.class};
}

protected Class<?>[] getServletConfigClasses() {
    return new Class<?>[]{WebConfig.class};
}

protected String[] getServletMappings() {
    return new String[]{"/"};
}

pom.xml

<dependency>
    <groupId>org.springframework</groupId>
    <artifactId>spring-webmvc</artifactId>
    <version>4.3.6.RELEASE</version>
</dependency>

...

<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.8.6</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-core</artifactId>
    <version>2.8.6</version>
    <scope>compile</scope>
</dependency>
<dependency>
    <groupId>com.fasterxml.jackson.dataformat</groupId>
    <artifactId>jackson-dataformat-xml</artifactId>
    <version>2.8.6</version>
</dependency>

我尝试了什么?

我尝试像这样配置 WebInit.java

public void onStartup(ServletContext container) {
    // Create the 'root' Spring application context
    AnnotationConfigWebApplicationContext rootContext =
            new AnnotationConfigWebApplicationContext();
    rootContext.register(WebConfig.class);

    // Manage the lifecycle of the root application context
    container.addListener(new ContextLoaderListener(rootContext));

    // Create the dispatcher servlet's Spring application context
    AnnotationConfigWebApplicationContext dispatcherContext =
            new AnnotationConfigWebApplicationContext();
    dispatcherContext.register(RootConfig.class);

    // Register and map the dispatcher servlet
    ServletRegistration.Dynamic dispatcher =
            container.addServlet("dispatcher", new DispatcherServlet(dispatcherContext));
    dispatcher.setLoadOnStartup(1);
    dispatcher.addMapping("/");
}

但这并没有改变什么。

然后我也尝试自己配置 Spring Message Converters,但这也没有帮助。

我不觉得 AJAX 请求有什么问题,或者我在 Controller 中如何处理它,但如果有,请指出。

如果有人可以就如何解决这个问题给我任何建议,将不胜感激(:

【问题讨论】:

  • 在你的 ajax 请求中你设置了"json/application;charset=UTF-8",但是在控制器中你设置了MediaType.APPLICATION_JSON_VALUE。尝试用这个替换你的控制器:produces = MediaType.APPLICATION_JSON_UTF8_VALUE
  • 嘿@amicoderozer - 感谢您的回答,并为我迟到的回复感到抱歉。我试过了,但仍然得到完全相同的结果和错误消息 415。知道还有什么问题吗?
  • 我尝试了一切,我添加了 jackson 映射器库,我向 IdObject 类添加了默认构造函数,更改了 refreshDetail 方法的参数,我向您的请求添加了标头并更改了接受和内容类型,但我可以' t设法让它工作。对不起。如果你解决了,请告诉我,以及你是如何做到的。
  • @amicoderozer - 所以我尝试了一些方法并意识到通过添加headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' }, 错误会更改为406(不可接受)。我似乎也找不到解决方案..

标签: java jquery json ajax spring


【解决方案1】:

你可以试试这个 ajax 函数,它可以与 spring 一起使用

    $.ajax({
            url: "/refreshDetail",
            method: "POST",
            dataType: 'json',
            data: JSON.stringify({"id": id}),
            success: function (data) {
               $(".containerDetailView").html(response);
            },
            error: function (data) {

            }
        }) 

发送JSON时dataType不能是html

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2019-06-07
    • 2016-01-28
    • 1970-01-01
    • 2011-08-26
    • 2019-04-11
    相关资源
    最近更新 更多