2016-08-24 30 views
0

我正在使用Mustache.java,但我沒有找到設置HTML標頭的簡單方法。例如,我想設置content="text/html如何使用鬍子設置HTML標頭

渲染鬍子文件

我的Java代碼是:

@Path("/home") 
@GET 
public static String getIndexPage(){ 
     MustacheFactory mf = new DefaultMustacheFactory(); 
     Mustache mustache = mf.compile(MustacheFileName); 
     StringWriter b = new StringWriter(); 
     try { 
      mustache.execute(b, new MustacheObject()).flush(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return b.toString(); 
} 

注:

  • 我正在使用Jersey

  • 返回的HTML內容是我的應用程序text/plain(檢查在Chrome瀏覽器中使用開發工具)

  • 我目前的解決方案是在MustacheFileName設置:

    <head> <meta http-equiv="content-type" content="text/html; charset=UTF-8"> ... </head>

那麼,有沒有一種優雅的方式做到這一點,而不是手動設置,在HTML模板文件?

回答

1

我發現這一個優雅的解決方案:

定義GET生產方法MediaType.TEXT_HTML

@Path("/home") 
@GET 
@Produces(MediaType.TEXT_HTML) 
public static String getIndexPage(){ 
     MustacheFactory mf = new DefaultMustacheFactory(); 
     Mustache mustache = mf.compile(MustacheFileName); 
     StringWriter b = new StringWriter(); 
     try { 
      mustache.execute(b, new MustacheObject()).flush(); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } 
     return b.toString(); 
} 
2

你的問題似乎與鬍子無關。然而,使用正常的球衣REST應用力學,你會切換到返回響應對象,而不是一個簡單的字符串,沿着線:

import javax.ws.rs.core.Response; 

@Path("/home") 
@GET 
public static Response getIndexPage(){ 
    MustacheFactory mf = new DefaultMustacheFactory(); 
    Mustache mustache = mf.compile(MustacheFileName); 
    StringWriter b = new StringWriter(); 
    try { 
     mustache.execute(b, new MustacheObject()).flush(); 
    } catch (IOException e) { 
     e.printStackTrace(); 
    } 
    return Response.ok() 
     .entity(b.toString()) 
     .header("whatever-header-you-need", "... its value") 
     .build(); 
} 
+0

謝謝你! 你可能想看看我的答案,我剛剛提出了另一個優雅的解決方案。 –

+0

是的,確實如此。我沒有注意到你需要的具體標題。對於你的情況,@Produces是最好的選擇。在一般情況下,在書中保留上面的答案,您沒有直接註釋支持。 – mtj