kazbeel
kazbeel

Reputation: 1436

SPring MVC - Several Controllers

I am developing for learning purposes my very first "big" Spring MVC project. I am learning everything by myself (and of course, thanks to this amazing community).

What I am starting to wonder is... Is my design "correct/valid"? So far I am creating one Controller per View/Page specially because of the ModelAttributes (attached to the method).

Is that fine? Should I start doing it in some other way? Are there "offical" patterns in this matter?

Upvotes: 0

Views: 272

Answers (1)

holtc
holtc

Reputation: 1820

To start, I assume you are creating a web project based on your use of ModelAttribute. You want to follow the MVC (Model, View, Controller) convention. The "Model" is the data you are manipulating. This data should be retrieved via a service layer. Then, your controller should call your service methods to get the data, making your controllers completely agnostic of your data. This is nice because you are free to change your data structure, e.g. migrating from MySQL to MongoDB, without worrying about changing your controller, all you need to change is your service layer. Also, this allows for controllers to use many different services in certain instances. Your controller receives requests from the client, e.g. the website user's page requests, GET/POST requests, etc., and performs some action, usually fetching/updating data via the service layer, and then returns a view. Each controller can take many requests, and can render many views. It is good practice to break up controllers by function. For example, if you had two different sections for your website, one for Admins, and one for Guests, then you may want to use one controller to process the Admin requests, and another to process the Guest requests. Each of these controllers can handle all requests from Admins/Guests accordingly. You may be a bit confused about controllers. Each method in a controller is bound to a single request/view, but a controller may have many such methods.

As you are learning, I would suggest exploring some client-side mvc frameworks like AngularJS. Angular allows very easy data binding and manipulation options, and makes it pretty easy to create RESTful web services.

Upvotes: 2

Related Questions