Solved

Servlet JSP Best Practices (putting business logic behind a JSP)

Posted on 2007-11-22
3
952 Views
Last Modified: 2013-11-24
I have a Servlet called PoolTest.java (see attached) which simply grabs a connection from a database connection pool and prints out an html page with all the rows of a table.  As a general rule I've heard that you should seperate the dislpay (HTML) from the business logic (DB connectivity) as much as possible.  I have been able to create a JSP that does the same thing as this servlet but all the DB connection code is in the JSP!  I can't figure out how to serperate the two.  How do I do this?  Do I need to create a java bean?  I'm clueless, but want to get this right at the beginning before I get in too deep.  Many thanks.
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
 
public class PoolTest extends HttpServlet {
 
	// Static class instantiation for the DB Connection Pool
	// As described from http://java.sun.com/developer/onlineTraining/Programming/JDCBook/conpool.html
	static {
		try {
		new pool.JDCConnectionDriver(
						"sun.jdbc.odbc.JdbcOdbcDriver",
						"jdbc:odbc:RREdb",
						"none", "none");
		}catch(Exception e){}
	}
 
	// Get a connection from the connection pool
  public Connection getConnection()
                      throws SQLException{
        return DriverManager.getConnection(
				"jdbc:jdc:jdcpool");
  }
 
	// Print out a simple HTML page with the rows of tblUsers
	public void doGet(HttpServletRequest request,
										HttpServletResponse response)
										throws IOException, ServletException
	{
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
 
		out.println("<html>\n");
		out.println("<body>\n");
		out.println("<table>\n");
 
		try {
			Statement stmt;
			Connection con;
			con = getConnection();
			stmt = con.createStatement();
 
			// Get data from tblUsers
			String query = "select userId, userName from tblUsers";
			ResultSet rs = stmt.executeQuery(query);
			ResultSetMetaData rsmd = rs.getMetaData();
			int numberOfColumns = rsmd.getColumnCount();
			int rowCount = 1;
			while (rs.next()) {
				out.println("<tr><td>" + rowCount + "</td>\n");
				for (int i = 1; i <= numberOfColumns; i++) {
					out.print("<td>" + rs.getString(i) + "</td>\n");
				}
				out.println("</tr>");
				rowCount++;
			}
			stmt.close();
			con.close();
 
		} catch(SQLException ex) {
			out.print("SQLException: ");
			out.println(ex.getMessage());
		}
 
		out.println("</table>");
		out.println("</body>");
		out.println("</html>");
	}
}

Open in new window

0
Comment
Question by:burtonrhodes
3 Comments
 
LVL 4

Assisted Solution

by:jcoombes
jcoombes earned 150 total points
ID: 20334491
You might want to look at a framework such as Struts, JSF or Spring Web MVC...

The basic idea is yes, to move this logic into a bean somewhere, the various frameworks will then specify architectural patterns that determine how you surface and access them within your JSP code.

Cheers


JC
0
 
LVL 25

Accepted Solution

by:
Tomas Helgi Johannsson earned 350 total points
ID: 20334881
    Hi!

Use Beans with JSP. That is put all the DB related code into a BEAN and
call the bean from a JSP page
http://www.java2s.com/Code/Java/JSP/Beans.htm
http://www.java2s.com/Code/Java/JSP/Bean-Scope.htm

Regards,
  Tomas Helgi
0
 
LVL 3

Author Closing Comment

by:burtonrhodes
ID: 31410562
Both were correct, but the second answer was most helpful.   Many thanks!
0

Featured Post

Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
The viewer will learn how to implement Singleton Design Pattern in Java.
This tutorial covers a practical example of lazy loading technique and early loading technique in a Singleton Design Pattern.

785 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question