Common web annotations & Classes

In Spring Web applications, several annotations are commonly used to facilitate the development of web components and controllers. Here are some of the most common annotations in Spring Web:

@Controller: Marks a class as a Spring MVC controller. It is used to handle HTTP requests and return appropriate responses.

@Controller
public class MyController {
    // Controller methods
}

@RequestMapping: Maps HTTP requests to handler methods in a controller. It can be applied at the class level and/or the method level.

@Controller
@RequestMapping("/example")
public class MyController {
    @RequestMapping("/hello")
    public String hello() {
        return "helloPage";
    }
}

@GetMapping, @PostMapping, @PutMapping, @DeleteMapping, @PatchMapping: These annotations are shortcuts for @RequestMapping with specific HTTP methods.

@Controller
@RequestMapping("/example")
public class MyController {
    @GetMapping("/hello")
    public String hello() {
        return "helloPage";
    }
}

@RequestParam: Binds a request parameter to a method parameter.

@Controller
public class MyController {
    @GetMapping("/greet")
    public String greet(@RequestParam(name = "name", defaultValue = "Guest") String name, Model model) {
        model.addAttribute("name", name);
        return "greetingPage";
    }
}

@PathVariable: Extracts values from URI templates and binds them to method parameters.

@Controller
@RequestMapping("/users")
public class UserController {
    @GetMapping("/{id}")
    public String getUserById(@PathVariable Long id, Model model) {
        // Retrieve user with the given id and add it to the model
        return "userDetailsPage";
    }
}

@RequestBody: Used to bind the HTTP request body to a method parameter.

@RestController
@RequestMapping("/api")
public class MyRestController {
    @PostMapping("/create")
    public ResponseEntity<String> create(@RequestBody MyObject myObject) {
        // Process the request body
        // 'myObject' will be automatically populated with the JSON data from the request body
        return ResponseEntity.ok("Object created successfully");
    }
}

@ResponseBody: Indicates that the return value of a method should be serialized directly to the HTTP response body.

@RestController
@RequestMapping("/api")
public class MyRestController {
    @GetMapping("/get")
    @ResponseBody
    public MyObject getObject() {
        // Return an object to be serialized in the response body
        return new MyObject();
    }
}

ResponseEntity

Allows for sending responses body, status and headers on the HTTP response

CustomerDto customerDto = iAccountsService.fetchAccount(mobileNumber);  
return ResponseEntity.status(HttpStatus.OK).body(customerDto);