Spring MVC控制器返回HTML


问题内容

我在尝试将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>";
}

我的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作为响应?


问题答案:

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