Essential Specialized Annotations for Spring MVC Application Development
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 formattimezone: 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 totrue) 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/IPsmaxAge: 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(); }
}