Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Spring MVC Annotations

Spring MVC provides a variety of annotations to facilitate the development of web applications. These annotations help in mapping web requests to handler methods, binding request parameters, and defining response types. This guide covers the key annotations used in Spring MVC and their purposes.

Key Spring MVC Annotations

  • @Controller: Indicates that a particular class serves as a controller in a Spring MVC application.
  • @RequestMapping: Used to map web requests to specific handler classes or methods.
  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Specialized annotations for mapping HTTP GET, POST, PUT, and DELETE requests, respectively.
  • @RequestParam: Binds a request parameter to a method parameter in a controller.
  • @PathVariable: Binds a URI template variable to a method parameter in a controller.
  • @ModelAttribute: Binds a method parameter or method return value to a named model attribute and exposes it to a web view.
  • @ResponseBody: Indicates that the return value of a method should be used as the response body in a web request.
  • @RequestBody: Indicates that a method parameter should be bound to the body of the web request.
  • @ExceptionHandler: Used to define a method that handles exceptions thrown by request handling methods in the same controller.

@Controller Annotation

The @Controller annotation is used to indicate that a particular class serves as a controller in a Spring MVC application:

Example:

// HomeController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

@Controller
public class HomeController {
    @GetMapping("/")
    public String home() {
        return "home";
    }
}

@RequestMapping Annotation

The @RequestMapping annotation is used to map web requests to specific handler classes or methods:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
@RequestMapping("/users")
public class UserController {
    @RequestMapping("/list")
    public String listUsers() {
        return "userList";
    }
}

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping Annotations

These annotations are specialized versions of @RequestMapping for specific HTTP methods:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;

@Controller
@RequestMapping("/users")
public class UserController {
    @GetMapping("/list")
    public String listUsers() {
        return "userList";
    }

    @PostMapping("/add")
    public String addUser() {
        return "userAdd";
    }

    @PutMapping("/update")
    public String updateUser() {
        return "userUpdate";
    }

    @DeleteMapping("/delete")
    public String deleteUser() {
        return "userDelete";
    }
}

@RequestParam Annotation

The @RequestParam annotation is used to bind a request parameter to a method parameter in a controller:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.ui.Model;

@Controller
public class UserController {
    @GetMapping("/user")
    public String getUser(@RequestParam("id") int id, Model model) {
        model.addAttribute("userId", id);
        return "userDetail";
    }
}

@PathVariable Annotation

The @PathVariable annotation is used to bind a URI template variable to a method parameter in a controller:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.ui.Model;

@Controller
public class UserController {
    @GetMapping("/user/{id}")
    public String getUser(@PathVariable("id") int id, Model model) {
        model.addAttribute("userId", id);
        return "userDetail";
    }
}

@ModelAttribute Annotation

The @ModelAttribute annotation is used to bind a method parameter or method return value to a named model attribute and expose it to a web view:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.ui.Model;

@Controller
public class UserController {
    @GetMapping("/userForm")
    public String showUserForm(Model model) {
        model.addAttribute("user", new User());
        return "userForm";
    }

    @GetMapping("/userDetails")
    public String submitUserForm(@ModelAttribute User user) {
        return "userDetails";
    }
}

@ResponseBody Annotation

The @ResponseBody annotation indicates that the return value of a method should be used as the response body in a web request:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @GetMapping("/userCount")
    @ResponseBody
    public String getUserCount() {
        return "42";
    }
}

@RequestBody Annotation

The @RequestBody annotation indicates that a method parameter should be bound to the body of the web request:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @PostMapping("/createUser")
    @ResponseBody
    public String createUser(@RequestBody User user) {
        return "User created: " + user.getName();
    }
}

@ExceptionHandler Annotation

The @ExceptionHandler annotation is used to define a method that handles exceptions thrown by request handling methods in the same controller:

Example:

// UserController.java
package com.example.springmvc.controllers;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ResponseBody;

@Controller
public class UserController {
    @GetMapping("/causeError")
    public String causeError() {
        throw new RuntimeException("An error occurred");
    }

    @ExceptionHandler(RuntimeException.class)
    @ResponseBody
    public String handleException(RuntimeException e) {
        return "Handled exception: " + e.getMessage();
    }
}

Key Points

  • @Controller: Indicates that a particular class serves as a controller in a Spring MVC application.
  • @RequestMapping: Used to map web requests to specific handler classes or methods.
  • @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Specialized annotations for mapping HTTP GET, POST, PUT, and DELETE requests, respectively.
  • @RequestParam: Binds a request parameter to a method parameter in a controller.
  • @PathVariable: Binds a URI template variable to a method parameter in a controller.
  • @ModelAttribute: Binds a method parameter or method return value to a named model attribute and exposes it to a web view.
  • @ResponseBody: Indicates that the return value of a method should be used as the response body in a web request.
  • @RequestBody: Indicates that a method parameter should be bound to the body of the web request.
  • @ExceptionHandler: Used to define a method that handles exceptions thrown by request handling methods in the same controller.

Conclusion

Spring MVC provides a rich set of annotations to facilitate the development of web applications. By understanding and using these annotations effectively, developers can build robust and maintainable web applications. Happy coding!