1

I already asked how to reload a specific part of a JSP page with Spring MVC on here.
I needed to pass a value with AJAX to my Controller and that didn't really work. But I could solve it without JSON.

What do I want?

I want to be able to pass this exact value as a JSON string because I'll need to get JSON working for further functions anyway plus I'm curious about why I it doesn't work for me.

At the moment I'm getting the Error: 415 (Unsupported Media Type).

My Code:

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 request)

$.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>

What have I tried?

I tried to configure WebInit.java like that:

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

But that didn't change anything.

Then I also tried to configure the Spring Message Converters myself, but that didn't help as well.

I don't feel like there's anything wrong in the AJAX request, or how I handle it in the Controller but please point it out if there is.

If anyone could give me any advise on how to solve this problem, it would be highly appreciated (:

Community
  • 1
  • 1
Marc Signer
  • 25
  • 1
  • 7
  • in your ajax request you set `"json/application;charset=UTF-8"` but in controller you set `MediaType.APPLICATION_JSON_VALUE`. Try substitute your controller produces with this: `produces = MediaType.APPLICATION_JSON_UTF8_VALUE` – amicoderozer Feb 17 '17 at 15:36
  • Hey @amicoderozer - thanks for your answer and sorry for my late response. I tried that out but still get the exact same result and the error message **415**. Any idea what else could be wrong? – Marc Signer Feb 20 '17 at 07:38
  • Man i tried everything, i added jackson mapper library, i added default constructor to IdObject class, changed the parameter of refreshDetail method, i added header to your request and changed accept and content type but i can't manage to get it working. Sorry. Let me know if you solve, and how you do that. – amicoderozer Feb 20 '17 at 09:11
  • @amicoderozer - so I tried a few things out and realized that by adding `headers: { 'Accept': 'application/json', 'Content-Type': 'application/json' },` the error changes to **406 (Not Acceptable)**. I can't seem to find a solution for this either.. – Marc Signer Feb 20 '17 at 12:27

1 Answers1

0

You can try this ajax function which is compact able with spring

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

            }
        }) 

The dataType should not be html while sending JSON

JRA
  • 392
  • 4
  • 18