Returning a simple map structure from spring mvc controller in ajax

I am using spring mvc 4 and trying to return a simple map in ajax - from my controller to a jsp file.

Controller:

  @RequestMapping(value = "/ajaxtest", method = RequestMethod.GET) public @ResponseBody Map<String, String> myTest() { System.out.println("------------------------------------test"); Map<String,String> myMap = new HashMap<String, String>(); myMap.put("a", "1"); myMap.put("b", "2"); return myMap; } 

Ajax from jsp file:

 function testAjax() { $.ajax({ url : '../../ajaxtest.html', dataType: "json", contentType: "application/json;charset=utf-8", success : function(data) { alert("1"); alert(data); } }); } 

But I am not getting a warning, but just an HTTP/1.1 406 Not Acceptable error.

However, changing the code to return a simple string works fine. Controller:

  @RequestMapping(value = "/ajaxtest", method = RequestMethod.GET) public @ResponseBody String myTest() { System.out.println("------------------------------------test"); return "hello"; } 

Ajax:

 function testAjax() { $.ajax({ url : '../../ajaxtest.html', success : function(data) { alert("1"); alert(data); } }); } 

Warning 1 and hello from ajax as expected.

I added json json files as expected (by pom.xml):

 dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.1</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>2.5.1</version> </dependency> 

Am I missing something? I just want to return a simple mapping structure (or another class structure in the future).

Update : From the spring console (not sure if this is related): Resolving exception from handler [null]: org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

Thanks in advance! Mike

+7
java json jackson ajax spring-mvc
source share
6 answers

I do not know if this is correct, but I solved it as follows.

In the controller, I converted the card to json:

  @RequestMapping(value = "/ajaxtest", method = RequestMethod.GET) public @ResponseBody String myTest() { System.out.println("------------------------------------random"); Map<String,String> myMap = new HashMap<String, String>(); myMap.put("a", "1"); myMap.put("b", "2"); ObjectMapper mapper = new ObjectMapper(); String json = ""; try { json = mapper.writeValueAsString(myMap); } catch (JsonProcessingException e) { // TODO Auto-generated catch block e.printStackTrace(); } return json; } 

and in jsp:

 function testAjax() { $.ajax({ url : '../../ajaxtest.html', type:"GET", contentType: "application/json;charset=utf-8", success : function(data) { alert("1"); alert(data); var obj = jQuery.parseJSON( data ); alert(obj.a); alert(obj.b); } }); 

Thanks everyone! Mike}

+6
source share

Try adding consumes="application/json" and produces={ "application/json"} in @RequestMapping to have spring process your json

Error Description UPDATE 406

HTTP Error 406 Unacceptable

Introduction

A client (for example, your web browser or our CheckUpDown robot) can indicate to the web server (on the website) the characteristics of the data that it will receive from the web server. This is done using the "accept headers" of the following types:

Accept: MIME types accepted by the client. For example, the browser can only accept back data types (HTML files, GIF files, etc.). It knows how to process. Accept-Charset: The character set accepted by the client. Accept-Encoding: data encoding accepted by the client, for example. file formats are understood. Accept-Language: natural languages ​​(English, German, etc.), Accepted by the client. Accept-Ranges: whether the client accepts byte ranges from the resource, i.e. part of the resource. If the web server detects that the data it wants to return is not acceptable to the client, it returns a header containing 406 error code.

This means that you must somehow change your server logic to accept MIME / Charset / Encoding, etc. request sent from the client. I can’t say exactly what is wrong, but try playing with the headers and consume RequestMapping.

+2
source share

Your "problem" is because your request ends in .html . You need to add the following configuration to make it work as you expect.

 <bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> <property name="favorPathExtension" value="false" /> <property name="defaultContentType" value="application/json" /> </bean> <mvc:annotation-driven content-negotiation-manager="contentNegotiationManager" /> 

and how to do as @StanislavL suggested add production produces={ "application/json"} , not add consumable resources because you are not sending any JSON

explanation

When spring determines the view to which it converts, it first looks at part of the request path (for example, .html, .json, .xml), then looks for a parameter that explicitly sets the conversion view, finally it goes for the Accept header (the so-called PPA strategy)

that's why your example works

 function testAjax() { $.ajax({ url : '../../ajaxtest.html', success : function(data) { alert("1"); alert(data); } }); } 

you get the HTML back. However, with the request

 function testAjax() { $.ajax({ url : '../../ajaxtest.html', dataType: "json", contentType: "application/json;charset=utf-8", success : function(data) { alert("1"); alert(data); } }); } 

you explicitly declare that you expect JSON back from the server, however .html hints that it should be HTML instead, and you get into problems

To find out the details of the content approval strategy, you should read this blog , almost known by now :) It will also show you a version of a clean version of java

+1
source share

Your Ajax call should look something like this:

 $("#someId" ).click(function(){ $.ajax({ url:"getDetails", type:"GET", contentType: "application/json; charset=utf-8", success: function(responseData){ console.log(JSON.stringify(responseData)); // Success Message Handler },error:function(data,status,er) { console.log(data) alert("error: "+data+" status: "+status+" er:"+er); } }); }); 

Spring controller code should be as follows:

 @RequestMapping(value="/getDetails",method=RequestMethod.GET) public @ResponseBody Map<String,String> showExecutiveSummar(){ Map<String,String> userDetails = new HashMap<String,String>(); userDetails .put("ID","a" ); userDetails .put("FirstName","b" ); userDetails .put("MiddleName","c" ); userDetails .put("LastName","d" ); userDetails .put("Gender","e" ); userDetails .put("DOB","f" ); return userDetails } 

You can also refer to this link for an understanding of the library that supports this functionality.

+1
source share

Try the following:

  $.ajax({ type:"GET", url: "/ajaxtest", dataType: "json", contentType: "application/json;charset=utf-8", success: function(data){ alert("1"); alert(data); } }); 
0
source share

You need this dependency:

 <dependency> <groupId>org.codehaus.jackson</groupId> <artifactId>jackson-mapper-asl</artifactId> <version></version> </dependency> 

Add this if you haven't already:

 <bean id="jsonConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean> <bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"> <property name="messageConverters"> <list> <ref bean="jacksonMessageConverter"/> </list> </property> </bean> 
-one
source share

All Articles