|
| 1 | +package com.baeldung.spring.controller; |
| 2 | + |
| 3 | +import java.util.List; |
| 4 | +import java.util.Map; |
| 5 | + |
| 6 | +import org.springframework.stereotype.Controller; |
| 7 | +import org.springframework.web.bind.annotation.GetMapping; |
| 8 | +import org.springframework.web.bind.annotation.PathVariable; |
| 9 | +import org.springframework.web.bind.annotation.PostMapping; |
| 10 | +import org.springframework.web.bind.annotation.RequestParam; |
| 11 | +import org.springframework.web.bind.annotation.ResponseBody; |
| 12 | + |
| 13 | + |
| 14 | +@Controller |
| 15 | +public class RequestParamController { |
| 16 | + |
| 17 | + @GetMapping("/api/foos") |
| 18 | + @ResponseBody |
| 19 | + public String getFoos(@RequestParam String id){ |
| 20 | + return "ID: " + id; |
| 21 | + } |
| 22 | + |
| 23 | + @PostMapping("/api/foos") |
| 24 | + @ResponseBody |
| 25 | + public String addFoo(@RequestParam(name = "id") String fooId, @RequestParam String name){ |
| 26 | + return "ID: " + fooId; |
| 27 | + } |
| 28 | + |
| 29 | + @GetMapping("/api/foos2") |
| 30 | + @ResponseBody |
| 31 | + public String getFoos2(@RequestParam(required = false) String id){ |
| 32 | + return "ID: " + id; |
| 33 | + } |
| 34 | + |
| 35 | + @GetMapping("/api/foos3") |
| 36 | + @ResponseBody |
| 37 | + public String getFoos3(@RequestParam(defaultValue = "test") String id){ |
| 38 | + return "ID: " + id; |
| 39 | + } |
| 40 | + |
| 41 | + @PostMapping("/api/foos1") |
| 42 | + @ResponseBody |
| 43 | + public String updateFoos(@RequestParam Map<String,String> allParams){ |
| 44 | + return "Parameters are " + allParams.entrySet(); |
| 45 | + } |
| 46 | + |
| 47 | + @GetMapping("/api/foos4") |
| 48 | + @ResponseBody |
| 49 | + public String getFoos4(@RequestParam List<String> id){ |
| 50 | + return "ID are " + id; |
| 51 | + } |
| 52 | + |
| 53 | + @GetMapping("/foos/{id}") |
| 54 | + @ResponseBody |
| 55 | + public String getFooById(@PathVariable String id){ |
| 56 | + return "ID: " + id; |
| 57 | + } |
| 58 | + |
| 59 | + @GetMapping("/foos") |
| 60 | + @ResponseBody |
| 61 | + public String getFooByIdUsingQueryParam(@RequestParam String id){ |
| 62 | + return "ID: " + id; |
| 63 | + } |
| 64 | + |
| 65 | + @GetMapping({"/myfoos/optional", "/myfoos/optional/{id}"}) |
| 66 | + @ResponseBody |
| 67 | + public String getFooByOptionalId(@PathVariable(required = false) String id){ |
| 68 | + return "ID: " + id; |
| 69 | + } |
| 70 | + |
| 71 | + @GetMapping("/myfoos/optionalParam") |
| 72 | + @ResponseBody |
| 73 | + public String getFooByOptionalIdUsingQueryParam(@RequestParam(required = false) String id){ |
| 74 | + return "ID: " + id; |
| 75 | + } |
| 76 | + |
| 77 | + |
| 78 | + |
| 79 | +} |
0 commit comments