Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.1k views
in Technique[技术] by (71.8m points)

Adding a REST API to Spring MVC application

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?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...