Spring MVC
404 Error
Controller
Web Development
Java

Trigger 404 in Spring-MVC controller?

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

Introduction

In the realm of web development, Spring MVC (Model-View-Controller) is a robust framework that provides a declarative way to handle web requests by defining endpoints in @Controller classes. However, handling HTTP responses effectively, particularly triggering a 404 error when a resource cannot be found, is crucial. This article will delve into how to trigger a 404 error in a Spring-MVC controller, discussing the technical aspects and providing practical examples.

Spring MVC Overview

Spring MVC is a part of the Spring Framework that adheres to the Model-View-Controller design pattern. It decouples the different aspects of web application development such as handling requests, managing models and providing views to clients. Controllers act as the central part of this framework, linking user requests with back-end services.

Handling 404 Errors

A 404 error indicates that the server could not find the requested resource. There are scenarios in application development where a controller may need to explicitly return this status, such as when querying a database for non-existent records.

Techniques to Trigger a 404 Error

1. Using @ResponseStatus Annotation

Spring MVC provides the @ResponseStatus annotation to set the response status code for a controller method. For triggering a 404 error, you can annotate a method or exception class with @ResponseStatus(HttpStatus.NOT_FOUND).

java
1import org.springframework.http.HttpStatus;
2import org.springframework.web.bind.annotation.ResponseStatus;
3
4// Custom Exception for Resource Not Found
5@ResponseStatus(value = HttpStatus.NOT_FOUND)
6public class ResourceNotFoundException extends RuntimeException {
7    public ResourceNotFoundException(String message) {
8        super(message);
9    }
10}

2. Throwing ResourceNotFoundException in Controller

When a resource is not found, you can throw the custom exception within your controller method:

java
1import org.springframework.web.bind.annotation.*;
2
3@RestController
4@RequestMapping("/api")
5public class ResourceController {
6    
7    @GetMapping("/resource/{id}")
8    public Resource getResourceById(@PathVariable("id") Long id) {
9        Resource resource = resourceService.findById(id);
10        if (resource == null) {
11            throw new ResourceNotFoundException("Resource not found with id: " + id);
12        }
13        return resource;
14    }
15}

3. Using ResponseEntity

The ResponseEntity class provides an alternative way to manage HTTP responses and status codes. You can return a 404 status with an empty body if a resource is not found:

java
1import org.springframework.http.ResponseEntity;
2import org.springframework.web.bind.annotation.*;
3
4@RestController
5@RequestMapping("/api")
6public class ResourceController {
7    
8    @GetMapping("/resource/{id}")
9    public ResponseEntity<Resource> getResourceById(@PathVariable("id") Long id) {
10        Resource resource = resourceService.findById(id);
11        if (resource == null) {
12            return new ResponseEntity<>(HttpStatus.NOT_FOUND);
13        }
14        return new ResponseEntity<>(resource, HttpStatus.OK);
15    }
16}

4. Mapping Exceptions Globally with @ControllerAdvice

@ControllerAdvice is a specialization of the @Component annotation that helps in handling exceptions globally. You can define exception handling logic across all controllers:

java
1import org.springframework.web.bind.annotation.*;
2
3@ControllerAdvice
4public class GlobalExceptionHandler {
5    
6    @ExceptionHandler(ResourceNotFoundException.class)
7    public ResponseEntity<Object> handleResourceNotFound(ResourceNotFoundException ex) {
8        return new ResponseEntity<>(ex.getMessage(), HttpStatus.NOT_FOUND);
9    }
10}

Summary Table

TechniqueDescriptionCode Example
@ResponseStatus AnnotationDefine response status directly on an exception class.Custom exception class with @ResponseStatus.
Throw ResourceNotFoundExceptionTrigger a 404 by throwing an exception in your controller.Throw exception in controller method when resource is absent.
ResponseEntityUse ResponseEntity to return status codes and responses.Return ResponseEntity with HttpStatus.NOT_FOUND.
@ControllerAdviceHandle exceptions globally across all controllers.Define a class with @ControllerAdvice and handle exceptions.

Conclusion

Managing 404 errors in Spring-MVC is an integral part of creating a user-friendly and robust web application. Using techniques like setting response statuses, throwing exceptions, and global exception handlers, you can ensure that users encounter informative responses when resources cannot be found. The choice of technique depends on the specific requirements of your application and the level of granularity you need in error handling.

The effective handling of 404 errors improves application reliability and provides clear feedback to users, enhancing the overall experience. Therefore, understanding these mechanisms is crucial for any developer working within the Spring MVC framework.


Related reading
Course
Intermediate
27 lessons
14 hours
OOD Fundamentals

Master object-oriented design from first principles, SOLID, design patterns, and classic interview problems with hands-on coding.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Interview Questions practice on Codemia

Over 8,000 real interview questions from top companies, searchable by company and role.

Browse interview questions

All Rights Reserved.