Skip to content

Commit 7743035

Browse files
committed
custom response handling
1 parent 3b603b4 commit 7743035

1 file changed

Lines changed: 53 additions & 0 deletions

File tree

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
package com.baeldung.annotations;
2+
3+
import java.io.IOException;
4+
import java.time.Year;
5+
6+
import javax.servlet.http.HttpServletResponse;
7+
8+
import org.springframework.http.HttpHeaders;
9+
import org.springframework.http.HttpStatus;
10+
import org.springframework.http.ResponseEntity;
11+
import org.springframework.stereotype.Controller;
12+
import org.springframework.web.bind.annotation.GetMapping;
13+
import org.springframework.web.bind.annotation.RequestMapping;
14+
import org.springframework.web.bind.annotation.RequestParam;
15+
16+
@Controller
17+
@RequestMapping("/customResponse")
18+
public class CustomResponseController {
19+
20+
@GetMapping("/hello")
21+
public ResponseEntity<String> hello() {
22+
return new ResponseEntity<>("Hello World!", HttpStatus.OK);
23+
}
24+
25+
@GetMapping("/age")
26+
public ResponseEntity<String> age(@RequestParam("yearOfBirth") int yearOfBirth) {
27+
int currentYear = Year.now().getValue();
28+
29+
if (currentYear < yearOfBirth) {
30+
return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST);
31+
}
32+
33+
int age = currentYear - yearOfBirth;
34+
35+
return new ResponseEntity<>("Your age is " + age, HttpStatus.OK);
36+
}
37+
38+
@GetMapping("/customHeader")
39+
public ResponseEntity<String> customHeader() {
40+
HttpHeaders headers = new HttpHeaders();
41+
headers.add("Custom-Header", "foo");
42+
43+
return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK);
44+
}
45+
46+
@GetMapping("/manual")
47+
public void manual(HttpServletResponse response) throws IOException {
48+
response.setHeader("Custom-Header", "foo");
49+
response.setStatus(200);
50+
response.getWriter().println("Hello World!");
51+
}
52+
53+
}

0 commit comments

Comments
 (0)