Return only string message from Spring MVC 3 Controller

Can any one tell me how I can return string message from controller?

If i just return a string from a controller method then spring mvc treating it as a jsp view name.


Solution 1:

Annotate your method in controller with @ResponseBody:

@RequestMapping(value="/controller", method=GET)
@ResponseBody
public String foo() {
    return "Response!";
}

From: 15.3.2.6 Mapping the response body with the @ResponseBody annotation:

The @ResponseBody annotation [...] can be put on a method and indicates that the return type should be written straight to the HTTP response body (and not placed in a Model, or interpreted as a view name).

Solution 2:

With Spring 4, if your Controller is annotated with @RestController instead of @Controller, you don't need the @ResponseBody annotation.

The code would be

@RestController
public class FooController {

   @RequestMapping(value="/controller", method=GET)
   public String foo() {
      return "Response!";
   }

}

You can find the Javadoc for @RestController here