Open In App

Spring Boot: Cannot access REST Controller on localhost (404)

The Spring Boot framework is one of the most famous in web application development, It can provide a lot of features to make development easy like dependency management, Spring Security, Spring Autoconfiguration, and other features provided by the Spring Framework. In this article, we will learn how a 404 error occurs while accessing the REST Controller on localhost. There are a lot of reasons for this error. We will get to know why this error is and what are the best solutions for this.

A 404 error when trying to access a RestController in Spring Boot can caused by various issues. The Rest Controller is created by using @RestController Annotation in Spring. Here are some reasons and troubleshooting steps to resolve the problem.

Reasons for 404 error in Spring Boot

Troubleshooting Ways:

Steps to Solve 404 Error while Accessing REST Controller on localhost

To solve the 404 error when accessing the REST Controller API endpoints on localhost, we can utilize the troubleshooting approaches provided above. Now, let's create a Spring Boot project using Spring Initializr.

Step 1:

Create the spring project using spring initializer on creating the project add the below dependencies into the project.

Dependencies:

Once Create the spring project then the file structure looks like the below image.

Folder Structure


Step 2:

Now, let's create a Rest Controller class in the main package of the Spring Project using the @RestController Spring Annotations. After this, we will create some API endpoints in that Rest Controller class. In this project, we have created example API endpoints. Below, we provide the example code.

package com.app;

import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class ParentController {
    
    @GetMapping("/api/example")
    public String displayData() {
        String message = "Welcome to GeeksForGeeks";
        return message;
    }
}


Here, an API endpoint with a Get Mapping and a method named displayData() is created. We can observe this in the above Java code, where a message of String type is being returned.

Step 3:

Now, let's run this project as a Spring Boot project. The project will run on the Apache Tomcat server with port number 8080, which is the default port number.

Application Runs


Step 4:

Now open any favorite browser or Postman tool to test this API endpoint. Below is the API end point for reference.

http://localhost:8080/api/example

Output:

We can see the message in Browser below:

Result in Browser


Now, we will hit wrong API URL in browser. Here, we are using chrome browser to test this API URL. After hitting the wrong URL, we will get the 404 error like below.

Wrong API URL:

http://localhost:8080/api/msg

Output:

After hitting the wrong URL, we get the below Whitelabel Error Page in Browser.

Error Page


Article Tags :