Solved

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

Posted on 2007-11-22
3
956 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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

Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

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

Suggested Solutions

Title # Comments Views Activity
wordmultiple challenge 12 170
tomcat startup error 5 174
Eclipse Help Java EE 5,6,7 Documentation, why not Java EE 8 8 71
collection output issue 9 96
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 last of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers our test design approach and then goes through a simple test case example, how …
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.

751 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