Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 302
Imran Qadir Baksh - Baloch Avatar asked Oct 06 '11 10:10

Imran Qadir Baksh - Baloch


People also ask

How do I return a string in spring?

The Best Answer is. public class StringResponse { private String response; public StringResponse(String s) { this. response = s; } // get/set omitted... }

How do I show error messages in spring?

Instead of passing a null argument for your error case, pass in a String . Spring is smart enough to see the String and write it as text to the response body. Alternatively, provide a @ExceptionHandler that will handle the exception itself and have your handler throw the exception.

How do you use GetMapping?

Spring @GetMapping ExampleThe @GetMapping annotation is a specialized version of @RequestMapping annotation that acts as a shortcut for @RequestMapping(method = RequestMethod. GET) . The @GetMapping annotated methods in the @Controller annotated classes handle the HTTP GET requests matched with given URI expression.


2 Answers

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

like image 135
Tomasz Nurkiewicz Avatar answered Sep 18 '22 15:09

Tomasz Nurkiewicz


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

like image 22
geoand Avatar answered Sep 21 '22 15:09

geoand