开发者

Unable to use Scala and Spring MVC 3 to return JSON

I am converting my Java Spring controller classes to Scala. In Java, a controller method that returned JSON was defined as this:

@RequestMapping(value = "/search", method = RequestMethod.GET)
public @ResponseBody String[] searchFoods(@RequestParam("term") String searchTerm, Principal principal) { ... }

This works as expected. The same method in Scala looks like this:

@RequestMapping(value = Array("/search"), method = Array(RequestMet开发者_如何学Pythonhod.GET))
def searchFoods(@RequestParam("term") searchTerm: String, principal: Principal): java.util.List[String] @ResponseBody = { ... }

However, any time this path is requested I get the following exception:

2011-10-09 09:06:19.980:WARN::/searchpath/search.html
javax.servlet.ServletException: Could not resolve view with name 'searchpath/search' in servlet with name 'dispatcher'
at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1029)

And the web server returns an HTTP 500 error. Is it possible to use Scala and Spring MVC 3 together to return JSON?


Looks like I was putting the @ResponseBody in the wrong place. It needs to appear before the method definition:

@RequestMapping(value = Array("/search"), method = Array(RequestMethod.GET))
@ResponseBody
def searchFoods(@RequestParam("term") searchTerm: String, principal: Principal): java.util.List[String]  = { ... }

I had tried this before, but forgot to clean my project. After moving the annotation to the correct location, then cleaning and rebuilding, everything was working again. Thanks!


Looks like the issue isn't JSON, but path resolution. Try changing the method annotation to:

@RequestMapping(value = Array("/searchpath/search"), method = Array(RequestMethod.GET))

See this page for a full example.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜