Handling Exceptions and Configuring View Resolvers in Spring MVC
Course: Advanced Java Training
Topic: Handling Exceptions and Configuring View Resolvers
Course Link: Advanced Java Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy Homepage
1. Introduction
Exception handling and view resolver configuration are important concepts in Spring MVC. Exception handling helps an application respond properly when a request fails, a resource is missing, validation fails, or an unexpected server-side problem occurs. View resolvers help Spring MVC locate the correct page when a controller returns a logical view name.
These concepts work together in traditional MVC applications. A controller processes a request, prepares model data, and returns a view name. If an error occurs, Spring can route the exception to an appropriate handler and display an error page. The view resolver then maps the selected logical view name to the actual template or page.
Learning Objectives
- Understand exceptions and their role in Spring MVC.
- Handle exceptions using
@ExceptionHandler.
- Implement centralized exception handling using
@ControllerAdvice.
- Understand HTTP status codes and custom error pages.
- Learn how view resolvers work.
- Configure JSP and Thymeleaf view resolution.
- Combine exception handling with model attributes and view rendering.
- Identify common configuration mistakes and troubleshoot them.
2. Understanding Exceptions in Spring MVC
An exception is an event that interrupts the normal execution of a program. In a web application, exceptions may occur while processing request parameters, validating form data, executing business logic, accessing a database, or rendering a view.
Without appropriate handling, an exception can produce an unclear error response or expose internal implementation details. Proper exception handling provides a meaningful response while protecting sensitive information.
Common Types of Exceptions
| Exception or Failure |
Possible Cause |
Typical Handling |
NumberFormatException |
Invalid text converted to a number in application code. |
Validate input and return a suitable client error. |
MethodArgumentTypeMismatchException |
A request parameter or path variable cannot be converted to the required type. |
Return a clear 400 Bad Request response. |
MethodArgumentNotValidException |
A request object fails Bean Validation in a supported binding scenario. |
Return validation errors or redisplay a form with messages. |
HttpMessageNotReadableException |
A request body is malformed or cannot be deserialized. |
Return a suitable 400 response. |
DataAccessException |
A database access operation fails. |
Log diagnostic details securely and return a safe response. |
| Custom business exception |
A business rule is violated or a requested resource is unavailable. |
Handle it with an application-specific exception handler. |
| Unexpected runtime exception |
An unforeseen application failure occurs. |
Log details securely and return a generic 500 response. |
3. How Exception Handling Works in Spring MVC
Spring MVC provides several mechanisms for handling exceptions. Depending on the exception and configuration, Spring can locate an appropriate exception handler, set an HTTP status, return a response body, or select an error view.
- The client sends an HTTP request.
- The
DispatcherServlet routes the request to the matching controller.
- The controller or a service executes application logic.
- If an exception occurs, Spring searches for an applicable exception handler.
- A local
@ExceptionHandler, applicable controller advice, or another configured resolver may handle the exception.
- The handler returns an error response, a view name, or another supported result.
- If a view is selected, Spring resolves and renders it. If a response body is returned, the response is written using the appropriate mechanism.
4. Handling Exceptions with @ExceptionHandler
The @ExceptionHandler annotation defines a method that handles specified exception types. When placed inside a controller, it normally handles matching exceptions raised by handler methods within that controller.
Example: Handling an Invalid Argument
package com.example.controller;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
@Controller
public class ReportController {
@GetMapping("/report")
public String showReport() {
throw new IllegalArgumentException("Invalid report request");
}
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleInvalidArgument(
IllegalArgumentException exception,
Model model) {
model.addAttribute(
"errorMessage",
"The report request contains invalid information."
);
return "error/bad-request";
}
}
Explanation:
@Controller identifies the class as a Spring MVC controller.
@GetMapping("/report") maps GET requests to the report endpoint.
@ExceptionHandler(IllegalArgumentException.class) identifies the exception type handled by the method.
@ResponseStatus(HttpStatus.BAD_REQUEST) sets the response status to 400.
Model supplies a safe error message to the view.
return "error/bad-request" selects the logical view name.
The corresponding template must exist and be supported by the configured view resolver. The example uses a generic error message instead of exposing internal exception details.
5. Centralized Exception Handling with @ControllerAdvice
When several controllers need consistent exception handling, writing the same handler in every controller creates duplication. Spring provides @ControllerAdvice to apply shared controller-related behavior across multiple controllers.
For REST APIs, @RestControllerAdvice is often appropriate because handler return values are written to the response body by default.
Example: Global Exception Handler for MVC Views
package com.example.exception;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public String handleBadRequest(
IllegalArgumentException exception,
Model model) {
model.addAttribute(
"errorMessage",
"The request could not be processed."
);
return "error/bad-request";
}
@ExceptionHandler(Exception.class)
@ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
public String handleUnexpectedError(
Exception exception,
Model model) {
model.addAttribute(
"errorMessage",
"Something went wrong. Please try again later."
);
return "error/general";
}
}
Explanation:
@ControllerAdvice enables shared exception handling for applicable controllers.
- The first method handles invalid arguments and returns a 400 status.
- The second method provides a fallback for unexpected exceptions.
- The returned strings identify error views, not literal response text.
The broad Exception.class handler should be a fallback, not a replacement for specific handlers. Log unexpected failures securely and avoid exposing stack traces to users.
Benefits of Centralized Exception Handling
- Reduces duplicate exception-handling code.
- Provides consistent error pages and response messages.
- Makes controller classes easier to maintain.
- Allows shared error-handling policies to be managed in one place.
- Separates business logic from error presentation.
6. Creating Custom Exceptions
Custom exceptions allow an application to represent business-specific failures clearly. For example, a course management application may need a dedicated exception when a requested course cannot be found.
Step 1: Create a Custom Exception
package com.example.exception;
public class CourseNotFoundException extends RuntimeException {
public CourseNotFoundException(String message) {
super(message);
}
}
Step 2: Throw the Exception from Application Logic
package com.example.service;
import com.example.exception.CourseNotFoundException;
import org.springframework.stereotype.Service;
@Service
public class CourseService {
public String findCourse(Long id) {
if (id == null || id != 1L) {
throw new CourseNotFoundException("Course not found");
}
return "Advanced Java";
}
}
This service is a simplified demonstration. In a real application, the service would normally query a repository and throw the exception when no matching record is found.
Step 3: Handle the Custom Exception
package com.example.exception;
import org.springframework.http.HttpStatus;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
@ControllerAdvice
public class CourseExceptionHandler {
@ExceptionHandler(CourseNotFoundException.class)
@ResponseStatus(HttpStatus.NOT_FOUND)
public String handleCourseNotFound(
CourseNotFoundException exception,
Model model) {
model.addAttribute(
"errorMessage",
"The requested course could not be found."
);
return "error/course-not-found";
}
}
The handler returns a 404 status and selects an error view. A specific custom exception is generally preferable to using a generic exception to represent a known business condition.
7. Understanding HTTP Status Codes
HTTP status codes communicate the outcome of a request. Selecting an appropriate status code helps browsers, API clients, and monitoring systems understand whether a request succeeded or failed.
| Status Code |
Meaning |
Example |
| 400 Bad Request |
The request contains invalid input. |
Malformed request data or invalid parameter. |
| 401 Unauthorized |
Valid authentication is missing or has failed. |
A protected endpoint requires login. |
| 403 Forbidden |
The user is not permitted to access the resource. |
A user lacks the required permission. |
| 404 Not Found |
The requested resource cannot be found. |
A course ID does not exist. |
| 405 Method Not Allowed |
The endpoint does not support the HTTP method used. |
A POST request is sent to a GET-only endpoint. |
| 409 Conflict |
The request conflicts with the current resource state. |
A duplicate entry violates a uniqueness rule. |
| 500 Internal Server Error |
An unexpected server-side failure occurred. |
An unhandled application exception. |
| 503 Service Unavailable |
The service is temporarily unable to handle requests. |
A service is temporarily unavailable. |
8. Creating Custom Error Views
In a view-based application, an exception handler can return a logical view name for a custom error page. The page should explain the problem in a user-friendly way without revealing internal technical details.
Example: Course Not Found Template
For a Thymeleaf application, create src/main/resources/templates/error/course-not-found.html.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Course Not Found</title>
</head>
<body>
<h1>Course Not Found</h1>
<p th:text="${errorMessage}">
The requested course could not be found.
</p>
<a href="/">Return to Home</a>
</body>
</html>
The template displays the message supplied by the exception handler. Adjust the home-page link to match your application's routing structure.
9. Introduction to View Resolvers
A view resolver is a Spring MVC component that translates a logical view name returned by a controller into an actual view resource or view implementation. This lets controllers return names such as "home" or "error/general" without hardcoding the full location of each template.
For example, a controller may return "home". Depending on the configured view technology, Spring might resolve it to a JSP page or a Thymeleaf template. The selected view is then responsible for rendering the model data into the HTTP response. Read the Spring MVC View Resolution documentation.
Why Are View Resolvers Needed?
- They separate controller logic from template file locations.
- They support consistent view naming across the application.
- They allow applications to use different supported view technologies.
- They simplify changes to template locations and file extensions.
- They help Spring MVC render the correct page after request processing.
10. Understanding Logical View Names
A logical view name identifies the intended view without necessarily specifying its physical path or file extension. The configured view resolver determines how that name is interpreted.
| Controller Return Value |
Possible Resolved View |
Technology |
"home" |
/WEB-INF/views/home.jsp |
JSP with a matching prefix and suffix. |
"student" |
templates/student.html |
Thymeleaf with its configured template resolver. |
"error/general" |
A template under the configured error-view location. |
Depends on the application's configuration. |
These mappings are examples, not universal paths. The actual location depends on the selected view technology and application configuration.
11. Configuring a View Resolver for JSP
JavaServer Pages (JSP) is a traditional server-side view technology used in Java web applications. The InternalResourceViewResolver maps logical view names to JSP files by applying a configured prefix and suffix.
For example, if a controller returns "home", a resolver with the prefix /WEB-INF/views/ and suffix .jsp resolves the name to /WEB-INF/views/home.jsp.
Java-Based Configuration
package com.example.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
@Configuration
public class WebMvcConfiguration {
@Bean
public ViewResolver viewResolver() {
InternalResourceViewResolver resolver =
new InternalResourceViewResolver();
resolver.setPrefix("/WEB-INF/views/");
resolver.setSuffix(".jsp");
return resolver;
}
}
How it works:
@Configuration identifies the class as a configuration class.
@Bean registers the view resolver in the Spring application context.
setPrefix() specifies the directory containing JSP views.
setSuffix() defines the file extension.
- The resolver combines the prefix, logical view name, and suffix to locate the JSP resource.
Example JSP File
Create home.jsp inside the configured /WEB-INF/views/ directory.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<title>Home Page</title>
</head>
<body>
<h1>Welcome to Spring MVC</h1>
<p>Your JSP view has been resolved successfully.</p>
</body>
</html>
Important: JSP support depends on the application's servlet container and packaging. JSP is generally more straightforward in traditional WAR-based deployments. For Spring Boot applications, verify JSP compatibility with the chosen embedded server and packaging format before selecting this approach.
12. Configuring Thymeleaf View Resolution
Thymeleaf is a server-side template engine commonly used with Spring Boot and Spring MVC. It supports HTML templates and allows dynamic data to be displayed through template expressions.
In a typical Spring Boot application, adding the compatible Thymeleaf starter enables automatic configuration of the template engine and view resolver. Templates are commonly stored under src/main/resources/templates/.
Example Maven Dependency
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-thymeleaf</artifactId>
</dependency>
Use the version managed by your Spring Boot project rather than adding an arbitrary version. Spring Boot dependency management typically handles compatible starter dependencies.
Example Controller
package com.example.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
@Controller
public class HomeController {
@GetMapping("/home")
public String showHome(Model model) {
model.addAttribute("message", "Welcome to the application");
return "home";
}
}
Example Thymeleaf Template
Create home.html in src/main/resources/templates/.
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<title>Home Page</title>
</head>
<body>
<h1 th:text="${message}">Welcome</h1>
</body>
</html>
When a user visits /home, Spring MVC invokes the controller, places the message in the model, resolves the logical view name home, and renders the Thymeleaf template.
Customizing Thymeleaf Properties
In Spring Boot, common template settings can be configured in application.properties.
spring.thymeleaf.prefix=classpath:/templates/
spring.thymeleaf.suffix=.html
spring.thymeleaf.mode=HTML
spring.thymeleaf.cache=true
These settings illustrate typical defaults and configuration options. Spring Boot normally configures them automatically. Explicit configuration is only needed when changing the defaults. During local development, disabling template caching can make template changes visible more quickly; production applications generally benefit from caching.
13. Understanding SimpleMappingExceptionResolver
SimpleMappingExceptionResolver is a Spring MVC exception resolver that maps exception class names to logical error view names. It can be useful in traditional applications that need basic exception-to-view mappings without writing a separate handler method for every exception.
Example Configuration
package com.example.config;
import java.util.Properties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.handler.SimpleMappingExceptionResolver;
@Configuration
public class ExceptionViewConfiguration {
@Bean
public SimpleMappingExceptionResolver
simpleMappingExceptionResolver() {
SimpleMappingExceptionResolver resolver =
new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.setProperty(
"java.lang.IllegalArgumentException",
"error/bad-request"
);
mappings.setProperty(
"java.lang.Exception",
"error/general"
);
resolver.setExceptionMappings(mappings);
resolver.setDefaultErrorView("error/general");
resolver.setDefaultStatusCode(500);
return resolver;
}
}
This configuration illustrates how exception types can be associated with view names. The default status code applies to the configured default error view; do not assume it automatically assigns a suitable status to every mapped exception. For precise status handling, use explicit exception handlers or another appropriate status-aware mechanism.
When Should You Use It?
- For simple exception-to-view mappings in traditional MVC applications.
- When the application needs a default error view for selected failures.
- When annotation-based exception handling is not the preferred approach.
For many annotation-driven applications, @ControllerAdvice with specific @ExceptionHandler methods offers clearer control over model attributes, status codes, and error responses.
14. Exception Handling with ModelAndView
An exception handler can return a ModelAndView when both the error view and model attributes need to be provided together. This is useful in traditional MVC applications that render custom error pages.
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.ModelAndView;
@ControllerAdvice
public class GlobalViewExceptionHandler {
@ExceptionHandler(IllegalArgumentException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public ModelAndView handleInvalidRequest(
IllegalArgumentException exception) {
ModelAndView mav =
new ModelAndView("error/bad-request");
mav.addObject(
"errorMessage",
"Please check the information you submitted."
);
return mav;
}
}
The handler selects error/bad-request as the logical view name and adds an error message to the model. The response status is explicitly set to 400. The configured view resolver must be able to locate the requested error template.
15. Redirects and View Resolvers
Sometimes a controller should redirect the user to another endpoint instead of rendering a view directly. Spring MVC supports redirect view names using the redirect: prefix.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
@Controller
public class RegistrationController {
@PostMapping("/register")
public String register() {
// Perform registration through the service layer.
return "redirect:/registration-success";
}
}
The redirect instructs the browser to make a new request to the destination URL. It differs from returning a normal logical view name, which is resolved to a view for rendering.
For passing a short-lived message through a redirect, Spring MVC provides RedirectAttributes and flash attributes.
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
@Controller
public class CourseRegistrationController {
@PostMapping("/course-registration")
public String registerCourse(
RedirectAttributes redirectAttributes) {
redirectAttributes.addFlashAttribute(
"message",
"Registration submitted successfully."
);
return "redirect:/registration-success";
}
}
Flash attributes are intended to survive the redirect to the next request and are typically removed after being consumed. They are more appropriate for one-time messages than expecting the original request's model attributes to remain available after a redirect.
16. Configuring View Resolvers in Traditional Spring MVC
Traditional Spring MVC applications may use Java-based configuration or XML configuration. The selected view technology determines which resolver and supporting components are required.
Example XML Configuration for JSP
<bean id="viewResolver"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"/>
<property name="suffix" value=".jsp"/>
</bean>
This example is a fragment for a Spring application context. It must be included in a valid configuration file loaded by the application. Avoid configuring duplicate resolvers that compete to resolve the same view names unless their order and responsibilities are intentional.
Important Configuration Considerations
- Ensure the view resolver is registered in the relevant Spring MVC application context.
- Confirm that the prefix and suffix match the actual template location and extension.
- Verify that the selected view technology is supported by the application runtime.
- Check component scanning so that controllers and advice classes are registered.
- Keep view names consistent between controllers, exception handlers, and templates.
- Use a dedicated error-template directory to organize error pages clearly.
17. Spring Boot Error Handling Considerations
Spring Boot provides default error-handling behavior for web applications. Depending on configuration and request type, an error may be rendered as an HTML page or returned as structured response data. Applications can customize this behavior with controller advice, custom error controllers, and error-page templates.
Spring Boot commonly supports an error template under src/main/resources/templates/error/ when the relevant view-based error handling is configured. The exact behavior depends on whether the exception is handled by controller advice, the servlet container, or Spring Boot's default error infrastructure.
Recommended Error Handling Strategy
- Handle predictable business exceptions explicitly.
- Use centralized exception handling for shared controller behavior.
- Return appropriate status codes for client and server errors.
- Provide user-friendly HTML pages for browser-based MVC applications.
- Provide structured error responses for REST APIs.
- Log unexpected failures with sufficient diagnostic context while protecting sensitive information.
- Test error handling for both normal and exceptional request paths.
18. Troubleshooting Exception Handling and View Resolution
| Problem |
Possible Cause |
Solution |
| Default error page appears |
No custom handler or matching error view is being used. |
Check exception handling, template names, and Spring Boot error configuration. |
| Template or JSP not found |
Incorrect prefix, suffix, template location, or view name. |
Verify the resolver configuration and physical file path. |
| Exception handler is not invoked |
The handler does not match the exception, is not registered, or the failure occurs outside the relevant MVC handling path. |
Check the exception type, component scanning, advice scope, and server logs. |
| Wrong HTTP status is returned |
Status configuration is missing or the response status is set elsewhere. |
Inspect @ResponseStatus, ResponseEntity, and resolver behavior. |
| Error message is missing |
The model key differs from the template expression. |
Match the attribute name in the handler and view. |
| Exception details are exposed |
The error template displays raw exception messages or stack traces. |
Display safe messages and keep detailed diagnostics in protected logs. |
| Redirect loses model data |
Regular request model attributes are not retained for the new request. |
Use flash attributes or another suitable mechanism for redirect data. |
| JSP fails after packaging |
The deployed runtime or packaging format does not support the JSP setup. |
Verify servlet container compatibility, WAR packaging, and JSP dependencies. |
19. Best Practices
- Prefer specific exception handlers over a single broad catch-all handler.
- Use
@ControllerAdvice to centralize shared MVC exception handling.
- Use
@RestControllerAdvice when the API should return structured error bodies.
- Choose HTTP status codes that accurately describe the outcome.
- Never expose stack traces, credentials, internal file paths, or database details in public error messages.
- Log unexpected exceptions securely and include a request or correlation identifier when available.
- Keep error templates simple, accessible, and consistent with the rest of the application.
- Use the correct view resolver for the selected view technology.
- Keep controller logic separate from view rendering and business operations.
- Test missing resources, invalid input, validation failures, and unexpected exceptions.
- Avoid duplicate or conflicting view resolver configuration.
- Review framework and Spring Boot version differences when following configuration examples.
20. Practical Project: Course Portal Error Handling
Build a small course portal that displays course information and handles errors with custom views. Use Spring MVC with Thymeleaf or JSP, depending on the project setup.
Project Requirements
- Create a controller endpoint that displays a course by its ID.
- Move course retrieval logic into a service class.
- Create a custom
CourseNotFoundException.
- Use
@ControllerAdvice to handle the custom exception.
- Return a 404 status when a course does not exist.
- Create a user-friendly course-not-found view.
- Configure the appropriate view resolver or template engine.
- Add a general error page for unexpected failures.
- Test valid course IDs, missing IDs, invalid parameters, and unexpected errors.
Expected Behavior
| Scenario |
Expected Result |
| Valid course ID |
Display the course details page. |
| Unknown course ID |
Display a course-not-found page with HTTP 404. |
| Invalid ID format |
Return an appropriate client error response. |
| Unexpected server failure |
Display a generic error page with HTTP 500 where appropriate. |
| Incorrect view configuration |
Identify the issue through application logs and resolver settings. |
21. Interview Questions and Answers
Q1. What is exception handling in Spring MVC?
It is the process of managing exceptions raised during request processing and producing an appropriate response, such as an error page or structured error body.
Q2. What is the purpose of @ExceptionHandler?
It maps specific exception types to handler methods that can return a view, a response body, or another supported response type.
Q3. What is the difference between @ControllerAdvice and @RestControllerAdvice?
@ControllerAdvice provides shared controller behavior and can return views. @RestControllerAdvice combines controller advice with response-body behavior, making it useful for REST API responses.
Q4. What is a view resolver?
A view resolver maps a logical view name returned by a controller to an actual view resource or view implementation.
Q5. Why are prefix and suffix used in JSP view resolution?
The prefix defines the directory containing JSP files, and the suffix defines their extension. Together with the logical view name, they identify the JSP resource.
Q6. Can an exception handler return ModelAndView?
Yes. It can specify the error view and add model attributes that the view needs to display an error message.
Q7. What is SimpleMappingExceptionResolver?
It is a Spring MVC exception resolver that maps exception class names to logical view names for basic exception-to-view handling.
Q8. How should unexpected exceptions be handled?
Log diagnostic details securely, return a generic server error response, and avoid revealing internal implementation details to users.
Q9. What is the difference between returning a view and redirecting?
Returning a normal view name renders a view for the current request. A redirect instructs the browser to make a new request to another URL.
Q10. How can you test a custom error view?
Trigger the corresponding exception, verify the returned HTTP status, confirm the selected view, and check that the expected safe message is displayed.
22. Quick Revision Checklist
@ExceptionHandler handles matching exceptions.
@ControllerAdvice supports centralized MVC exception handling.
@RestControllerAdvice is useful for structured REST error responses.
@ResponseStatus declares an HTTP status for a handler or exception.
ModelAndView can combine an error view and model data.
SimpleMappingExceptionResolver maps exception types to view names.
- A view resolver maps a logical view name to a configured view resource.
InternalResourceViewResolver is commonly used for JSP view resolution in traditional Spring MVC.
- Spring Boot commonly configures Thymeleaf automatically when its compatible starter is present.
- Redirects create a new request; flash attributes can carry short-lived data across them.
- Error responses should use appropriate status codes and avoid exposing sensitive information.
- Always verify the configured template location, view name, and framework version.
23. Conclusion
Exception handling and view resolver configuration are essential for building reliable Spring MVC applications. Exception-handling mechanisms such as @ExceptionHandler, @ControllerAdvice, and @ResponseStatus help developers produce consistent and meaningful error responses. View resolvers map logical view names to JSP pages, Thymeleaf templates, or other supported views.
By combining clear exception-handling policies with correct view configuration, developers can improve user experience, simplify debugging, and maintain a clean separation between controllers, business logic, and presentation. Practice these concepts by building a course portal with custom error pages and testing different failure scenarios.
Explore Advanced Java Training: View the Advanced Java Training Course
Register for a Demo: Register for a Course Demo
Visit JustAcademy: JustAcademy Homepage