Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Core Spring MVC Annotations for HTTP Request Handling

Tech 1

@RequestMapping

Establishes the routing configuration between incoming HTTP requests and specific controller methods. It functions at both the class and method scopes.

  • Class Scope: Sets the primary URL prefix for the entire controller. If omitted, routes resolve from the application root. When defined, it must start with a forward slash (/).
  • Method Scope: Appends a secondary path to the class prefix, completing the endpoint URI.
  • Configuration Attributes:
    • value / path: Defines the exact URL pattern to match.
    • method: Restricts the handler to specific HTTP verbs (e.g., RequestMethod.GET, RequestMethod.POST).
    • params: Filters invocations based on query parameters. Supports exact key-value matching.
    • headers: Narrows mapping eligibility by inspecting specific HTTP headers in the request.

@RequestParam

Maps named query parameters or form submission fields directly to method arguments in the controller.

  • value: Specifies the exact parameter name expected in the HTTP request.
  • required: Boolean indicator dictating if the parameter is mandatory. Defaults to true, which triggers a client error if missing. Setting it to false allows optional submission.
@Controller
@RequestMapping("/api/accounts")
public class AccountLookupHandler {
    @RequestMapping("/verify")
    public String processAccountQuery(@RequestParam("user_handle") String loginId, 
                                      @RequestParam(value = "is_active", required = false) Boolean isActive) {
        System.out.println("Verifying handle: " + loginId + " | Active Status: " + isActive);
        return "verificationResult";
    }
}

@PathVariable

RESTful design principles advocate for resourec-based URIs where identifiers are embedded directly into the path rather than passed as query strings. @PathVariable extracts these dynamic URI segments and binds them to method parameters, a core capability introduced in Spring 3.0 for robust REST support.

  • value: Corresponds to the placeholder name enclosed in braces within the mapped URL pattern (e.g., /orders/{orderId}).
  • required: Enforces the presence of the URI segment.
@Controller
@RequestMapping("/warehouse")
public class InventoryRoutingController {
    @RequestMapping("/stock/{zoneCode}/{skuNumber}")
    public String locateInventory(@PathVariable("zoneCode") String storageLocation, 
                                  @PathVariable(value = "skuNumber", required = true) Long itemReference) {
        System.out.println("Scanning Zone: " + storageLocation);
        System.out.println("Tracking SKU: " + itemReference);
        return "stockSummary";
    }
}

@RequestHeader

Retrieves specific metadata from the HTTP request headers and injects it into the controller method.

  • value: Targets a particular header field (e.g., Accept-Language, Authorization).
  • required: Determines whether the framework should fail if the specified header is absent.
@Controller
@RequestMapping("/diagnostics")
public class NetworkInspectorController {
    @RequestMapping("/analyze-client")
    public String captureNetworkHeaders(@RequestHeader(value = "X-Forwarded-For", required = false) String proxyAddress) {
        System.out.println("Client Proxy Origin: " + proxyAddress);
        return "diagnosticReport";
    }
}

@CookieValue

Extracts stored HTTP cookie data and passes it as a method parameter within the controller layer.

  • value: Identifies the specific cookie key to retrieve.
  • required: Specifies if the cookie must be present in the browser request.
@Controller
@RequestMapping("/analytics")
public class SessionTrackerController {
    @RequestMapping("/track-visit")
    public String logUserCookie(@CookieValue(name = "VISITOR_ID", required = false) String uniqueToken) {
        System.out.println("Logging visitor token: " + uniqueToken);
        return "trackingConfirmation";
    }
}

Related Articles

Understanding Strong and Weak References in Java

Strong References Strong reference are the most prevalent type of object referencing in Java. When an object has a strong reference pointing to it, the garbage collector will not reclaim its memory. F...

Comprehensive Guide to SSTI Explained with Payload Bypass Techniques

Introduction Server-Side Template Injection (SSTI) is a vulnerability in web applications where user input is improper handled within the template engine and executed on the server. This exploit can r...

Implement Image Upload Functionality for Django Integrated TinyMCE Editor

Django’s Admin panel is highly user-friendly, and pairing it with TinyMCE, an effective rich text editor, simplifies content management significantly. Combining the two is particular useful for bloggi...

Leave a Comment

Anonymous

◎Feel free to join the discussion and share your thoughts.