开发者

Spring mvc configuration JSON

I would know how works the configuration about Spring MVC rest services that returns JSON.

I have configurated the applicationContenxt.xml in this way:

<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
    <property name="messageConverters">
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"/>
        </list>
    </property>
</bean>
<bean id="contentNegotiatingViewResolver" class="org.springframework.web.servlet.view.ContentNegotia开发者_Python百科tingViewResolver">
    <property name="mediaTypes">
        <map>
            <entry key="json" value="application/json"/>
        </map>
    </property>
    <property name="defaultViews">
        <list>
            <bean class="org.springframework.web.servlet.view.json.MappingJacksonJsonView"/>
        </list>
    </property>
</bean>
<bean class="com.MyController"></bean>

And this is the code of my controller:

@Controller(value="MyController")
public class MyController {
    @RequestMapping(value="/getValue", method=RequestMethod.GET)
    public ModelAndView getValue() {
        Map model = new HashMap();
        model.put("asasa", "bbbbb");
        model.put("cccc", "ddddd");
        return new ModelAndView("jsonView",model);
    }
}

I'm missing something about xml configuration or Java code? I have always error 404 while trying to invoke this resource: http://localhost:8080/fss/MyController/getValue


Just do:

@Controller
public class HelloController {

  @RequestMapping(value="/hello", method=RequestMethod.GET)
  public @ResponseBody String hello(@RequestParam String name) {
    return "Hi " + name;
  }
}

Change the return type to an object and include jackson in the classpath for an object response.

The request need to have a application/json header for the controller to return json.

Check out http://blog.springsource.com/2010/01/25/ajax-simplifications-in-spring-3-0/


And don't forget to add jackson converter to Spring context file.

<mvc:annotation-driven>
  <mvc:message-converters>
    <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
  </mvc:message-converters>
</mvc:annotation-driven>

By the way - if your method accepts JSON, then use @RequestBody annotation with incoming data type:

@RequestMapping
public @ResponseBody OutgoingClass getJsonByJson(@RequestBody IncomingClass data) {...}

You can find nice examples of JSON and Spring MVC and more https://sites.google.com/site/upida4j/example

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜