Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential Specialized Annotations for Spring MVC Application Development

Tech 1

HTTP Method-Specific Request Mapping Annotations

@PostMapping

Constrains a handler method to accept only POST requests. All attributes mirror those available in @RequestMapping.

@PostMapping("/submit-user")
public String handleUserSubmission() {
    return "redirect:/confirmation.jsp";
}

@GetMapping

Limits a handler method to respond exclusive to GET requests, sharing all valid attributes with @RequestMapping.

@GetMapping("/user-details")
public String fetchUserProfile() {
    return "forward:/profile-display.jsp";
}

Composite Controller Annotation

@RestController

Applied at the class level, this annotation combines @Controller and @ResponseBody, eliminating the need to mark every handler method with @ResponseBody for direct data serialization to HTTP responses (e.g., JSON, XML). Attributes match those of @Controller.

@RestController
public class ProductController {
    // All methods automatically serialize return values to response body
}

JSON Data Processing Annotations

@JsonFormat

Configures formatting for date/time fields when converting Java objects to JSON responses.

  • pattern: Defines the desired date/time string format
  • timezone: Adjusts for timezone offsets (critical when dealing with UTC-based dates)
@DateTimeFormat(pattern = "dd/MM/yyyy")
@JsonFormat(pattern = "dd/MM/yyyy", timezone = "Asia/Shanghai")
private Date orderDate;

@RequestBody

Binds the raw JSON content of an HTTP request body directly to a Java object, skipping standard form paramter parsing. GET requests do not include a request body, so this annotation is incompatible unless required is explicitly set to false.

  • required: Specifies whether a request body is mandatory (defaults to true) Frontend AJAX Example (Simplified ES6+):
window.addEventListener('DOMContentLoaded', () => {
    const formData = { username: "lisi", passcode: "secure456" };
    const jsonString = JSON.stringify(formData);
    fetch('/parse-json-body', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: jsonString
    });
});

Backend Handler Example:

@RequestMapping("/parse-json-body")
public String processJsonPayload(@RequestBody(required = false) Customer customer) {
    System.out.println(customer);
    return "dashboard";
}

Cross-Origin Resource Sharing Annotation

@CrossOrigin

Resolves cross-domain AJAX request restrictions enforced by browsers’ same-origin policy (which blocks scripts from different protocols, hosts, or ports from interacting).

  • origins: Lists allowed origin domains/IPs
  • maxAge: Sets the maximum duration (in seconds) for preflight response caching
@CrossOrigin(origins = "https://external-shop.com", maxAge = 1800)
@RestController
@RequestMapping("/inventory")
public class StockController {
    @GetMapping("/{productId}")
    public StockItem getStockInfo(@PathVariable Long productId) { return new StockItem(); }
}

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.