【发布时间】:2011-06-08 10:08:56
【问题描述】:
我正在使用 Spring 3.0.5 构建 JSON REST 服务,并且我的 response 包含来自我的 request 的对象,尽管我没有添加它。我正在使用 MappingJacksonJsonView 和 Jackson 1.6.4 将 ModelAndView 对象呈现为 JSON。
User 对象很简单
public class SimpleUser {
private String username;
private String password;
public String getUsername() { return username; }
public void setUsername(String username) { this.username = username; }
public String getPassword() { return password; }
public void setPassword(String password) { this.password = password;
}
}
其中一个请求如下所示
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView register(SimpleUser user) {
ModelAndView mav = new ModelAndView();
mav.addObject("ok", "success");
return mav;
}
然后我调用服务
curl 'http://localhost:8080/register?username=mike&password=mike'
我期望的回应是
{"ok": "success"}
我得到的回应是
{"ok":"success","simpleUser":{"username":"mike","password":"mike"}}
将用户对象添加到 ModelAndView 的位置和原因以及如何防止这种情况发生?
可能的解决方案
解决此问题的一种方法是使用 Model 而不是 SimpleUser。这似乎可行,但应该可以使用业务对象。
这行得通:
@RequestMapping(value = "/register", method = RequestMethod.GET)
public ModelAndView register(Model model) {
log.debug("register(%s,%s)", model.asMap().get("usernmae"), model.asMap().get("password"));
ModelAndView mav = new ModelAndView();
mav.addObject("ok", "success");
return mav;
}
【问题讨论】:
标签: json spring rest spring-mvc