Spring Boot Cheatsheet

Request Mapping

Use this Spring Boot reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.

Mapping Annotations

AnnotationHTTP MethodEquivalent
@RequestMappingAny (configurable)Base annotation; all others are shortcuts
@GetMappingGET@RequestMapping(method = RequestMethod.GET)
@PostMappingPOST@RequestMapping(method = RequestMethod.POST)
@PutMappingPUT@RequestMapping(method = RequestMethod.PUT)
@PatchMappingPATCH@RequestMapping(method = RequestMethod.PATCH)
@DeleteMappingDELETE@RequestMapping(method = RequestMethod.DELETE)

@RequestMapping Attributes

@RequestMapping(
    value    = "/api/items/{id}",     // path (alias: path)
    method   = RequestMethod.GET,
    params   = "version=2",           // only if query param present/matches
    headers  = "X-Custom=true",       // only if header present/matches
    consumes = MediaType.APPLICATION_JSON_VALUE,  // Content-Type filter
    produces = MediaType.APPLICATION_JSON_VALUE   // Accept header filter
)
public ItemDto getItem(@PathVariable Long id) { ... }

Path Patterns

// Exact match
@GetMapping("/users")

// Path variable
@GetMapping("/users/{id}")
@GetMapping("/users/{userId}/orders/{orderId}")

// Wildcards
@GetMapping("/files/*")          // one path segment
@GetMapping("/files/**")         // zero or more path segments

// Regex constraint on path variable
@GetMapping("/items/{id:[0-9]+}")        // digits only
@GetMapping("/users/{name:[a-z]+}")      // lowercase alpha only

// Optional trailing slash (Spring 6 disables redirect by default)
@GetMapping({"/about", "/about/"})

Path Variable Options

// Name matches parameter name automatically
@GetMapping("/{id}")
public Product get(@PathVariable Long id) { ... }

// Explicit name when they differ
@GetMapping("/{product-id}")
public Product get(@PathVariable("product-id") Long productId) { ... }

// Optional path variable via two mappings
@GetMapping({"/items", "/items/{id}"})
public Object getOrList(@PathVariable Optional<Long> id) { ... }

Query Parameters (@RequestParam)

// Required (throws 400 if missing)
@GetMapping("/search")
public List<Item> search(@RequestParam String q) { ... }

// Optional with default
@GetMapping("/list")
public Page<Item> list(
    @RequestParam(defaultValue = "0")  int page,
    @RequestParam(defaultValue = "20") int size,
    @RequestParam(required = false)    String category
) { ... }

// Multi-value: ?tag=java&tag=spring
@GetMapping("/posts")
public List<Post> byTags(@RequestParam List<String> tag) { ... }

// Map of all params
@GetMapping("/dynamic")
public Result handle(@RequestParam Map<String, String> params) { ... }

Headers (@RequestHeader)

@GetMapping("/secure")
public Data get(
    @RequestHeader("Authorization") String auth,
    @RequestHeader(value = "Accept-Language", defaultValue = "en") String lang
) { ... }

// All headers
@GetMapping("/echo")
public Map<String, String> echo(@RequestHeader Map<String, String> headers) { ... }

Request Body (@RequestBody)

@PostMapping("/users")
public UserDto create(@RequestBody @Valid CreateUserRequest req) { ... }

// Raw string body
@PostMapping("/webhook")
public void webhook(@RequestBody String raw) { ... }

// Byte array body
@PostMapping("/upload-raw")
public void uploadRaw(@RequestBody byte[] bytes) { ... }

Content Negotiation Constraints

// Only accept JSON body
@PostMapping(value = "/items", consumes = MediaType.APPLICATION_JSON_VALUE)
public ItemDto create(@RequestBody @Valid CreateItemRequest req) { ... }

// Only respond with JSON
@GetMapping(value = "/items", produces = MediaType.APPLICATION_JSON_VALUE)
public List<ItemDto> list() { ... }

// Multiple consume types
@PostMapping(consumes = {MediaType.APPLICATION_JSON_VALUE,
                          MediaType.APPLICATION_XML_VALUE})
public void ingest(@RequestBody Payload payload) { ... }

Class-Level vs Method-Level Mapping

@RestController
@RequestMapping("/api/v1/orders")  // common prefix for all methods
public class OrderController {

    @GetMapping                     // → GET /api/v1/orders
    public List<OrderDto> list() { ... }

    @GetMapping("/{id}")            // → GET /api/v1/orders/{id}
    public OrderDto get(@PathVariable Long id) { ... }

    @PostMapping                    // → POST /api/v1/orders
    public OrderDto create(@RequestBody @Valid CreateOrderRequest req) { ... }
}

Matrix Variables

Matrix variables are key-value pairs embedded in path segments separated by semicolons: /cars/42;color=red;seats=4.

// Must enable in WebMvcConfigurer
@Configuration
public class MvcConfig implements WebMvcConfigurer {
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        // Matrix variables work by default in Spring Boot 3;
        // ensure no path variable removal
    }
}

@GetMapping("/cars/{id}")
public Car getCar(
    @PathVariable Long id,
    @MatrixVariable String color,
    @MatrixVariable(required = false, defaultValue = "5") int seats
) { ... }

// Multiple path segments with matrix vars
@GetMapping("/users/{userId}/orders/{orderId}")
public Order get(
    @PathVariable Long userId,
    @PathVariable Long orderId,
    @MatrixVariable(pathVar = "userId") String role
) { ... }

Model Attribute (Form Data)

@PostMapping("/register")
public String register(
    @ModelAttribute @Valid RegistrationForm form,
    BindingResult result
) {
    if (result.hasErrors()) return "register";
    userService.register(form);
    return "redirect:/login";
}

@RequestPart (Multipart)

@PostMapping(value = "/upload", consumes = MediaType.MULTIPART_FORM_DATA_VALUE)
public ResponseEntity<String> upload(
    @RequestPart("metadata") @Valid UploadMetadata meta,
    @RequestPart("file") MultipartFile file
) { ... }

Flash Attributes and Redirects

@PostMapping("/submit")
public String submit(RedirectAttributes attrs) {
    attrs.addAttribute("id", 42);                // appears in URL: /success?id=42
    attrs.addFlashAttribute("message", "Done!");  // survives one redirect, not in URL
    return "redirect:/success";
}

@GetMapping("/success")
public String success(@ModelAttribute("message") String msg) { ... }

Common Pitfalls

  • Ambiguous mapping — two methods with identical paths and methods throw IllegalStateException at startup; use params, headers, or produces to disambiguate.
  • @PathVariable regex not matching — the handler is simply skipped; the request may fall through to a 404.
  • @RequestParam vs @ModelAttribute — for simple flat form data both work; @ModelAttribute populates a POJO; @RequestParam binds a single value.
  • Trailing slash differences — Spring MVC 6+ does not redirect /users//users by default; map both explicitly if needed.
  • Matrix variable semicolons stripped by default in older configs — ensure useDefaultSuffixPattern or removeSemicolonContent is not set to true.