Spring Framework

Quick Reference on Spring Framework Spring MVC follows Front Controller pattern using DispatcherServlet. Requests go through HandlerMapping → HandlerAdapter → Controller. Controllers delegate to Services. Services manage transactions and business logic. Repositories handle persistence. ViewResolver renders view or returns JSON in REST. Interceptors and ExceptionResolvers handle cross-cuting concerns.

MVC stands for Model-View-Controller, which is a software design pattern used for developing web applications. It separates the application into three interconnected components: the Model, which represents the data and business logic; the View, which is responsible for rendering the user interface; and the Controller, which handles user input and interacts with the Model to update the View. This separation of concerns allows for better organization and maintainability of code in web applications.

Spring MVC

Spring MVC is a web framework built on top of the Spring Framework. It provides a Model-View-Controller architecture for building web applications. Spring MVC allows developers to create flexible and maintainable web applications by separating the different concerns of the application into distinct components. Spring MVC provides a powerful and flexible way to handle HTTP requests and responses, making it easier to build web applications that are scalable and maintainable. It also integrates well with other Spring components, such as Spring Security and Spring Data, allowing developers to build robust and secure web applications. Spring MVC provides a wide range of features, including support for RESTful web services, data binding, validation, and internationalization. It also supports various view technologies, such as JSP, Thymeleaf, and FreeMarker, allowing developers to choose the best view technology for their application. Overall, Spring MVC is a popular choice for building web applications in the Java ecosystem due to its flexibility, ease of use, and integration with other Spring components.

Diagram
Diagram

Layered architecture of Spring MVC can be visualized as follows:

Diagram

Spring MVC Architecture

The Spring MVC architecture consists of several key components that work together to handle HTTP requests and generate responses. These components include: 1. DispatcherServlet: The central component of the Spring MVC architecture, responsible for receiving HTTP requests and dispatching them to the appropriate controllers. 2. HandlerMapping: Responsible for mapping incoming HTTP requests to the appropriate controller based on the URL and HTTP method. 3. Controller: Handles the business logic of the application and interacts with the Model to retrieve data and update the View. 4. Model: Represents the data and business logic of the application. It is responsible for managing the application’s data and providing it to the Controller when requested. 5. View: Responsible for rendering the user interface and generating the HTML response that is sent back to the browser. 6. ViewResolver: Responsible for resolving the logical view names returned by the Controller into actual view implementations, such as JSP or Thymeleaf templates. 7. Interceptors: Optional components that can be used to intercept and modify HTTP requests and responses before they reach the Controller or after they leave the Controller. Overall, the Spring MVC architecture provides a structured and organized way to handle web requests and generate responses, allowing developers to build scalable and maintainable web applications. 8. HandlerAdapter: Responsible for invoking the appropriate method on the Controller to handle the incoming HTTP request. It determines which method to call based on the request mapping and the parameters of the request. 9. ExceptionResolver: Responsible for handling exceptions that occur during the processing of HTTP requests. It allows developers to define custom error pages or responses when exceptions are thrown. 10. LocaleResolver: Responsible for resolving the locale of the user based on the incoming HTTP request. It allows developers to provide localized content and support internationalization in their web applications. 11. ThemeResolver: Responsible for resolving the theme of the user based on the incoming HTTP request. It allows developers to provide different themes for their web applications based on user preferences or other criteria. 12. MultipartResolver: Responsible for handling file uploads in web applications. It allows developers to process multipart HTTP requests and extract the uploaded files for further processing. Overall, these components work together to provide a robust and flexible architecture for building web applications with Spring MVC. By separating the different concerns of the application into distinct components, Spring MVC allows developers to build maintainable and scalable web applications that can easily handle complex business logic and provide a rich user experience. 13. Binding and Validation: Spring MVC provides support for data binding and validation, allowing developers to easily bind incoming HTTP request parameters to Java objects and validate the data before processing it in the Controller. This helps to ensure that the data being processed is valid and reduces the likelihood of errors or security vulnerabilities in the application.

DispatcherServlet

The DispatcherServlet is the central component of the Spring MVC architecture. It acts as the front controller for the application, receiving all incoming HTTP requests and dispatching them to the appropriate controllers for processing. The DispatcherServlet is responsible for coordinating the various components of the Spring MVC architecture, including the HandlerMapping, HandlerAdapter, ViewResolver, and Interceptors. When a request is received, the DispatcherServlet first consults the HandlerMapping to determine which controller should handle the request. Once the appropriate controller is identified, the DispatcherServlet uses the HandlerAdapter to invoke the controller’s method to process the request. After the controller has processed the request and returned a logical view name, the DispatcherServlet consults the ViewResolver to resolve the logical view name into an actual view implementation, such as a JSP or Thymeleaf template. Finally, the DispatcherServlet renders the view and sends the generated HTML response back to the browser. The DispatcherServlet is a key component of the Spring MVC architecture, providing a centralized point of control for handling HTTP requests and coordinating the various components of the application. It is typically configured in the web application’s deployment descriptor (web.xml) or through Java-based configuration using the @Configuration annotation. The DispatcherServlet can be customized and extended to provide additional functionality, such as handling specific types of requests or integrating with other frameworks and libraries. Overall, the DispatcherServlet plays a crucial role in the Spring MVC architecture, enabling developers to build flexible and maintainable web applications that can handle complex business logic and provide a rich user experience.

@SpringBootApplication
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
}

HandlerMapping

The HandlerMapping is a component of the Spring MVC architecture that is responsible for mapping incoming HTTP requests to the appropriate controller based on the URL and HTTP method. When a request is received by the DispatcherServlet, it consults the HandlerMapping to determine which controller should handle the request. The HandlerMapping uses various strategies to map requests to controllers, such as URL patterns, request parameters, and HTTP methods. The most common strategy is to use URL patterns, where the HandlerMapping matches the incoming request URL against a set of predefined patterns to determine which controller should handle the request. For example, a request with the URL "/users" might be mapped to a UserController, while a request with the URL "/products" might be mapped to a ProductController. The HandlerMapping can also use request parameters and HTTP methods to further refine the mapping of requests to controllers. For example, a request with the URL "/users" and the HTTP method "POST" might be mapped to a different controller method than a request with the same URL but the HTTP method "GET". The HandlerMapping is a crucial component of the Spring MVC architecture, as it allows developers to define how incoming requests are routed to the appropriate controllers for processing. By using different mapping strategies, developers can create flexible and maintainable web applications that can handle a wide variety of requests and provide a rich user experience. The HandlerMapping can be configured using annotations, such as @RequestMapping, or through XML configuration. It is also possible to create custom HandlerMapping implementations to provide additional mapping strategies or to integrate with other frameworks and libraries. Overall, the HandlerMapping plays a critical role in the Spring MVC architecture, enabling developers to define how incoming requests are routed to the appropriate controllers for processing and allowing for flexible and maintainable web applications.

@RestController
@RequestMapping("/users")
public class UserController {

    @GetMapping("/{id}")
    public User getUser(@PathVariable Long id) {
        return new User(id, "John");
    }
}

Controller

The Controller is a key component of the Spring MVC architecture that handles the business logic of the application and interacts with the Model to retrieve data and update the View. The Controller is responsible for processing incoming HTTP requests, performing any necessary business logic, and returning a logical view name along with any required model data to the DispatcherServlet. The Controller is typically implemented as a Java class that is annotated with @Controller or @RestController. The @Controller annotation indicates that the class is a Spring MVC controller, while the @RestController annotation indicates that the class is a controller that returns data directly in the response body, typically in JSON format. The Controller contains methods that are mapped to specific HTTP requests using annotations such as @RequestMapping, @GetMapping, @PostMapping, etc. These annotations specify the URL patterns and HTTP methods that the controller methods should handle. For example, a method annotated with @GetMapping("/users") would handle GET requests to the "/users" URL. Inside the controller methods, developers can perform any necessary business logic, such as interacting with services or repositories to retrieve data from a database. The controller methods can also accept parameters from the incoming HTTP request, such as query parameters or path variables, and can return a logical view name along with any required model data to be rendered in the view. The Controller is a crucial component of the Spring MVC architecture, as it serves as the intermediary between the Model and the View, allowing developers to implement the business logic of the application and control the flow of data between the Model and the View. By using annotations to map controller methods to specific HTTP requests, developers can create flexible and maintainable web applications that can handle a wide variety of requests and provide a rich user experience. Overall, the Controller plays a critical role in the Spring MVC architecture, enabling developers to implement the business logic of the application and control the flow of data between the Model and the View, ultimately allowing for the creation of flexible and maintainable web applications.

@Controller
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.findById(id));
        return "user";
    }
}

Service

The Service is a component of the Spring MVC architecture that contains the business logic of the application. It is responsible for performing operations on the data and providing it to the Controller when requested. The Service is typically implemented as a Java class that is annotated with @Service, indicating that it is a Spring service component. The Service contains methods that perform various operations on the data, such as retrieving data from a database, performing calculations, or applying business rules. These methods can be called by the Controller to retrieve data or perform operations as needed. The Service can also interact with other components, such as repositories, to access the underlying data storage and perform CRUD operations on the data. By using a Service layer, developers can separate the business logic of the application from the presentation logic in the Controller, allowing for better organization and maintainability of the code. The Service layer can also be used to implement additional functionality, such as caching, transaction management, or integration with other frameworks and libraries, providing a flexible and maintainable architecture for building web applications with Spring MVC. Overall, the Service is a crucial component of the Spring MVC architecture, as it contains the business logic of the application and provides it to the Controller when requested. By using a Service layer, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience while maintaining a clean separation of concerns between the different layers of the application.

@Controller
@RequestMapping("/users")
public class UserController {

    private final UserService userService;

    public UserController(UserService userService) {
        this.userService = userService;
    }

    @GetMapping("/{id}")
    public String getUser(@PathVariable Long id, Model model) {
        model.addAttribute("user", userService.findById(id));
        return "user";
    }
}

Model

The Model is a component of the Spring MVC architecture that represents the data and business logic of the application. It is responsible for managing the application’s data and providing it to the Controller when requested. The Model is typically implemented as a Java class that contains properties and methods to represent the data and business logic of the application. The Model can be used to encapsulate the data and business logic of the application, allowing for better organization and separation of concerns in the application. The Model can also be used to perform any necessary data validation or transformation before providing the data to the Controller. In Spring MVC, the Model is often used in conjunction with the View to render the user interface. The Controller can add data to the Model, which is then used by the View to generate the HTML response that is sent back to the browser. The Model can also be used to represent the state of the application, allowing developers to manage the application’s data and business logic in a structured and organized way. Overall, the Model is a crucial component of the Spring MVC architecture, as it represents the data and business logic of the application and provides it to the Controller when requested. By encapsulating the data and business logic of the application in the Model, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience. The Model can be implemented using various technologies, such as JavaBeans, POJOs, or even more complex domain models. It can also be integrated with other Spring components, such as Spring Data, to provide additional functionality for managing data and business logic in the application.

@Repository
public interface UserRepository extends JpaRepository<User, Long> {
}

View

The View is a component of the Spring MVC architecture that is responsible for rendering the user interface and generating the HTML response that is sent back to the browser. The View is typically implemented using a view technology, such as JSP, Thymeleaf, or FreeMarker. The View is responsible for taking the data provided by the Controller through the Model and using it to generate the HTML response that is sent back to the browser. The View can also be used to provide a rich user experience by incorporating dynamic content, such as images, videos, and interactive elements. In Spring MVC, the View is often resolved using a ViewResolver, which maps logical view names returned by the Controller to actual view implementations. For example, a logical view name of "home" might be resolved to a JSP file located at "/WEB-INF/views/home.jsp". The View can also be customized and extended to provide additional functionality, such as support for internationalization or integration with other frameworks and libraries. Overall, the View is a crucial component of the Spring MVC architecture, as it is responsible for rendering the user interface and generating the HTML response that is sent back to the browser. By using different view technologies and customizing the View as needed, developers can create flexible and maintainable web applications that provide a rich user experience. The View can also be used to implement different presentation layers for the application, such as a web interface, a mobile interface, or even a desktop interface, allowing developers to create applications that can be accessed from a variety of devices and platforms.

ViewResolver

The ViewResolver is a component of the Spring MVC architecture that is responsible for resolving the logical view names returned by the Controller into actual view implementations, such as JSP or Thymeleaf templates. When a Controller returns a logical view name, the DispatcherServlet consults the ViewResolver to determine which view implementation should be used to render the response. The ViewResolver uses various strategies to resolve logical view names into actual view implementations. The most common strategy is to use a prefix and suffix to construct the path to the view template. For example, if the logical view name is "home" and the prefix is "/WEB-INF/views/" and the suffix is ".jsp", the ViewResolver would resolve the logical view name to the actual view implementation located at "/WEB-INF/views/home.jsp". The ViewResolver can also use other strategies, such as mapping logical view names to specific view implementations based on configuration or using a custom implementation to provide additional functionality. The ViewResolver is a crucial component of the Spring MVC architecture, as it allows developers to separate the logical view names returned by the Controller from the actual view implementations, providing flexibility and maintainability in the application. By using different ViewResolvers or customizing the ViewResolver as needed, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience. The ViewResolver can also be used to implement different presentation layers for the application, such as a web interface, a mobile interface, or even a desktop interface, allowing developers to create applications that can be accessed from a variety of devices and platforms.

@Bean
public InternalResourceViewResolver viewResolver() {
    InternalResourceViewResolver resolver =
            new InternalResourceViewResolver();
    resolver.setPrefix("/WEB-INF/views/");
    resolver.setSuffix(".jsp");
    return resolver;
}

Interceptors

Interceptors are optional components in the Spring MVC architecture that can be used to intercept and modify HTTP requests and responses before they reach the Controller or after they leave the Controller. Interceptors can be used to perform various tasks, such as logging, authentication, authorization, or modifying the request or response data. Interceptors are typically implemented as Java classes that implement the HandlerInterceptor interface. This interface defines three methods: preHandle, postHandle, and afterCompletion. The preHandle method is called before the request reaches the Controller, allowing developers to perform tasks such as authentication or logging. The postHandle method is called after the Controller has processed the request but before the view is rendered, allowing developers to modify the model data or perform additional processing. The afterCompletion method is called after the view has been rendered and the response has been sent back to the browser, allowing developers to perform cleanup tasks or logging. Interceptors can be configured in the Spring MVC application context, allowing developers to specify which interceptors should be applied to which requests. Interceptors can be applied globally to all requests or can be applied to specific URL patterns or HTTP methods. By using interceptors, developers can add additional functionality to their web applications without modifying the core business logic in the Controllers, providing a clean separation of concerns and improving maintainability. Overall, interceptors are a powerful feature of the Spring MVC architecture that allows developers to intercept and modify HTTP requests and responses, providing additional functionality and improving the maintainability of web applications. Interceptors can also be used to implement cross-cutting concerns, such as security or performance monitoring, allowing developers to create robust and secure web applications that can handle complex business logic and provide a rich user experience.

Diagram
@Component
public class LoggingInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request,
                             HttpServletResponse response,
                             Object handler) {
        System.out.println("Request URI: " + request.getRequestURI());
        return true;
    }
}

To Register the Interceptor, you can create a configuration class that implements the WebMvcConfigurer interface and override the addInterceptors method to add your interceptor to the registry.

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoggingInterceptor());
    }
}

HandlerAdapter

The HandlerAdapter is a component of the Spring MVC architecture that is responsible for invoking the appropriate method on the Controller to handle the incoming HTTP request. It determines which method to call based on the request mapping and the parameters of the request. The HandlerAdapter is typically implemented as a Java class that implements the HandlerAdapter interface. This interface defines a single method, handle, which takes an HttpServletRequest, an HttpServletResponse, and a HandlerMethod as parameters. The HandlerAdapter uses the information from the HandlerMethod, which represents the method on the Controller that should handle the request, to determine how to invoke the method. It can use various strategies to determine how to invoke the method, such as using reflection to call the method directly or using a more complex strategy that takes into account the parameters of the request. The HandlerAdapter is a crucial component of the Spring MVC architecture, as it allows for flexible and maintainable web applications by decoupling the Controller from the specifics of how the method is invoked. By using different HandlerAdapters or customizing the HandlerAdapter as needed, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience. The HandlerAdapter can also be used to implement additional functionality, such as support for asynchronous processing or integration with other frameworks and libraries, allowing developers to create robust and scalable web applications that can handle a wide variety of requests and provide a rich user experience.

ExceptionResolver

The ExceptionResolver is a component of the Spring MVC architecture that is responsible for handling exceptions that occur during the processing of HTTP requests. It allows developers to define custom error pages or responses when exceptions are thrown. The ExceptionResolver is typically implemented as a Java class that implements the HandlerExceptionResolver interface. This interface defines a single method, resolveException, which takes an HttpServletRequest, an HttpServletResponse, an Object handler, and an Exception as parameters. The ExceptionResolver uses the information from the exception and the handler to determine how to handle the exception. It can use various strategies to determine how to handle the exception, such as returning a specific error page, returning a JSON response with error details, or even rethrowing the exception to be handled by a higher-level exception handler. The ExceptionResolver is a crucial component of the Spring MVC architecture, as it allows developers to handle exceptions in a consistent and maintainable way, providing a better user experience when errors occur. By using different ExceptionResolvers or customizing the ExceptionResolver as needed, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience even in the face of errors. The ExceptionResolver can also be used to implement additional functionality, such as logging exceptions or sending notifications when exceptions occur, allowing developers to create robust and scalable web applications that can handle a wide variety of requests and provide a rich user experience.

LocaleResolver

The LocaleResolver is a component of the Spring MVC architecture that is responsible for resolving the locale of the user based on the incoming HTTP request. It allows developers to provide localized content and support internationalization in their web applications. The LocaleResolver is typically implemented as a Java class that implements the LocaleResolver interface. This interface defines a single method, resolveLocale, which takes an HttpServletRequest as a parameter and returns a Locale object representing the user’s locale. The LocaleResolver uses various strategies to determine the user’s locale, such as checking the Accept-Language header in the HTTP request, looking for a locale parameter in the request, or using a cookie to store the user’s locale preference. The LocaleResolver is a crucial component of the Spring MVC architecture, as it allows developers to provide localized content and support internationalization in their web applications. By using different LocaleResolvers or customizing the LocaleResolver as needed, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience for users from different locales. The LocaleResolver can also be used to implement additional functionality, such as allowing users to switch between different locales or providing fallback locales when the user’s preferred locale is not available, allowing developers to create robust and scalable web applications that can handle a wide variety of requests and provide a rich user experience for users from different locales.

ThemeResolver

The ThemeResolver is a component of the Spring MVC architecture that is responsible for resolving the theme of the user based on the incoming HTTP request. It allows developers to provide different themes for their web applications based on user preferences or other criteria. The ThemeResolver is typically implemented as a Java class that implements the ThemeResolver interface. This interface defines a single method, resolveThemeName, which takes an HttpServletRequest as a parameter and returns a String representing the name of the theme to be used for the user’s request. The ThemeResolver uses various strategies to determine the user’s theme, such as checking for a theme parameter in the request, looking for a cookie that stores the user’s theme preference, or using a default theme if no specific theme is specified. The ThemeResolver is a crucial component of the Spring MVC architecture, as it allows developers to provide a personalized user experience by allowing users to choose different themes for their web applications. By using different ThemeResolvers or customizing the ThemeResolver as needed, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience for users with different theme preferences. The ThemeResolver can also be used to implement additional functionality, such as allowing users to switch between different themes or providing fallback themes when the user’s preferred theme is not available, allowing developers to create robust and scalable web applications that can handle a wide variety of requests and provide a rich user experience for users with different theme preferences.

MultipartResolver

The MultipartResolver is a component of the Spring MVC architecture that is responsible for handling file uploads in web applications. It allows developers to process multipart HTTP requests and extract the uploaded files for further processing. The MultipartResolver is typically implemented as a Java class that implements the MultipartResolver interface. This interface defines several methods, including isMultipart, which checks if the incoming request is a multipart request, and resolveMultipart, which processes the multipart request and extracts the uploaded files. The MultipartResolver can use various strategies to handle file uploads, such as using the Apache Commons FileUpload library or using the Servlet 3.0 multipart support. The MultipartResolver is a crucial component of the Spring MVC architecture, as it allows developers to easily handle file uploads in their web applications, providing a better user experience and enabling additional functionality. By using different MultipartResolvers or customizing the MultipartResolver as needed, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience when it comes to file uploads. The MultipartResolver can also be used to implement additional functionality, such as validating uploaded files or providing progress indicators for file uploads, allowing developers to create robust and scalable web applications that can handle a wide variety of requests and provide a rich user experience when it comes to file uploads.

Binding and Validation

Spring MVC provides support for data binding and validation, allowing developers to easily bind incoming HTTP request parameters to Java objects and validate the data before processing it in the Controller. This helps to ensure that the data being processed is valid and reduces the likelihood of errors or security vulnerabilities in the application. Data binding in Spring MVC is typically achieved using the @ModelAttribute annotation, which allows developers to bind request parameters to Java objects. For example, a form submission with fields for "username" and "password" can be bound to a User object with corresponding properties. Validation in Spring MVC can be performed using the @Valid annotation, which triggers validation of the bound object based on constraints defined in the object’s class. For example, if the User class has a @NotNull constraint on the "username" property, the validation will fail if the "username" field is left empty in the form submission. Spring MVC also provides support for custom validators, allowing developers to implement their own validation logic as needed. By using data binding and validation in Spring MVC, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience while ensuring that the data being processed is valid and secure. Overall, data binding and validation are important features of the Spring MVC architecture that help to ensure the integrity and security of web applications while providing a better user experience. By using these features effectively, developers can create robust and scalable web applications that can handle a wide variety of requests and provide a rich user experience while maintaining the integrity and security of the data being processed.

public class UserDTO {

    @NotBlank
    private String name;

    @Email
    private String email;

    // getters/setters
}

@PostMapping("/users")
public ResponseEntity<String> createUser(
        @Valid @RequestBody UserDTO userDTO) {
    return ResponseEntity.ok("User created");
}

Power of Annotations

Spring MVC makes extensive use of annotations to simplify the development of web applications. Annotations provide a declarative way to configure and customize the behavior of the various components in the Spring MVC architecture, allowing developers to write cleaner and more maintainable code. Some of the key annotations used in Spring MVC include: 1. @Controller: Indicates that a class is a Spring MVC controller. 2. @RestController: Indicates that a class is a Spring MVC controller that returns data directly in the response body, typically in JSON format. 3. @RequestMapping: Used to map HTTP requests to specific controller methods based on URL patterns and HTTP methods. 4. @GetMapping, @PostMapping, @PutMapping, @DeleteMapping: Specialized annotations for mapping specific HTTP methods to controller methods. 5. @ModelAttribute: Used to bind request parameters to Java objects for data binding. 6. @Valid: Used to trigger validation of bound objects based on constraints defined in the object’s class. 7. @Autowired: Used for dependency injection to automatically wire components together. 8. @Component, @Service, @Repository: Used to indicate that a class is a Spring component, service, or repository, respectively, allowing for automatic detection and wiring of these components in the application context. 9. @PathVariable: Used to bind URI template variables to method parameters in controller methods. 10. @RequestParam: Used to bind query parameters or form parameters to method parameters in controller methods. 11. @ConrollerAdvice: Used to define global exception handling, data binding, and model attribute handling across all controllers in the application. 12. @ResponseBody: Used to indicate that the return value of a controller method should be written directly to the HTTP response body, typically in JSON format. 13. @initBinder: Used to customize the data binding process for specific controller methods or globally across all controllers. 14. @SessionAttributes: Used to indicate that certain model attributes should be stored in the session and made available across multiple requests. 15. @CrossOrigin: Used to enable Cross-Origin Resource Sharing (CORS) for specific controller methods or globally across all controllers, allowing for requests from different origins to access the resources of the application. 16. @ExceptionHandler: Used to define methods that handle specific exceptions thrown by controller methods, allowing for custom error handling and responses when exceptions occur.

By using these annotations effectively, developers can create flexible and maintainable web applications that can handle complex business logic and provide a rich user experience while reducing the amount of boilerplate code needed to configure and customize the behavior of the application. Overall, the power of annotations in Spring MVC is a key feature that allows developers to write cleaner and more maintainable code while providing a rich set of features for building robust and scalable web applications. By leveraging the power of annotations, developers can create web applications that are easy to understand, maintain, and extend, ultimately providing a better user experience and enabling the creation of complex and feature-rich web applications with ease.