Fading Coder

One Final Commit for the Last Sprint

Home > Notes > Content

Essential Annotations for Spring MVC Development

Notes 2

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/app and https://example.com:8080/app differ in protocol.
  • http://192.168.1.1:8080/app and http://localhost:8080/app differ 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) { }
}
Tags: Spring MVC

Related Articles

Designing Alertmanager Templates for Prometheus Notifications

How to craft Alertmanager templates to format alert messages, improving clarity and presentation. Alertmanager uses Go’s text/template engine with additional helper functions. Alerting rules referenc...

Deploying a Maven Web Application to Tomcat 9 Using the Tomcat Manager

Tomcat 9 does not provide a dedicated Maven plugin. The Tomcat Manager interface, however, is backward-compatible, so the Tomcat 7 Maven Plugin can be used to deploy to Tomcat 9. This guide shows two...

Skipping Errors in MySQL Asynchronous Replication

When a replica halts because the SQL thread encounters an error, you can resume replication by skipping the problematic event(s). Two common approaches are available. Methods to Skip Errors 1) Skip a...

Leave a Comment

Anonymous

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