Fading Coder

One Final Commit for the Last Sprint

Home > Tech > Content

Essential Spring Boot Annotations and Their Practical Usage

Tech Jun 5 1

1. Core Class-Level Annotations

Spring Boot provides several annotations to define controller behavior, primarily @RestController and @Controller.

1.1 @RestController

@RestController is a convenience annotation that combines @Controller and @ResponseBody. When applied to a class, all handler methods automatically serialize their return values directly into the HTTP response body (typically as JSON or XML), eliminating the need to annotate each method with @ResponseBody.

@RequestMapping("/api/greet")
@RestController
public class GreetingController {
    @GetMapping("/say-hi")
    public String greet() {
        return "Hello from Spring Boot!";
    }
}

Accessign http://localhost:8080/api/greet/say-hi returns the plain text response directly in the body.

1.2 @Controller

In contrast, @Controller indicates that a class handles web requests and typically returns view names for randering templates (e.g., Thymeleaf, JSP). The return value is interpreted as a logical view name, not raw data.

@RequestMapping("/pages")
@Controller
public class PageController {
    @GetMapping("/home")
    public String homePage() {
        return "index"; // Resolves to index.html or index.jsp
    }
}

This approach is common in server-rendered applications where the backend generates full HTML pages.

1.3 @RequestMapping

@RequestMapping defines URL path mappings at both class and method levels. The full endpoint is the concatenation of class-level and method-level paths.

@RequestMapping("/v1/messages")
@RestController
public class MessageController {
    @GetMapping("/welcome")
    public String welcomeMessage() {
        return "Welcome to version 1!";
    }
}

The endpoint becomes /v1/messages/welcome.

2. Key Method-Level Annotations

2.1 HTTP Method-Specific Variants

While @RequestMapping supports all HTTP methods via its method attribute, Spring offers shorthand annotations:

  • @GetMapping@RequestMapping(method = RequestMethod.GET)
  • @PostMapping@RequestMapping(method = RequestMethod.POST)
  • Similarly for @PutMapping, @DeleteMapping, etc.
@GetMapping("/users/{id}")
public User getUser(@PathVariable Long id) { /* ... */ }

@PostMapping("/users")
public User createUser(@RequestBody User user) { /* ... */ }

Omitting the method restriction allows both GET and POST by default, but explicit annotations improve clarity and security.

2.2 @RequestParam

Binds query parameters or form fields to method arguments. Useful when request paramter names differ from Java variable names or when handling collections.

@GetMapping("/search")
public String search(
    @RequestParam(value = "q", required = false) String query,
    @RequestParam List<String> tags
) {
    // Handles /search?q=spring&tags=java&tags=boot
    return "Query: " + query + ", Tags: " + tags;
}

The required = false attribute makes the parameter optional.

2.3 @RequestBody

Deserializes the HTTP request body (usually JSON) into a Java object using configured message converters (e.g., Jackson).

public class UserDTO {
    private String email;
    private int age;
    // getters/setters
}

@PostMapping("/register")
public ResponseEntity<String> register(@RequestBody UserDTO user) {
    // Process user registration
    return ResponseEntity.ok("Registered: " + user.getEmail());
}

2.4 @PathVariable

Extracts values from URI template variables.

@GetMapping("/articles/{articleId}")
public Article getArticle(@PathVariable("articleId") Long id) {
    return articleService.findById(id);
}

2.5 @RequestPart

Used for multipart requests, especially file uploads. Binds parts of a multipart/form-data request to method parameters.

@PostMapping("/upload")
public String handleFileUpload(@RequestPart("file") MultipartFile uploadedFile) throws IOException {
    Path target = Paths.get("/tmp/uploads", uploadedFile.getOriginalFilename());
    Files.copy(uploadedFile.getInputStream(), target, StandardCopyOption.REPLACE_EXISTING);
    return "Uploaded: " + uploadedFile.getOriginalFilename();
}

2.6 @CookieValue

Reads a specific cookie value from the incoming request.

@GetMapping("/profile")
public String getUserProfile(@CookieValue("session_token") String token) {
    return "Token: " + token;
}

2.7 @SessionAttribute

Retrieves attributes stored in the HTTP session.

@GetMapping("/dashboard")
public String showDashboard(@SessionAttribute(name = "userId", required = false) Long userId) {
    if (userId == null) {
        return "redirect:/login";
    }
    return "dashboard";
}

2.8 @RequestHeader

Accesses HTTP header values.

@GetMapping("/info")
public String clientInfo(@RequestHeader("User-Agent") String userAgent) {
    return "Your browser: " + userAgent;
}

2.9 @ResponseBody

When used with @Controller (not @RestController), this annotation ensures a single method returns data directly in the response body instead of a view name.

@Controller
public class MixedController {
    @GetMapping("/data-only")
    @ResponseBody
    public Map<String, Object> getData() {
        return Map.of("status", "active", "count", 42);
    }

    @GetMapping("/page")
    public String getPage() {
        return "report"; // Returns view
    }
}

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.