2012-01-21 27 views
15

我想在頁面上顯示簡單的文本,因此我想返回Content-Type作爲text/plainSpring MVC 3返回內容類型:text/plain

使用下面的代碼,我在頁​​面上看到純文本,但返回Content-Type仍然text/html

我該如何解決這個問題?

注意:我在Spring MVC中使用了Tiles。返回的「m.health」指向映射到僅包含下面1行的health.jsp的tiles def。

UPDATE注:我有超過在HTTP報頭的請求或Content-TypeAccept沒有控制。我想我的迴應返回text/plain無論進來什麼樣的要求

控制器:

@RequestMapping(value = "/m/health", method = RequestMethod.GET, headers = "Accept=*") 
public String runHealthCheck(HttpServletResponse response, HttpServletRequest request, Model model) throws Exception { 
    model = executeCheck(request, response, TEMPLATE, false, model); 
    model.addAttribute("accept", "text/plain"); 
    response.setContentType("text/plain"); 
    response.setCharacterEncoding("UTF-8"); 
    return "m.health"; 
} 

JSP:

$ {狀態}

回答

7

你可以試試將您的@RequestMapping註釋的produces值設置爲text/plain。 Spring文檔將其列爲sample

+1

我在什麼'內容Type'在'request'設置沒有控制,併產生不匹配,如果請求類型這不是我設定的。無論請求類型是什麼,我基本上都希望返回「text/plain」。 – Ali

46

,如果你與另外@ResponseBody註釋你的方法它應該工作:

@RequestMapping(value = "/", 
       method = RequestMethod.GET) 
@ResponseBody 
public String plaintext(HttpServletResponse response) { 
    response.setContentType("text/plain"); 
    response.setCharacterEncoding("UTF-8"); 
    return "TEXT"; 
} 
+6

對於訪問此問題的任何人,Markus在Ali接受後添加了他的回覆,但這是使用註釋時的正確方法。它很簡單,效果很好。 – 2012-06-12 18:43:52

+0

這應該被接受爲正確的答案。 –

+8

它不起作用。如果您使用@ResponseBody,則Spring將通過「application/json」重寫Content Type –

相關問題