Swiftorial Logo
Home
Swift Lessons
Matchups
CodeSnaps
Tutorials
Career
Resources

Spring MVC Controllers

In Spring MVC, controllers are the components responsible for handling incoming HTTP requests and returning appropriate responses. Controllers process user input, interact with the model, and return views for rendering. This guide covers the key concepts and annotations used to define and configure Spring MVC controllers.

Key Concepts of Spring MVC Controllers

  • @Controller: Indicates that a particular class serves as a controller in a Spring MVC application.
  • @RequestMapping: Maps 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.

Defining a Simple Controller

A simple controller can be defined using the @Controller annotation and mapped to a URL using @RequestMapping:

HomeController.java

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

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

@Controller
public class HomeController {
    @GetMapping("/")
    public String home(Model model) {
        model.addAttribute("message", "Welcome to Spring MVC!");
        return "home";
    }
}

Handling Different HTTP Methods

Spring MVC provides specialized annotations to handle different 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";
    }
}

Binding Request Parameters

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";
    }
}

Binding URI Template Variables

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";
    }
}

Binding Model Attributes

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";
    }
}

Returning Response Body

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";
    }
}

Handling Request Body

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();
    }
}

Handling Exceptions

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: Maps 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 controllers are the core components responsible for handling incoming HTTP requests, processing user input, interacting with the model, and returning appropriate views. By understanding and using the various annotations provided by Spring MVC, developers can build robust and maintainable web applications. Happy coding!