Spring 3 MVC and JSON example

In this tutorial, we show you how to output JSON data in Spring MVC framework.

Technologies used :

  1. Spring 3.2.2.RELEASE
  2. Jackson 1.9.10
  3. JDK 1.6
  4. Eclipse 3.6
  5. Maven 3

P.S In Spring 3, to output JSON data, just puts Jackson library in the project classpath.

1. Project Dependencies

Get Jackson and Spring dependencies.

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
        http://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.mkyong.common</groupId>
	<artifactId>SpringMVC</artifactId>
	<packaging>war</packaging>
	<version>1.0-SNAPSHOT</version>
	<name>SpringMVC Json Webapp</name>
	<url>http://maven.apache.org</url>

	<properties>
		<spring.version>3.2.2.RELEASE</spring.version>
		<jackson.version>1.9.10</jackson.version>
		<jdk.version>1.6</jdk.version>
	</properties>

	<dependencies>

		<!-- Spring 3 dependencies -->
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-web</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-webmvc</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<!-- Jackson JSON Mapper -->
		<dependency>
			<groupId>org.codehaus.jackson</groupId>
			<artifactId>jackson-mapper-asl</artifactId>
			<version>${jackson.version}</version>
		</dependency>

	</dependencies>

	<build>
		<finalName>SpringMVC</finalName>
		<plugins>
		  <plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-eclipse-plugin</artifactId>
			<version>2.9</version>
			<configuration>
				<downloadSources>true</downloadSources>
				<downloadJavadocs>false</downloadJavadocs>
				<wtpversion>2.0</wtpversion>
			</configuration>
		  </plugin>
		  <plugin>
			<groupId>org.apache.maven.plugins</groupId>
			<artifactId>maven-compiler-plugin</artifactId>
			<version>2.3.2</version>
			<configuration>
				<source>${jdk.version}</source>
				<target>${jdk.version}</target>
			</configuration>
		  </plugin>
		</plugins>
	</build>

</project>

2. Model

A simple POJO, later output this object as formatted JSON data.


package com.mkyong.common.model;

public class Shop {

	String name;
	String staffName[];

	//getter and setter methods
	
}

3. Controller

Add @ResponseBody as return value. Wen Spring sees

  1. Jackson library is existed in the project classpath
  2. The mvc:annotation-driven is enabled
  3. Return method annotated with @ResponseBody

Spring will handle the JSON conversion automatically.

JSONController.java

package com.mkyong.common.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.mkyong.common.model.Shop;

@Controller
@RequestMapping("/kfc/brands")
public class JSONController {

	@RequestMapping(value="{name}", method = RequestMethod.GET)
	public @ResponseBody Shop getShopInJSON(@PathVariable String name) {

		Shop shop = new Shop();
		shop.setName(name);
		shop.setStaffName(new String[]{"mkyong1", "mkyong2"});
		
		return shop;

	}
	
}

4. mvc:annotation-driven

Enable mvc:annotation-driven in your Spring configuration XML file.

mvc-dispatcher-servlet.xml

<beans xmlns="http://www.springframework.org/schema/beans"
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:mvc="http://www.springframework.org/schema/mvc" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
        http://www.springframework.org/schema/beans     
        http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
        http://www.springframework.org/schema/context 
        http://www.springframework.org/schema/context/spring-context-3.0.xsd
        http://www.springframework.org/schema/mvc
        http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">

	<context:component-scan base-package="com.mkyong.common.controller" />

	<mvc:annotation-driven />

</beans>

5. Demo

URL : http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar

spring mvc and json demo

Download Source Code

Download it – SpringMVC-Json-Example.zip (21 KB)

References

  1. mvc-annotation-driven documentation
  2. High-performance JSON processor
  3. Spring MVC and XML example

108 comments on “Spring 3 MVC and JSON example

  1. Hello, do you need the mvc-dispatcher-servlet.xml at Spring boot ?

    Reply
  2. com.fasterxml.jackson.core
    jackson-databind
    2.5.0

    This is also needed.

    Reply
  3. We are using Jackson-2.9.4 version with spring version to 4.0.x RELEASE. But while formatting response in resttemplate is giving exception.
    Please advise me what is the spring compatible version for jackson-2.9.4

    Reply
  4. Dear Sir,

    Could you please help me with solving the following issue?

    I have followed your tutorial for returning json from controller but itz simply not working. I am using JBOSS EAP server

    Reply
  5. IF DOESN’T WORK ?
    !!!! ADD jackson dependency in pom.xml

    com.fasterxml.jackson.core
    jackson-databind
    2.8.9

    Reply
  6. What is this following exception

    excetion occured : org.springframework.web.HttpMediaTypeNotAcceptableException: Could not find acceptable representation

    Reply
  7. Thanks for this post. its not working. i have download project. done maven clean install and deployed on Tomcat. when i hit the given url “http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar” getting Http-Status 404.
    Need Help. Thanks in Advance.

    Reply
  8. tell me the flow and i imported project but it is not running, tell me how to run it

    Reply
    1. Add this plugin in to your plugins inside of your pom.xml

      org.apache.tomcat.maven
      tomcat7-maven-plugin
      2.1

      /
      8080
      true

      Also add this dependency in your pom file:

      org.apache.tomcat.maven
      tomcat7-maven-plugin
      2.2

      if you are using eclipse run as>Maven build>under goals put “clean install tomcat7:run” (without quotations”)

      Then in your browser navigate to http://localhost:8080/rest/kfc/brands/kfc-kampar

      Reply
  9. Hi!
    I have some problem with jquery getJSON, can you help me?

    Reply
  10. Thanks for this post. I have a doubt in configuring JSON Response prefix string. I have configured jsonPrefix in my project to prefix the response json with )]}’,n in MappingJson2HTTPMessageConverter class to fix common vulnerability. How could I see the response prefixed with the above string to confirm that this is working. I tried checking in chrome in the response string F12 -> Networks-> Json Response, however I could not find the string appended to the output. Could you please help me out with this?

    Reply
  11. When I have a field of type String with over 1000 characters, all the characters are turned into u0000. Any ideas?

    Reply
  12. Hi,

    I am getting this error :

    java.lang.IllegalArgumentException: No converter found for return value of type: class com.mkyong.common.model.Shop

    on upgrading spring version to 4.2.0 RELEASE.

    Reply
    1. replace in pom.xml the dependency of jackson:
      <!– old dependency

      org.codehaus.jackson
      jackson-mapper-asl
      ${jackson.version}

      –>

      com.fasterxml.jackson.module
      jackson-module-kotlin
      ${jackson.version}

      see also “https://stackoverflow.com/questions/51259077/no-converter-found-for-return-value-of-type-class-java-util-arraylist-spring-b”

      Reply
  13. Thanks for this post!!
    I have a question, how do you configure your project ?
    Do you use only annotations setting the configuration into the code or do you prefer use the XML to set the configuration of frameworks like Spring mvc, spring batch or hibernate?

    Thank you mkyong.

    Reply
  14. P.S In Spring 3, to output JSON data, just puts Jackson library in the project classpath.

    Reply
  15. Whenever i am entering url,”http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar” in my web browser it show error page that “Resource is not available”. How can i solved it?

    Reply
  16. Hi, what is the difference between ContentNegotiationManagerFactoryBean and ContentNegotiatingViewResolver ? We can also use ContentNegotiationManagerFactoryBean for the same purpose .

    Reply
    1. I’m back…
      I needed to use jackson’s annotation @Jsonproperty(“class”) on the getter method.

      Reply
  17. Will the same work for jdk7 and spring 3.5?? Because I have created almost same project but its not working.I think there is some problem with jackson…I don’t think jackson 2.3 works with jdk7 correct me If I am wrong.

    I am not getting any error message but the ‘alert’ in which I am displaying my data is not getting displayed. However If I just send a normal string instead of a complex object its works fine.

    Can you please help?

    Reply
  18. Hi to all ,

    I am new to Spring Boot ,i was face this problem of itteration but it’s resolved by using Jackson annotaions of @JsonBackReference and @JsonManagedReference and @JsonIdentityInfo after added these annotaions and bean configuration is everything fine .. but after i could not able to post the data as Json to a controller .Please suggest answer i am facing issue like

    1)Requested URL is http://localhost:8080/custMast/state (POST) that time 405 method is coming and JSON is
    {
    “custmastCountry” : {
    “id” : 1,
    “name” : “INDIA”,
    “customerAddresses” : [ ]
    },
    “name” : “MahaRashtra”,
    “createdOn” : null,
    “updatedOn” : null,
    “”custmastDistricts” : [ ],
    “customerAddresses” : [ ]
    }

    It’s giving this following error like

    Caused by: java.lang.IllegalArgumentException: Multiple back-reference properties with name ‘defaultReference’

    and my configuration is

    Here is My Configuration file for JSON in Spring BOOT

    @Bean
    public MappingJackson2HttpMessageConverter jackson2Converter() {
    MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
    converter.setObjectMapper(objectMapper());
    return converter;
    }

    @Bean
    public ObjectMapper objectMapper() {
    Object objectMapper = new ObjectMapper();
    // ((ObjectMapper) objectMapper).registerModule(new Hibernate4Module());
    ((ObjectMapper) objectMapper)
    .enable(SerializationFeature.ORDER_MAP_ENTRIES_BY_KEYS);
    // to allow serialization of “empty” POJOs (no properties to serialize)
    // (without this setting, an exception is thrown in those cases)
    ((ObjectMapper) objectMapper)
    .disable(SerializationFeature.FAIL_ON_EMPTY_BEANS);
    // to write java.util.Date, Calendar as number (timestamp):
    ((ObjectMapper) objectMapper)
    .disable(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS);

    // DeserializationFeature for changing how JSON is read as POJOs:

    // to prevent exception when encountering unknown property:
    ((ObjectMapper) objectMapper)
    .disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES);
    // to allow coercion of JSON empty String (“”) to null Object value:
    ((ObjectMapper) objectMapper)
    .enable(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT);

    return (ObjectMapper) objectMapper;
    }

    Reply
  19. the tutorial of this guy never works as so easy.

    Reply
  20. when we make a Spring MVC project in eclipse. It creates a default structure. How does that structure work? I have tried working on it but i am not able to trace the execution path

    Reply
    1. spring mvc force us to use maven its impossible to build a spring mvc project today without using it unfortunately.

      Reply
  21. Have you been able to pass a json string to a Post method in a controller?
    We are having some issues with it. Let us know.

    Reply
    1. Here is a method to try:

      @RequestMapping(method = RequestMethod.POST, headers = {“Content-type=application/json”})
      public void setShopInJSON(@RequestBody final Shop shop) {
      System.out.println(shop);

      }

      Reply
  22. would it be possible to modify the example to include receving a JSON? I’m trying to merge you MVC/JSP example with a get/post json example, and am having issues with getting Spring config set correctly. Thanks!

    Reply
    1. Meant to add: I would like to have a controller that could do both: launch a jsp, and send/receive json. Thanks!

      Reply
      1. Same issue here.
        Having issues passing a json string to a Post method in a controller?

        Reply
  23. Hi, Is it possible to specifiy the in a java file as an annotation?

    Thanks

    Reply
    1. I am receiving following error for downloaded project zip.!!

      The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.

      Reply
  24. Hi,

    this example not working with Spring 3.2.2 and 3.2.3. It only work on Spring 3.1.4 and older version. I tested it with tomcat 7.x and JDK 1.7

    For Spring 3.2.2 and 3.2.3 I got: HTTP Status 406 – The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers.

    Can any one help me?

    Reply
    1. @mykong.. as usual.. simple and perfect example.. It worked.. thnx..

      @alapierre… I used Spring 3.2.4.. didnot have any problem, it worked. for you Http status 406 error, please include “jackson-core-asl” and “jackson-mapper-asl” jars in your lib folder.

      Reply
  25. hi, I m khaled moez i have probleme when i want to
    recuperate the object employe but when i put de type string or int it’s work and we recuperate this string . i don’t undrestand what is the probleme

    @RequestMapping(value = “employeeEntity/addd”, method = RequestMethod.POST)
    public @ResponseBody String add(HttpServletRequest request, HttpServletResponse response)
    throws Exception {
    EmployeeEntity employee = new EmployeeEntity();

    employee.setEmail(“”);
    employee.setId(12);
    employee.setLastname(“”);
    employee.setTelephone(“77”) ;
    employee.setFirstname(“”);

    System.out.println(“je suis la pour tester “);
    return “fffffffffff” ;
    }

    ***************************************************************************************
    function madeAjaxCall(){
    $.ajax({
    type: “post”,
    url: “http://localhost:8089/Applipdf/employeeEntity/addd”,
    cache: false,
    //data:’firstName=’ + $(“#firstName”).val() + “&lastName=” + $(“#lastName”).val() + “&email=” + $(“#email”).val(),
    success: function(response){
    $(‘#result’).html(response);
    // var obj = JSON.parse(response);
    // $(‘#result’).html(“First Name:- ” + obj.firstName +”Last Name:- ” + obj.lastName + “Email:- ” + obj.email);
    },
    error: function(){
    alert(‘Error while request..’);
    }
    });
    }

    Reply
  26. The tutorial is very helpful and easy to follow, thank you.

    Reply
  27. Thanks a lot! Very clear and simple article.

    Reply
  28. make sure that you add two jackson related jar files.
    jackson-core-asl-1.9.8.jar
    jackson-mapper-asl-1.9.8.jar

    Reply
  29. Hi
    in Your source Exsample and your description,
    there has not “/kfc/brands” folder. in that folder, what does it have?
    so, I can not run your Example. You would like to show me, please

    Reply
  30. Hi, Im getting the below error when trying to do this(@ResponseBody),

    com.ibm.ws.webcontainer.webapp.WebApp logServletError SRVE0293E: [Servlet Error]-[chpServlet]: com.ibm.ws.webcontainer.webapp.WebAppErrorReport: SRVE0295E: Error reported: 500
    at com.ibm.ws.webcontainer.webapp.WebAppDispatcherContext.sendError(WebAppDispatcherContext.java:624)
    at com.ibm.ws.webcontainer.webapp.WebAppDispatcherContext.sendError(WebAppDispatcherContext.java:642)
    at com.ibm.ws.webcontainer.srt.SRTServletResponse.sendError(SRTServletResponse.java:1236)
    at com.ibm.ws.webcontainer.srt.SRTServletResponse.sendError(SRTServletResponse.java:1210)
    at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.handleHttpMessageNotWritable(DefaultHandlerExceptionResolver.java:344)
    at org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver.doResolveException(DefaultHandlerExceptionResolver.java:131)
    at org.springframework.web.servlet.handler.AbstractHandlerExceptionResolver.resolveException(AbstractHandlerExceptionResolver.java:136)
    at org.springframework.web.servlet.DispatcherServlet.processHandlerException(DispatcherServlet.java:1120)
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:944)
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:852)
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:882)
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:778)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:575)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.service(ServletWrapper.java:1214)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:774)
    at com.ibm.ws.webcontainer.servlet.ServletWrapper.handleRequest(ServletWrapper.java:456)
    at com.ibm.ws.webcontainer.servlet.ServletWrapperImpl.handleRequest(ServletWrapperImpl.java:178)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.invokeTarget(WebAppFilterChain.java:125)
    at com.ibm.ws.webcontainer.filter.WebAppFilterChain.doFilter(WebAppFilterChain.java:77)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.doFilter(WebAppFilterManager.java:926)
    at com.ibm.ws.webcontainer.filter.WebAppFilterManager.invokeFilters(WebAppFilterManager.java:1023)
    at com.ibm.ws.webcontainer.servlet.CacheServletWrapper.handleRequest(CacheServletWrapper.java:87)
    at com.ibm.ws.webcontainer.WebContainer.handleRequest(WebContainer.java:895)
    at com.ibm.ws.webcontainer.WSWebContainer.handleRequest(WSWebContainer.java:1662)
    at com.ibm.ws.webcontainer.channel.WCChannelLink.ready(WCChannelLink.java:195)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleDiscrimination(HttpInboundLink.java:452)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.handleNewRequest(HttpInboundLink.java:511)
    at com.ibm.ws.http.channel.inbound.impl.HttpInboundLink.processRequest(HttpInboundLink.java:305)
    at com.ibm.ws.http.channel.inbound.impl.HttpICLReadCallback.complete(HttpICLReadCallback.java:83)
    at com.ibm.ws.tcp.channel.impl.AioReadCompletionListener.futureCompleted(AioReadCompletionListener.java:165)
    at com.ibm.io.async.AbstractAsyncFuture.invokeCallback(AbstractAsyncFuture.java:217)
    at com.ibm.io.async.AsyncChannelFuture.fireCompletionActions(AsyncChannelFuture.java:161)
    at com.ibm.io.async.AsyncFuture.completed(AsyncFuture.java:138)
    at com.ibm.io.async.ResultHandler.complete(ResultHandler.java:204)
    at com.ibm.io.async.ResultHandler.runEventProcessingLoop(ResultHandler.java:775)
    at com.ibm.io.async.ResultHandler$2.run(ResultHandler.java:905)
    at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:1659)

    Any inputs on this. Although this happens for one type of object only. Im running Spring 3.1.2 on WAS 8.

    Reply
    1. I now have exacltly the same problem, did you find any solution for your problem? Please help me.

      Reply
      1. Yeah I was able to figure that out. I had an empty class(that was JAXB Generated). It was causing the issue. Like, public class DataIndicator{}. There was no variable within it. I changed the schema(that was in my case). Check if you have a similar empty class(that is a part of the response object that ur trying to convert it to JSON). Hope this helps!!

        Reply
  31. Thanks for this post. I dont see an configuration which explicitly sets the response type to json. Is that something that happens by default. For example if i wanted to have an xml response type what would i need to do?

    Thanks,
    N

    Reply
    1. @RequestMapping(value = “/greeting”, produces = “application/json”)

      Reply
  32. This is very nice website…
    Very useful articles are posted here..
    Thanks for you…

    Reply
  33. Would be nice if u can enhance the tutorial for WADL and some way of generating the code from the WADL like we could do using WSDL

    I just hate REST because it got rid of the Service Definition part of SOAP for convenience.

    Reply
  34. I already have a PDF document generated by my backend, how do I return this in a RESTful service? What will the MarshallingView and ContentNegotiatingViewResolver look like?

    thank you.

    Reply
  35. what about post how to get the json data post in the json format … please give an example

    Reply
  36. i am getting this error when running this example in browser. plz help

    The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers ().

    Reply
    1. Hi,

      You should in servlet.xml file and ensure the file should be error free.

      Reply
    2. I get this same exact error in response. Status 406: “The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request “accept” headers ().”

      I have exactly followed this procedure and also making sure my dependency for Jackson is set correctly. Here are more details if anyone has gotten this to resolve
      http://stackoverflow.com/questions/12865093/spring-3-x-json-status-406-characteristics-not-acceptable-according-to-the-requ

      Reply
      1. Solution – This is a followup to the problem I had posted earlier which is now resolved. Hopefully this helps anybody else who might face this. The solution for the “406” error in my case was to make the POJO getter methods public [I had them protected]

        Reply
  37. Hi,

    How can I use MarshallingViewResolver to handle the conversion for json?
    Could someone take me through it?

    Reply
  38. If one of the JSON name value pairs need to be made optional, what’s the best way to go about it ?
    Eg. In this example String staffName[]; is optional…

    Reply
    1. Setup defaults in the constructor and got going 🙂

      Reply
  39. Unable to run this example. I downloaded all the dependencies. Still I’m getting error
    No mapping found for HTTP request with URI [/JSONTest/rest/kfc/brands/Rani]

    Reply
    1. I had same issue. My classes were not compiled because build class path was pointing to maven repository. I changed to jars in web-inf/lib and re-compiled. It is working now.

      Reply
  40. Missing:
    ———-
    1) net.sf.sojo:sojo-optional:jar:0.5.0

    Try downloading the file manually from the project website.

    Then, install it using the command:
    mvn install:install-file -DgroupId=net.sf.sojo -DartifactId=sojo-optional -Dversion=0.5.0 -Dpackaging=jar -Dfile=/path/to/file

    Alternatively, if you host your own repository you can deploy the file there:
    mvn deploy:deploy-file -DgroupId=net.sf.sojo -DartifactId=sojo-optional -Dversion=0.5.0 -Dpackaging=jar -Dfile=/path/to/file -Durl=[url] -DrepositoryId=[id]

    Path to dependency:
    1) SpringDemos:SpringDemos:jar:1.0
    2) net.sf.spring-json:spring-json:jar:1.1
    3) net.sf.sojo:sojo-optional:jar:0.5.0

    ———-
    1 required artifact is missing.

    for artifact:
    SpringDemos:SpringDemos:jar:1.0

    from the specified remote repositories:
    central (http://repo1.maven.org/maven2)

    Reply
  41. I had to add the following jackson dependencies to get the downloaded example to work.

    		
    		
    			org.codehaus.jackson
    			jackson-core-lgpl
    			1.3.0
    		
    		
    			org.codehaus.jackson
    			jackson-mapper-lgpl
    			1.3.0
    		
    		
    			org.codehaus.jackson
    			jackson-xc
    			1.3.0
    		
    
    Reply
  42. Hi
    public ActionResult About()
    {
    List listStores = new List();
    listStores = this.GetResults(“param”);
    return Json(listStores, “Stores”, JsonRequestBehavior.AllowGet);
    }

    Using the above code i am able to get the below result :

    [{“id”:”1″,”name”:”Store1″,”cust_name”:”custname1″,”telephone”:”1233455555″,”email”:”[email protected]”,”geo”:{“latitude”:”12.9876″,”longitude”:”122.376237″}},{“id”:”2″,”name”:”Store2″,”cust_name”:”custname2″,”telephone”:”1556454″,”email”:”[email protected]”,”geo”:{“latitude”:”12.9876″,”longitude”:”122.376237″}},

    how would i able to get the result in below format ? would need stores at the beginning of the result.

    {
    “stores” : [
    {“id”:”1″,”name”:”Store1″,”cust_name”:”custname1″,”telephone”:”1233455555″,”email”:”[email protected]”,
    “geo”:{“latitude”:”12.9876″,”longitude”:”122.376237″}},{“id”:”2″,”name”:”Store2″,”cust_name”:”custname2″,”telephone”:”1556454″,”email”:”[email protected]”,”geo”:{“latitude”:”12.9876″,”longitude”:”122.376237″}} ] }

    Please help me in this regard.

    Reply
  43. If Mavan build doesn’t work replace the build tag with following one.
    Use Maven 3.x

    SpringMVC

    maven-compiler-plugin
    2.2

    1.6
    1.6

    Reply
  44. Hello,

    I am working on Spring MVC 3.0 JAXB & REST. I am new to these technologies. I am learning from your examples.

    In the above examples I didn’t understand the URL format. Could you explain it. where was the “rest” configured (http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar)

    I am getting 404 error when trying to execute this one in eclipse

    Reply
    1. SpringMVC is the webapp (directory name in the web server’s webapps directory)

      In the webapp’s web.xml, the url mapping includes ‘rest’ as follows:

      <servlet-mapping>
      		<servlet-name>mvc-dispatcher</servlet-name>
      		<url-pattern>/rest/*</url-pattern>
      	</servlet-mapping>

      The controller takes you further in the url with the following annotation:
      @RequestMapping(“kfc/brands”)

      Whatever comes after that in the url is the ‘name’ PathVariable

      I hosted his example in Tomcat and it works.

      I discovered that the only misleading part in this example is the following in web.xml:

      <context-param>
      		<param-name>contextConfigLocation</param-name>
      		<param-value>/WEB-INF/mvc-dispatcher-servlet.xml</param-value>
      	</context-param>

      Since the servlet name, as defined in web.xml, is mvc-dispatcher, the default dispatcher servlet name is mvc-dispatcher-servlet.xml, which coincides with the given name in the web.xml
      If you try to give any other name via this mechanism, the application will not work. You need to specify via servlet’s init-param as follows:

      <init-param>
      			<param-name>contextConfigLocation</param-name>
      			<param-value>/WEB-INF/applicationContext.xml</param-value>
      		</init-param>
      Reply
  45. Thank you… very helpful.

    Code snippet such as the following will allow UI to get to the controller:
    $(document).ready(function() {
    $.getJSON(“http://localhost:8080/SpringMVC/rest/kfc/brands/kfc-kampar”, function(shop) {
    alert(shop.name);
    });
    });

    Reply
  46. When I run this example, its giving me Open/Save dialog on UI instead of printing JSOn data on browser.

    How would I print on browser ? Do I need to set any Accept header ?

    Reply
  47. Hi,
    I like your way of explaining things, all your helps are appreciated.

    Can you please teach us how to interact from HTML (or jsp) to call an MVC controller , the controller will send data (as json)back to the page and update a div area.

    Thanks lot.
    Majid

    Reply
    1. Can you please post the reponse mapping code using json (I want to take json as an input to the spring controller and process the data)

      Reply

Leave a Comment

Your email address will not be published. Required fields are marked *