Mahesha999
Mahesha999

Reputation: 24721

Controller in MVC in JSP

Am trying a project in JSP using MVC pattern.

In online tutorial, it had a servlet as a controller which in its doPost() method:

The JSP page then accesses the parameter added in request scope and displays the content of that object in the desired layout.

Q1: However in this approach there will be one controller per view, I mean for every JSP there will be one servlet. Is that good practice? Or I should have single controller for many views and have views send a command value to controller through header which controller will use to decide what to access through model and what view to generate next.

Q2: Does servlets is the standard way to implement Controller? What are other options to build controllers? What is more commonly used?

Upvotes: 2

Views: 3966

Answers (1)

Jerry Tian
Jerry Tian

Reputation: 3448

This is the same question when I am entering Java EE in early days ;-)

Seems you have already directly mapped the concept of controller to servlet, which may be true on your sample project. But for a more realistic project, this is hardly true and maintainable. So for my following answer, please do bear in mind, controller and servlet are two different concepts, and I intent to answer your second questions first.

Q2:

Since servlet mapping must be hard coded in web.xml, which is very bothering(I mean, you prefer to write Java code then XML stuff, right?), nowadays mainstream MVC framework(struts, Spring MVC, etc) all take a similar single "dispatcher" servlet practice.

This servlet bootstrap the framework, load your custom controllers, then your whole application is alive. This dispatcher servlet is in charge of finding the correct controller, based on different request paths, query parameters, you name it.

Q1:

For one controller per view, or one controller to multiple views, there is no single best practice on that. My suggestion is as long as you can keep your code clean and consistent, choose whatever strategy suitable for your project. After all, this is a taste of orgnazing your code.

Controller and view are two different layers to separate problems of concerns, right?

BTW, I strongly recommend you to pick up whatever mainstream MVC framework's design document, I think they can do a quite better job to explain your puzzles.

External reference:

http://www.jpalace.org/docs/articles/mvc/mvc.html This is a great article on implement a dispatch servlet. It actually build a very small but complete framework using the MVC design pattern. http://static.springsource.org/spring/docs/2.0.x/reference/mvc.html The chart on it explains well what a dispatcher servlet does in the framework.

Upvotes: 1

Related Questions