Essential Annotations for Spring MVC Development
Spring MVC provides a comprehensive set of annotations to streamline web application development. This section details key annotations beyond the basics, focusing on their roles, properties, and implementation.
@PostMapping
This annotation restricts request handling to HTTP POST methods only. It shares all attributes with @RequestMapping.
@PostMapping("/processUser")
public String handleUserSubmission() {
return "redirect:/confirmation";
}
@GetMapping
Similar to @PostMapping, this annotation confines request processing to HTTP GET operations. Its properties align with those of @RequestMapping.
@GetMapping("/fetchUserData")
public String retrieveUserInformation() {
return "view/userDetails";
}
@RestController
Applied at the class level, this annotation indicates that all handler methods within the class will return data directly as the response body, typically in JSON format. It combines the functionality of @Controller and @ResponseBody.
@RestController
public class DataController {
// Handler methods here
}
@JsonFormat
This annotation manages JSON serialization for date and time fields, ensuring proper formatting in responses.
- patttern: Defines the output date/time format.
- timezone: Specifies the timezone to prevent an 8-hour offset if omitted.
@DateTimeFormat(pattern = "yyyy-MM-dd")
@JsonFormat(pattern = "yyyy-MM-dd", timezone = "GMT+8")
private LocalDate registrationDate;
@RequestBody
Used to extract JSON-formatted request body content, converting it directly in to an object. It is not suitable for GET requests, which typically use URL parameters.
- required: Indicates if the request body is mandatory (default: true). When true, GET requests will cause errors; if false, they return null.
Example with client-side AJAX:
$.ajax({
type: "POST",
url: "/api/process",
data: JSON.stringify({username: "john", password: "secret"}),
contentType: "application/json"
});
Server-side implementation:
@PostMapping("/api/process")
public String processRequest(@RequestBody(required = false) UserAccount account) {
System.out.println(account);
return "processed";
}
@CrossOrigin
Cross-origin issues arise from the browser's Same-Origin Policy, which restricts interactions between scripts from different domains. A domain is defined by its protocol, host, and port. For example:
http://example.com:8080/appandhttps://example.com:8080/appdiffer in protocol.http://192.168.1.1:8080/appandhttp://localhost:8080/appdiffer in host.
This annotation resolves cross-origin problems in AJAX requesst by specifying allowed origins.
- origins: List of permitted domain IPs or URLs.
- maxAge: Maximum cache duration for preflight responses in seconds.
@CrossOrigin(origins = "https://trusted-domain.com", maxAge = 1800)
@RestController
@RequestMapping("/api/accounts")
public class AccountManagementController {
@GetMapping("/{accountId}")
public AccountDetails fetchAccount(@PathVariable Long accountId) { }
}