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?

6
  • this is not a particularly good idea. Commented Jul 12, 2013 at 9:51
  • 1
    Could you please be more specific why it is not? Commented Jul 12, 2013 at 9:58
  • what do you find easier - editing html embedded within java, or just editing a normal html/jsp file? Commented Jul 12, 2013 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. Commented Jul 12, 2013 at 10:31
  • So what would you suggest? Commented Jul 12, 2013 at 10:35

1 Answer 1

28

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

Sign up to request clarification or add additional context in comments.

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.