【问题标题】:Spring MVC preparing JSON but loading a page insteadSpring MVC 准备 JSON 但加载页面
【发布时间】:2018-02-25 15:57:36
【问题描述】:

我有一个控制器来发回 JSON 有效负载

    @RequestMapping(value = "/MerchantMonitoringAPI", method = RequestMethod.GET,produces = "application/json") 
public String MerchantMonitoring() {

    ApplicationContext context =
            new ClassPathXmlApplicationContext("Spring-Module.xml");

        TopMerchantsDAO topMerchantsDAO = (TopMerchantsDAO) context.getBean("topMerchantsDAO");
        TopMerchants topMerchants = topMerchantsDAO.retrieveMerchantList();

        for(String temp:topMerchants.getMerchantList())
        {
            System.out.println(temp);
        }

        Gson gson = new Gson();
        Type type = new TypeToken<TopMerchants>() {}.getType();

        String jsonPayload = gson.toJson(topMerchants, type);
        System.out.println(jsonPayload);

        return jsonPayload;
}

它试图将我重定向到页面名称为 JSON (localhost:8080/{"merchantList":["Apple","Google"]}.jsp) 的视图

如何停止并返回 JSON 负载??

【问题讨论】:

  • 你能把这个 @RestController 添加到 RequestMapping 的顶部吗?
  • @georgesvan 成功了!
  • 不错。随意在下面验证我的答案

标签: json spring spring-mvc gson


【解决方案1】:

在@RequestMapping 之上添加@RestController

    @RestController 
    @RequestMapping(value = "/MerchantMonitoringAPI", method = 
    RequestMethod.GET,produces = "application/json") 
    public String MerchantMonitoring() {...}

由于该方法现在使用@RestController注解,从该方法返回的对象将经过消息转换为客户端生成一个json资源表示。

【讨论】:

    【解决方案2】:

    如果你想在同一个类中有多个返回JSONpage的方法,你仍然可以用@Controller注释你的类,以及JSON的方法注释为@ResponseBody

    如果您将使用 @RestController 注释类 - 类中的所有方法都将像 @ResponseBody 一样工作,并且类将像 @Controller 注释一样。当然,这是一种更好的方法(在一个 Controller 中不包含页面和 JSON 返回方法)。

    注意!您只能将@RestController 用于类(而不是@Controller),不能用于方法。 如果您将开放此注释的源代码,您将看到以下内容:

    @Target({ElementType.TYPE})
    @Retention(RetentionPolicy.RUNTIME)
    @Documented
    @Controller
    @ResponseBody
    public @interface RestController {
        String value() default "";
    }
    

    ElementType.TYPE 有评论:

    类、接口(包括注解类型)或枚举声明

    【讨论】:

      猜你喜欢
      • 2013-04-25
      • 2012-10-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-05-17
      • 1970-01-01
      • 2014-07-14
      相关资源
      最近更新 更多