Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Want my spring controller to return a string without a view [duplicate]

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?

like image 925
Blankman Avatar asked Jan 02 '12 14:01

Blankman


2 Answers

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.

like image 53
Dave Newton Avatar answered Oct 21 '22 12:10

Dave Newton


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.

like image 31
ŁukaszBachman Avatar answered Oct 21 '22 10:10

ŁukaszBachman