thonnor
thonnor

Reputation: 1246

Java servlets vs Java class in webapp

I am quite new to Java/Servlets/Tomcat etc. but have a fairly good understanding of web apps from my days as a CGI/PHP developer.

I have a JSP index.jsp that presents a table from a database.

I have a Results.class that is a normal Java class (not a servlet) that queries a database and returns a string from a method: public static String displayAllResults()

The String being returned is an html table.
So in my index.jsp there is a line that says something like:

String table = Result.displayAllResults();

And then the table is displayed as I'd hoped - All good!

My question is this: is there any advantage/disadvantage to using normal Java classes instead of Java servlets in this manner or should I port all of my classes to servlets for added functionality??

Upvotes: 4

Views: 5231

Answers (3)

avijendr
avijendr

Reputation: 4153

You should really be using MVC frameworks like Spring MVC or struts2. You should always have clear abstractions:

  • Dao Layer
  • Service Layer
  • Business Layer
  • Model Objects
  • DTO's
  • Helpers/Utils

Whenever possible use EL languages like JSTL/OGNL on JSP pages. Never ever use scriptlets. If you use any of the above MVC frameworks, you'd probably never need to use Servlets directly!

Displaying grids with data from database use something like DisplayTag or Jqgrid (with Ajax calls)

Upvotes: 1

user1707035
user1707035

Reputation:

I think understanding the purpose of Servlet, JSP, and normal classes will answer your question.

As per my understanding, JSP is used for View purpose, that is, rendering UI to the screen is role of jsp.

whereas, Servlets are used as a controller, whose role is to act as a bridge between your Views and Models.

Normal java classes can act as a Model, here you can perform some core business logic.

Upvotes: 0

Thorn G
Thorn G

Reputation: 12776

It's generally considered poor practice to be invoking Java from a scriptlet in a JSP page. JSP is intended to do HTML formatting, with some extra intelligence around using the Locale and things like that. A better PHP, if you will. Database processing should be handled by a servlet.

Upvotes: 1

Related Questions