Nachshon Schwartz
Nachshon Schwartz

Reputation: 15765

Best way for using JSP and Servlets in an MVC webapp

I'm working on a dynamic website in Java and I'm interested in sticking with the MVC pattern. What is the best way to divide the work of a webapp between JSP and Servlets?

Should I see my JSP file as the view of the program and the Servlet more as the controller?

If I should use the Servlet as a controller, is it wise to give a Servlet more than one functionallity, for example: send in an action number to the Servlet and the Servlet will switch case on it to decide which action to do. This way i can create very few Servlets and each one would be in charge of a separate type of requests.

Upvotes: 3

Views: 1118

Answers (2)

jdc0589
jdc0589

Reputation: 7018

I was in a little bit of a similar situation a few months ago. I had to use java to introduce a group of people to web development, but I honestly wasn't a huge fan of any of the frameworks out there for java. A lot of people get stuck in the mentality that just because JSP's let you do whatever the hell you want in the page, you should.

You can use plain old java/jsp's and still have a well organized project. Here is a link to the project I mentioned. I simply limited each page to ONE function call to a pseudo controller method which returned the model needed for the page. The only other java code on the pages was for templating.

Here is the source for the project, take a look if you want.

http://net-machine.com/indefero/p/lsms/source/tree/master/src

Upvotes: 1

Stephen C
Stephen C

Reputation: 718688

Should I see my JSP file as the view of the program and the Servlet more as the controller?

Yes. JSPs are best used for implementing views.

Depending on your application requirements, there may be other views that are not implemented as JSPs. But your proposed division of responsibility is a good starting point.

If I should use the Servlet as a controller, is it wise to give a Servlet more than one functionallity, for example: send in an action number to the Servlet and the Servlet will switch case on it to decide which action to do.

This is more debatable. You can either have a small number of servlets and switch inside the servlet or have a large number of servlets and switch in the "web.xml" file or in some framework classes. For instance, a lot of people use a restlet framework, and / or annotations to manage the dispatching of requests to controller servlets.


My general advice would be:

  • Don't try to code yet another framework. There are already lots of them out there, and at least one of them should be good enough.
  • Don't over-design.

Upvotes: 7

Related Questions