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