我正在尝试返回Map的JSON表示作为我的控制器中定义的操作的返回类型。
这是方法本身:
@RequestMapping(value = "/executeRetrieve", method = RequestMethod.POST, produces = "application/json; charset=utf-8")
public @ResponseBody Map<String, Object> executeAction() {
Map map = new HashMap();
map.put("message", "hello");
return map;
}
但是当我调用该动作时,我一直收到错误406:
HTTP Status 406 - description: The resource identified by this request is only capable of generating responses with characteristics not acceptable according to the request "accept" headers.
这意味着问题与Spring转换为JSON无关,对吧?
更新 - 这是我的上下文配置:
public class ServletInitializer implements WebApplicationInitializer {
public void onStartup(ServletContext container) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.register(ServletConfiguration.class);
context.setServletContext(container);
ServletRegistration.Dynamic servlet = container.addServlet("dispatcher", new DispatcherServlet(context));
servlet.setLoadOnStartup(1);
servlet.addMapping("/");
}
}
答案 0 :(得分:0)
从一开始就做了我应该做的事情。 Spring可以为我们将对象渲染为JSON。因此,为了保持一致性,组织和基本的面向对象编程,我创建了一个模型类,其中包含我作为响应所需的所有属性,并让Spring处理渲染。这是我的最终代码:
@RequestMapping(value = "/executeRetrieve", method = RequestMethod.POST)
public @ResponseBody Student executeRetrieve(HttpServletRequest request) {
String user = request.getParameter("user");
String password = request.getParameter("password");
return loginService.executeRetrieve(user, password);
}
谢谢大家。