|
| 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 | + if (isInFuture(yearOfBirth)) { |
| 28 | + return new ResponseEntity<>("Year of birth cannot be in the future", HttpStatus.BAD_REQUEST); |
| 29 | + } |
| 30 | + |
| 31 | + return new ResponseEntity<>("Your age is " + calculateAge(yearOfBirth), HttpStatus.OK); |
| 32 | + } |
| 33 | + |
| 34 | + private int calculateAge(int yearOfBirth) { |
| 35 | + return currentYear() - yearOfBirth; |
| 36 | + } |
| 37 | + |
| 38 | + private boolean isInFuture(int year) { |
| 39 | + return currentYear() < year; |
| 40 | + } |
| 41 | + |
| 42 | + private int currentYear() { |
| 43 | + return Year.now().getValue(); |
| 44 | + } |
| 45 | + |
| 46 | + @GetMapping("/customHeader") |
| 47 | + public ResponseEntity<String> customHeader() { |
| 48 | + HttpHeaders headers = new HttpHeaders(); |
| 49 | + headers.add("Custom-Header", "foo"); |
| 50 | + |
| 51 | + return new ResponseEntity<>("Custom header set", headers, HttpStatus.OK); |
| 52 | + } |
| 53 | + |
| 54 | + @GetMapping("/manual") |
| 55 | + public void manual(HttpServletResponse response) throws IOException { |
| 56 | + response.setHeader("Custom-Header", "foo"); |
| 57 | + response.setStatus(200); |
| 58 | + response.getWriter() |
| 59 | + .println("Hello World!"); |
| 60 | + } |
| 61 | + |
| 62 | +} |
0 commit comments