Spring MVC @controller not working

Ahmed Rafsan Raqib 0 Reputation points
2024-05-31T20:13:11.82+00:00

I have a spring mvc application that has @controller classes. When I deploy the application using azure app services it gives me a 404 error. When I remove the @Controller and add @RestController and redeploy it seems to work properly. Not sure why this is happening.

Azure App Service
Azure App Service
Azure App Service is a service used to create and deploy scalable, mission-critical web apps.
8,930 questions
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Grmacjon-MSFT 19,151 Reputation points Moderator
    2024-05-31T21:54:21.0566667+00:00

    Hello @Ahmed Rafsan Raqib so there is a difference between @Controller and @RestController in Spring MVC.

    • @Controller: This annotation marks a class as a Spring MVC controller. It handles traditional web requests that might return different view technologies like JSP, Thymeleaf, etc. By default, methods within a @Controller class return a logical view name that gets resolved to a physical view template.
    • @RestController: This annotation is specifically for building RESTful web services. It assumes a response format suitable for API consumption (e.g., JSON, XML). Methods within a @RestController typically return the data itself (objects, collections) that gets serialized into the chosen format.

    Azure App Services typically geared towards handling RESTful APIs. When you deploy your application with @Controller annotations, Azure App Services might not be configured to interpret the returned view names and render them appropriately, leading to the 404 error you got

    So, if your application primarily deals with API functionalities and doesn't require traditional web views, consider switching your controller classes to use @RestController instead of @Controller. This aligns better with the expectations of Azure App Services for handling RESTful requests.

    Modify your methods to directly return the data objects you want to expose through the API. Spring will automatically handle serialization based on the chosen content type (e.g., JSON by default).

    Hope that helps. Please let us know if you have further questions

    Best,

    Grace

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.