2013-07-12 123 views
11

我嘗試將HTML返回給我的Spring MVC控制器時遇到問題。Spring MVC控制器返回HTML

它看起來像這樣:

@RequestMapping(value = QUESTION_GROUP_CREATE_URL, method = RequestMethod.POST) 
public 
@ResponseBody 
String createQuestionGroup(@RequestBody JsonQuestionGroup questionGroup, HttpServletResponse response) { 

    // questionGroup - this comes OK. 

    response.setContentType("text/html"); 
    response.setCharacterEncoding("UTF-8"); 
    return "<div></div>"; 
} 

我的Spring配置:

<bean id="contentNegotiationManager" class="org.springframework.web.accept.ContentNegotiationManagerFactoryBean"> 
    <property name="favorPathExtension" value="false"/> 
    <property name="favorParameter" value="true"/> 
    <property name="mediaTypes"> 
     <value> 
      json=application/json 
      xml=application/xml 
      html=application/html 
     </value> 
    </property> 
</bean> 

我看到螢火蟲是響應即將到來,如:{"String":"<div></div>"}我怎麼能告訴這個方法來給我簡單的HTML作爲響應?

+0

這不是一個特別好的主意。 – NimChimpsky

+1

你能否更具體地說明爲什麼它不是? – user2219247

+0

你覺得更容易 - 編輯嵌入在Java中的HTML,或只是編輯一個正常的HTML/JSP文件? – NimChimpsky

回答

19

更改您的Spring配置,如下所示:html=text/html並將produces = MediaType.TEXT_HTML_VALUE添加到您的@RequestMapping註釋中。

+0

這適用於我。謝謝。 – user2219247

+3

如果你必須使用彈簧的老版本,你可以這樣做'response.setContentType(「text/html」); response.getWriter()。println(...)'刪除'@ ResponseBody'註釋。 –

+0

將生產= MediaType.TEXT_HTML_VALUE添加到@RequestMapping註釋,它工作。是否必須在Spring配置中提供?如果是的話需要提供嗎? – arvindwill