2017-09-16 39 views
1

我有一個控制器發回一個JSON有效載荷Spring MVC的準備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視圖(本地主機:8080/{「merchantList」:[「Apple」,「Google」]}。jsp)

如何停止並返回JSON負載?

+0

你可以在RequestMapping之上添加這個@RestController嗎? –

+0

@georgesvan工作! –

+0

不錯。請隨時在下面驗證我的答案 –

回答

2

頂部添加@RestController的@RequestMapping的

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

由於該方法現在@RestController註釋,對象從這個方法返回將通過郵件轉換,以產生用於客戶端的JSON資源表示。

0

如果你想有幾個方法返回JSON頁面在同一個班級,你仍然可以註解你的類@Controller,並與@ResponseBody

註釋爲JSON的方法,如果你將註解與@RestController類 - 類內的所有方法將工作像@ResponseBody和類將像@Controller註釋。當然,這是一個更好的方法(不要在一個Controller中包含頁面和JSON返回方法)。

注意!您只能使用@RestController進行分類(而不是@Controller),而不是方法。 如果你打開這個註釋的源代碼,你會除其他事項外看到下一個:

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

ElementType.TYPE有評論:

類,接口(包括註釋類型)或枚舉聲明

相關問題