TechBuzzPro

Why We Use Rest Controller in Spring Boot

· 5 min read · Gaming

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

We use @RestController to simplify the creation of RESTful web services by combining two essential annotations: @Controller and @ResponseBody. This single annotation tells Spring that every method in the class will return a data object (like JSON or XML) directly into the HTTP response body, rather than rendering a server-side view template like HTML. If you are building an API that communicates with mobile apps, front-end frameworks, or other services, this is the standard entry point.

What You'll Need

  • A Java Development Kit (JDK) version 17 or higher installed on your machine.
  • An Integrated Development Environment (IDE) such as IntelliJ IDEA, Eclipse, or VS Code.
  • A build tool configured for dependency management, typically Maven or Gradle.
  • Spring Boot Starter Web dependency added to your project configuration file.

Step-by-Step

  1. Create a New Spring Boot Project: Start by initializing a new project using Spring Initializr (start.spring.io) or your IDE’s project wizard. Ensure you select the "Web" dependency, which includes Spring MVC and Tomcat. This sets up the foundational infrastructure required to run a web server locally.
  2. Add the Annotation: Locate your main service class. Above the class declaration, add the @RestController annotation. It should look like this: @RestController followed by public class MyApiController { ... }. This marks the entire class as a component that Spring will scan and manage automatically.
  3. Define a Mapping Method: Inside the class, create a public method. Annotate it with @GetMapping, @PostMapping, @PutMapping, or @DeleteMapping depending on the HTTP action you want to handle. For example, use @GetMapping("/users") to handle requests to that specific URL path.
  4. Return Data Objects: Unlike traditional controllers where you return a String representing a view name (like "home.jsp"), here you return actual Java objects. Spring Boot’s built-in Jackson library will automatically serialize these objects into JSON format. Simply write return new User("John", 30);.
  5. Configure the Port: By default, Spring Boot runs on port 8080. You can verify this in your browser by navigating to http://localhost:8080/users after starting the application. If you need a different port, update the application.properties file with server.port=8090.
  6. Test the Endpoint: Use a tool like Postman, curl, or your browser to send a request to your endpoint. Check the response body. You should see raw JSON data, not an HTML page. This confirms that the @ResponseBody behavior is active.

Common Mistakes

One frequent error is confusing @Controller with @RestController. If you use @Controller without adding @ResponseBody to every method, Spring will interpret the returned string as a view name. This leads to errors like "Whitelabel Error Page" because the framework looks for a template file named after your return string instead of sending the text itself.

Another common issue is forgetting to include getters and setters in your return objects. The JSON serialization engine relies on JavaBeans conventions. If your class fields are private and lack public getter methods, the output will be empty JSON objects ({}) even though the data exists in memory.

Developers also often mistake the scope of the annotation. @RestController applies to the whole class. You cannot mix view-resolving methods and data-returning methods in the same class easily. If you need both, you must separate them into two different classes or explicitly override the behavior on specific methods using @ResponseBody.

Tips

Use @RequestMapping at the class level to define a common base path for all endpoints. For example, @RequestMapping("/api/v1") ensures all methods inside have that prefix, keeping your URLs clean and organized. This is much better than repeating the path in every method annotation.

Leverage @ResponseStatus if you need to return specific HTTP codes other than 200 OK. For instance, when creating a resource, returning a 201 Created status is semantically correct. You can add @PostMapping(value = "/users", status = HttpStatus.CREATED) to achieve this.

Keep your controller thin. Controllers should only handle incoming requests, validate input, and delegate logic to Service classes. Do not put business logic inside the controller methods. This keeps your code testable and maintainable. The controller acts merely as the dispatcher.

Troubleshooting

If you receive a 404 Not Found error, first check that your class has the @RestController annotation. Next, verify that the package containing the controller is scanned by Spring. Usually, placing the controller in the same package or a sub-package of your main Application class solves this. If it is in a parent package, you may need to add @ComponentScan.

If you get a 406 Not Acceptable error, it means the client requested a media type (like HTML) that your controller does not produce. Ensure your client sends an Accept: application/json header. Most modern browsers do this automatically for AJAX requests, but simple URL clicks might trigger HTML acceptance.

If the JSON output looks wrong or dates are formatted oddly, check your Jackson dependencies. Spring Boot manages these automatically, but custom configurations in application.properties might interfere. Try removing custom date formats temporarily to see if the default ISO-8601 format works.

Frequently Asked Questions

Can I use @Controller and @RestController together?

No, they are mutually exclusive at the class level. Using both will cause conflicts. Use @RestController for APIs and @Controller for server-side rendered views.

Does @RestController require a View Resolver?

No. Since it returns data directly to the response body, it bypasses the view resolution process entirely. You do not need to configure Thymeleaf or JSP for basic REST endpoints.

How do I handle POST requests with @RestController?

Use @PostMapping. To receive data from the request body, annotate a parameter with @RequestBody. Spring will automatically deserialize the incoming JSON into your Java object.

Is @RestController thread-safe?

Yes. Spring creates a singleton instance of the controller bean. As long as you do not store mutable state in instance variables, the controller is safe for concurrent requests.

What happens if I return null from a @RestController method?

Spring will return an HTTP 204 No Content status code. This is appropriate for DELETE operations or cases where no data needs to be sent back to the client.