12

Possible Duplicate:
Return only string message from Spring MVC 3 Controller

My spring controller has a endpoint where I want to only:

1. set the http response code
2. return a string back, don't need to render a .jsp view page or anything.

So will want to set the http status code to 200 OK or 500 etc. And simply return a string like "OK".

How can I do this, or am I forced to render a .jsp view page?

Community
  • 1
  • 1
Blankman
  • 259,732
  • 324
  • 769
  • 1,199

2 Answers2

15

Use the @ResponseBody annotation:

@RequestMapping(value="/sayHello", method=GET)
@ResponseBody
public String whatever() {
    return "Hello";
}

See the @ResponseBody ref docs for further details.

You may be able to use the @ResponseStatus annotation to set the code rather than using the HttpServletResponse directly.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302
13

No, you are not forced to use view. If you use more recent version of Spring, you may use @ResponseBody annotation. See documentation for reference.

Example:

@Controller
@RequestMapping(value = "/someUrl", method = RequestMethod.GET, produces="text/plain")
@ResponseBody
public String returnSimpleMessage() {    
    return "OK";
}

You could also use HttpServletResponse as a parameter to set desired HTTP status.

ŁukaszBachman
  • 33,595
  • 11
  • 64
  • 74