Solved

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

Posted on 2007-11-22
3
947 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 24

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

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Title # Comments Views Activity
maxMirror challenge 10 89
wordsFront challenge 8 68
sumHeights2  challenge 7 76
count11 challenge 6 47
I had a project requirement for a displaying a user workbench .This workbench would consist multiple data grids .In each grid the user will be able to see a large number of data. These data grids should allow the user to 1. Sort 2. Export the …
Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
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.

758 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

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now