Skip to content

Commit 113ebc2

Browse files
authored
Merge pull request eugenp#4583 from fanatixan/bael-1906
Bael 1906
2 parents 841221d + 913c95c commit 113ebc2

2 files changed

Lines changed: 60 additions & 0 deletions

File tree

Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
package com.baeldung.annotations;
2+
3+
import org.springframework.http.HttpStatus;
4+
import org.springframework.web.bind.annotation.ResponseStatus;
5+
6+
@ResponseStatus(code = HttpStatus.BAD_REQUEST)
7+
public class CustomException extends RuntimeException {
8+
}
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)