Skip to content

Commit 913c95c

Browse files
committed
ResponseEntity builder examples
1 parent 53201b4 commit 913c95c

1 file changed

Lines changed: 52 additions & 0 deletions

File tree

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
package com.baeldung.annotations;
2+
3+
import java.time.Year;
4+
5+
import org.springframework.http.HttpStatus;
6+
import org.springframework.http.ResponseEntity;
7+
import org.springframework.stereotype.Controller;
8+
import org.springframework.web.bind.annotation.GetMapping;
9+
import org.springframework.web.bind.annotation.RequestMapping;
10+
import org.springframework.web.bind.annotation.RequestParam;
11+
12+
@Controller
13+
@RequestMapping("/customResponseWithBuilder")
14+
public class CustomResponseWithBuilderController {
15+
16+
@GetMapping("/hello")
17+
public ResponseEntity<String> hello() {
18+
return ResponseEntity.ok("Hello World!");
19+
}
20+
21+
@GetMapping("/age")
22+
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
23+
if (isInFuture(yearOfBirth)) {
24+
return ResponseEntity.badRequest()
25+
.body("Year of birth cannot be in the future");
26+
}
27+
28+
return ResponseEntity.status(HttpStatus.OK)
29+
.body("Your age is " + calculateAge(yearOfBirth));
30+
}
31+
32+
private int calculateAge(int yearOfBirth) {
33+
return currentYear() - yearOfBirth;
34+
}
35+
36+
private boolean isInFuture(int year) {
37+
return currentYear() < year;
38+
}
39+
40+
private int currentYear() {
41+
return Year.now()
42+
.getValue();
43+
}
44+
45+
@GetMapping("/customHeader")
46+
public ResponseEntity<String> customHeader() {
47+
return ResponseEntity.ok()
48+
.header("Custom-Header", "foo")
49+
.body("Custom header set");
50+
}
51+
52+
}

0 commit comments

Comments
 (0)