0

Assuming an application with a traditional UI based on Spring MVC and Thymeleaf, it seems like there are a few ways to expose a REST API...

  1. Add a completely separate set of Controllers using @RestController - Feels like a lot of duplication, but allows complete separation of UI vs REST logic

  2. Use a single Controller for each entity, with a mix of both @ResponseBody methods and ModelAndView methods - Keeps all logic for a given entity in a single place, but requires mixing different concepts

  3. Use a single Controller for each entity, use only ModelAndView, and use content negotiation with a JSON view resolver like the MappingJackson2JsonView (https://spring.io/blog/2013/06/03/content-negotiation-using-views/)

I'm particularly interested in #3 as it feels similar to how Ruby on Rails Controllers work with the respond_to for different content types.

Is this a common approach / best-practice in Spring applications?

Would POST and DELETE requests still require separate methods since they may work differently between a REST API vs the UI? (i.e. posting a form vs posting a json entity)

Would it require separate Exception handling based on whether it was a UI request or API request?

1 Answer 1

2

I'd go with option 1. Having a separate set of @Controller and @RestController avoids mixing MVC pattern with your REST api. To avoid code duplication, you should add a service layer and have the REST endpoint and the MVC controller to make use of that service layer.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.