Spring MVC控制器返回HTML

use*_*247 14 java spring controller spring-mvc

我试图将HTML返回到我的Spring MVC控制器时遇到了一个问题.

它看起来像这样:

@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>";
}
Run Code Online (Sandbox Code Playgroud)

我的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>
Run Code Online (Sandbox Code Playgroud)

我看到firebug响应就像:{"String":"<div></div>"}我怎么能告诉这个方法发送简单的HTML作为响应?

Pau*_*nis 25

像这样更改你的Spring配置:html=text/html并添加produces = MediaType.TEXT_HTML_VALUE到你的@RequestMapping注释中.

  • 如果你必须使用旧版本的spring,你可以这样做`response.setContentType("text/html"); response.getWriter().println(...)`删除`@ ResponseBody`注释. (3认同)