109

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.

Imran Qadir Baksh - Baloch
  • 32,612
  • 68
  • 179
  • 322

10 Answers10

222

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

Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
60

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

geoand
  • 60,071
  • 24
  • 172
  • 190
19

Although, @Tomasz is absolutely right there is another way:

@RequestMapping(value="/controller", method=GET)
public void foo(HttpServletResponse res) {
    try {       
        PrintWriter out = res.getWriter();
        out.println("Hello, world!");
        out.close();
    } catch (IOException ex) { 
        ...
    }
}

but the first method is preferable. You can use this method if you want to return response with custom content type or return binary type (file, etc...);

Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
danny.lesnik
  • 18,479
  • 29
  • 135
  • 200
  • Just a heads up, but you don't even need to pull the response in for this. – Scott Oct 06 '11 at 20:51
  • Meant that for the second point, about needing to set a custom content type or returning a binary type, you can still use the ResponseEntity for those means. – Scott Oct 06 '11 at 21:41
  • This allows you to return data that might not fit in memory. I don't know if there's a better alternative for that in Spring, but this is generally what I've used. – David Bradley May 18 '22 at 19:46
6

This is just a note for those who might find this question later, but you don't have to pull in the response to change the content type. Here's an example below to do just that:

@RequestMapping(method = RequestMethod.GET, value="/controller")
public ResponseEntity<byte[]> displayUploadedFile()
{
  HttpHeaders headers = new HttpHeaders();
  String disposition = INLINE;
  String fileName = "";
  headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);

  //Load your attachment here

  if (Arrays.equals(Constants.HEADER_BYTES_PDF, contentBytes)) {
    headers.setContentType(MediaType.valueOf("application/pdf"));
    fileName += ".pdf";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_TIFF_BIG_ENDIAN, contentBytes)
      || Arrays.equals(Constantsr.HEADER_BYTES_TIFF_LITTLE_ENDIAN, contentBytes)) {
    headers.setContentType(MediaType.valueOf("image/tiff"));
    fileName += ".tif";
  }

  if (Arrays.equals(Constants.HEADER_BYTES_JPEG, contentBytes)) {
    headers.setContentType(MediaType.IMAGE_JPEG);
    fileName += ".jpg";
  }

  //Handle other types if necessary

  headers.add("Content-Disposition", , disposition + ";filename=" + fileName);
  return new ResponseEntity<byte[]>(uploadedBytes, headers, HttpStatus.OK);
}
Scott
  • 9,458
  • 7
  • 54
  • 81
3

What about:

PrintWriter out = response.getWriter();
out.println("THE_STRING_TO_SEND_AS_RESPONSE");
return null;

This woks for me.

Dimitris
  • 3,975
  • 5
  • 25
  • 27
3

For outputing String as text/plain use:

@RequestMapping(value="/foo", method=RequestMethod.GET, produces="text/plain")
@ResponseBody
public String foo() {
    return "bar";
}
MariuszS
  • 30,646
  • 12
  • 114
  • 155
  • 1
    This didn't work for me. I had to get the response object and explicitly set the content type before returning the String object. – Pedro Madrid Apr 20 '16 at 20:34
2

There are two possible solution

  1. Use @Controller and @ResponseBody, to combine HTML page and the string message for different functions

    @Controller
    @RequestMapping({ "/user/registration"})
    public class RegistrationController {    
    @GetMapping
     public String showRegistrationForm(Model model) {
         model.addAttribute("user", new UserDto());
         return "registration"; //Returns the registration.html
     }
    
     @PostMapping
     @ResponseBody
     public String registerUserAccount(@Valid final UserDto accountDto, final HttpServletRequest request) {
         LOGGER.debug("Registering user account with information: {}", accountDto);
         return "Successfully registered" // Returns the string
     }
    
  2. Use @RestController to return String message. In this case, you cannot have functions which returns HTML page.

     @RestController
     @RequestMapping({ "/user/registration"})
     public class RegistrationController {
    
     @PostMapping
         public String registerUserAccount(@Valid @RequestBody final UserDto accountDto, final HttpServletRequest request) {
             LOGGER.debug("Registering user account with information: {}", accountDto);
             return "Successfully registered" // Returns the string
         }
    
jfk
  • 4,335
  • 34
  • 27
2
@Controller
public class HelloController {
    @RequestMapping(value = "/", method = RequestMethod.GET)
    ResponseEntity<String> sayHello() {
        return ResponseEntity.ok("Hello");
    }
}
Programmer
  • 57
  • 7
1

Simplest solution:

Just add quotes, I really don't know why it's not auto-implemented by Spring boot when response type defined as application/json, but it works great.

@PostMapping("/create")
public String foo()
{
    String result = "something"
    return "\"" + result + "\"";
}
Adir Dayan
  • 1,308
  • 13
  • 21
0
@ResponseBody
@RequestMapping(value="/get-text", produces="text/plain")
public String myMethod() {
     return "Response!";
}
  • You see that @ResponseBody ?

It's telling that the method returns some text and not to interpret it as a view etc.

  • You see that produces="text/plain" ?

It's just a good practice as it tells what will be returned from the method :)

Ashutosh Tiwari
  • 1,496
  • 11
  • 20