17

I am having an issue trying when trying to return HTML to my Spring MVC controller.

It looks like this:

@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>";
}

My Spring config:

<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>

I am seeing firebug that response is coming like: {"String":"<div></div>"} how can I tell this method to send me plain HTML as the response?

user2219247
  • 1,313
  • 10
  • 20
  • 26
  • this is not a particularly good idea. – NimChimpsky Jul 12 '13 at 09:51
  • 1
    Could you please be more specific why it is not? – user2219247 Jul 12 '13 at 09:58
  • what do you find easier - editing html embedded within java, or just editing a normal html/jsp file? – NimChimpsky Jul 12 '13 at 10:25
  • 1
    There is a reason I need to do so. I have a custom JSP tag which already generates HTML for me, I am reusing the same handlers to generate it on ajax requet. If I won't do that, I would need to return JSON representing my Objects tree from which I will need to generate appropriate HTML. So this makes easier for me because I can reuse my existing java code to do that instead of writing java script to produce the same HTML. – user2219247 Jul 12 '13 at 10:31
  • So what would you suggest? – user2219247 Jul 12 '13 at 10:35
  • @NimChimpsky I am trying to build a portal. Here, the html content is build up from various sources including database, jspf fragments, property files and multiple other webservices serving HTML content. I want to assemble the HTML Content in a service and return the build up HTML String from the controller. Is it a good Idea? or shall I think about something else? – Mohit Kanwar Jun 18 '15 at 06:16

1 Answers1

28

Change your Spring config like this: html=text/html and add produces = MediaType.TEXT_HTML_VALUE to your's @RequestMapping annotation.

Paulius Matulionis
  • 23,085
  • 22
  • 103
  • 143
  • 3
    if you have to use an older version of spring you can do this `response.setContentType("text/html"); response.getWriter().println(...)` Drop the `@ResponseBody` annotation. – David Williams Jun 07 '14 at 00:18
  • added produces = MediaType.TEXT_HTML_VALUE to @RequestMapping annotation and it worked. Is it mandatory to provide in Spring config? if yes where it needs to be provided ? – arvindwill Apr 16 '16 at 03:14