我正在使用spring mvc框架做一个网站。 我想做一个调用ajax并直接从我的web控制器接收一个json对象。 这样做的最佳方式/方式/插件是什么? 我已经看过来自keith donald的教程,但是,它认为有点复杂。 谢谢你的任何建议。
我把jakson json mapper放在我的pom文件中。 我的控制器看起来像:
@RequestMapping(value = "m015", method = RequestMethod.GET)
public @ResponseBody String list(@RequestParam(value = "type", required = true) String type){
List<Mail> mails = mailService.getUserMails((Long) WebHelper.getPrincipal().getUser().getId(),type);
logger.info("yeah");
return mails.toString();
}
但我得到了我的javascript:[com.stunaz.domain.Mail@94e0a6a2]
我的ajax调用如下:
var xhrArgs = {
url: "${ctx}/portal/mail/m015.do",
content: { type: id },
headers: {'Content-Type':'application/json'},
handleAs: 'text',
sync: true,
load: function(data) {
alert(data);
},
}; dojo.xhrGet(xhrArgs);
我想念的是什么?
答案 0 :(得分:1)
在春季3.0,它很简单:
@RequestMapping("/ajax/foo")
@ResponseBody
public Foo foo(){
return new Foo();
}
确保你的app中有一个jackson json库,spring会自动将结果序列化为json。
答案 1 :(得分:0)
博客中描述的方式实际上非常简单和优雅。您可以重用控制器方法来获取JSON,XML等响应......
您所做的只是使用@ResponseBody注释方法并在项目中包含JSON jar。我自己使用maven并通过添加此依赖项来执行此操作:
<!-- Jackson JSON Mapper -->
<dependency>
<groupId>org.codehaus.jackson</groupId>
<artifactId>jackson-mapper-asl</artifactId>
<version>1.5.4</version>
</dependency>
这样的优点是控制器方法可以返回POJO(最好是DTO),只要对服务器的请求具有带有accept-encoding的正确头文件,映射器就会将其映射到JSON:application / json(或其他任何东西)。它甚至将具有正确内容类型的传入请求转换为方法签名中的dto类型。美丽!
方法示例:
@RequestMapping(value ="/service/status", method = RequestMethod.GET)
public @ResponseBody Status getServiceStatus() {
return new Status("Online", 60, "Nothing to report");
}
使用这种方法,您可以重用您的方法(我将其用于REST API)用于JSON,Web服务等...
答案 2 :(得分:0)
<bean class="org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping">
<property name="order" value="0" />
<property name="interceptors">
<list>
<ref bean="localeChangeInterceptor" />
</list>
</property>
</bean>
<!-- Enables annotated POJO @Controllers -->
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter" >
<property name="messageConverters">
<list>
<ref bean="jsonConverter" />
</list>
</property>
</bean>