Skip to main content

Basics about ResponseEntity to maniputale HTTP Response

ResponseEntity represents the whole HTTP response: status code, headers, and body. Because of it, we can use it to fully configure the HTTP response.
If we want to use it, we have to return it from the endpoint; Spring takes care of the rest.
ResponseEntity is a generic type. As a result, we can use any type as the response body:
1
2
3
4
@GetMapping("/hello")
ResponseEntity<String> hello() {
    return new ResponseEntity<>("Hello World!", HttpStatus.OK);
}
Since we specify the response status programmatically, we can return with different status codes for different scenarios:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@GetMapping("/age")
ResponseEntity<String> age(
  @RequestParam("yearOfBirth") int yearOfBirth) {
  
    if (isInFuture(yearOfBirth)) {
        return new ResponseEntity<>(
          "Year of birth cannot be in the future",
          HttpStatus.BAD_REQUEST);
    }
    return new ResponseEntity<>(
      "Your age is " + calculateAge(yearOfBirth),
      HttpStatus.OK);
}
Additionally, we can set HTTP headers:
1
2
3
4
5
6
7
8
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    HttpHeaders headers = new HttpHeaders();
    headers.add("Custom-Header", "foo");
         
    return new ResponseEntity<>(
      "Custom header set", headers, HttpStatus.OK);
}
Furthermore, ResponseEntity provides two nested builder interfacesHeadersBuilder and its subinterface, BodyBuilder. Hence we can access their capabilities through the static methods of ResponseEntity.
The simplest case is a response with a body and HTTP 200 response code:
1
2
3
4
@GetMapping("/hello")
ResponseEntity<String> hello() {
    return ResponseEntity.ok("Hello World!");
}
For the most popular HTTP status codes we get static methods:
1
2
3
4
5
6
BodyBuilder accepted();
BodyBuilder badRequest();
BodyBuilder created(java.net.URI location);
HeadersBuilder<?> noContent();
HeadersBuilder<?> notFound();
BodyBuilder ok();
In addition, we can use the BodyBuilder status(HttpStatus status) and the BodyBuilder status(int status) methods to set any HTTP status.
Finally with ResponseEntity<T> BodyBuilder.body(T body) we can set the HTTP response body:
1
2
3
4
5
6
7
8
9
10
@GetMapping("/age")
ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
    if (isInFuture(yearOfBirth)) {
        return ResponseEntity.badRequest()
            .body("Year of birth cannot be in the future");
    }
    return ResponseEntity.status(HttpStatus.OK)
        .body("Your age is " + calculateAge(yearOfBirth));
}
We can also set custom headers:
1
2
3
4
5
6
@GetMapping("/customHeader")
ResponseEntity<String> customHeader() {
    return ResponseEntity.ok()
        .header("Custom-Header", "foo")
        .body("Custom header set");
}
Hence BodyBuilder.body() returns a ResponseEntity instead of BodyBuilder, it should be the last call.
Note, that with HeaderBuilder we can’t set any properties of the response body.
While returning ResponseEntity<T> object from the controller, we might get some exception or error while processing the request and would like to return error-related information to the user represented as some other type let’s say E.
Spring 3.2 brings support for a global @ExceptionHandler with the new @ControllerAdvice annotation handles these kinds of scenarios. For in-depth details
While ResponseEntity is very powerful, we shouldn’t overuse it. In simple cases, there’re other options that satisfy our needs and they result in much cleaner code.

Comments

Popular posts from this blog

How to secure SpringBoot with SSL and Tomcat or Undertow

when we are going to take our applications to production mode, we must have an SSL certificate for the FrontEnd and   BackEnd too, in this case, our backend is a  SpringBoot which is using a tomcat embedded server. Terminology TLS vs SSL TLS is the successor to SSL. It is a protocol that ensures privacy between communicating applications. Unless otherwise stated, in this document consider TLS and SSL as interchangable. Certificate (cert) The public half of a public/private key pair with some additional metadata about who issued it etc. It may be freely given to anyone. Private Key A private key can verify that its corresponding certificate/public key was used to encrypt data. It is never given out publicly. Certificate Authority (CA) A company that issues digital certificates. For SSL/TLS certificates, there are a small number of providers (e.g. Symantec/Versign/Thawte, Comodo, GoDaddy, LetsEncrypt) whose certificates are included by most browsers and Op...

How to deploy a VueJS App using Nginx on Ubuntu

There are thousands of blogs and websites out there explaining how to do a hello world and how to start with VueJS, but in this little post, I’m just going to be explaining how to do deploy a VueJs app after you have run the command through the CLI npm run build . So when you run the command npm run build a dist folder is created and that folder’s got the essential .js files to run our app, when we want to run our app on an Nginx server by default the vue-router is not going to work well so that Nginx does not come ready to work by default with a VueJs app This is basically for a Linux Ubuntu distribution if you’ve got any other Linux distribution just pay attention where is going to be set the www/html folder and the Nginx settings so that this is useful for any Linux distribution  Install and configure nginx sudo apt install nginx Double check to make sure the nginx service is running with command service nginx status, then open your browser and enter ...

Printing using SpringBoot - cups4j

One of the easiest ways to print something from Java , in this case, using a SpringBoot Java Api Rest is with CUPS . Let's assume you've set up your CUPS server up and running, add to your pom.xml file this dependency      < dependency >      < groupId > org.cups4j </ groupId >      < artifactId > cups4j </ artifactId >      < version > 0.7.6 </ version > </ dependency > now at this imports to import  java.io.FileInputStream; import  java.io.FileNotFoundException; import  java.net.URL; import  java.util.HashMap; import  java.util.List; import  org.cups4j.CupsClient; import  org.cups4j.CupsPrinter; import  org.cups4j.PrintJob; import  org.cups4j.PrintJobAttributes; import  org.cups4j.PrintRequestResult; import  org.cups4j.WhichJobsEnum; add this method to prin...