I’m very new to web development, so bear with me =)
Ok here is my tech stack I’m working with
SQL Server 2008 R2,
Tomcat Server 6.0,
Java 1.6,
jQuery,
Here is my problem.
I have a bunch of report type queries I need to run, and I need to display those results as a table on a JSP page for the user to see. The problem I am running into is the method of how to do this.
Most online examples show to store the results of the query in a ResultSet, and putting it into an ArrayList with JavaBeans setters/getters, and then calling that Arraylist in the JSP.
Another problem is, all these queries have different column headers, and these examples do not show how to dynamically create the column headings (most examples are hardcoded).
Here is an example of what I can do so far to generate a report:
//inside the servlet and sets stuff inside a JavaBean
public List<ClaimInfoBean> getClaimInfo() throws SQLException {
List<ClaimInfoBean> claimList = new ArrayList<ClaimInfoBean>();
while (results.next()) {
ClaimInfoBean claim = new ClaimInfoBean();
claim.setClaimNum(results.getString(1));
//set more stuff for the bean
}
claimList.add(claim);
}
On the JSP page
//scriptlet (I know this isnt the best way, but only relevant example I can find)
List<ClaimInfoBean> claimList = claimData.getClaimInfo();
Iterator<ClaimInfoBean> claimListIterator = claimList.iterator();
ClaimInfoBean claim;
while ( claimListIterator.hasNext() ) {
claim = ( ClaimInfoBean ) claimListIterator.next();
//call getXXX to plug into a table
For this servlet, all I care about is running x query, to display y table, when a user clicks a link. This servlet should take any query and display any kind of table, so the way I shown above is very restrictive.
Any help in the right direction would be appreciated!
Here is the guts of a simple Servlet. getConnection returns a connection to your database, and buildDBRequest returns a PreparedStatement that is set up to execute an SQL query. Both are left as exercises for the reader to implement.
The key driver for this is the JSTL. In the JSP, JSTL is used to iterate and present the data. One of the interfaces in JSTL is the javax.servlet.jsp.jstl.sql.Result interface. It is normally created by the JSTL SQL tags, which nobody uses (they they’re quite interesting and really flexible — for quick and dirty stuff they work pretty well).
JSTL also provides a ResultSupport class that conveniently converts a JDBC ResultSet in to a compliant JSTL Result object. So, all the Servlet really needs to do in this case is link up a result set to a JSTL Result, and then forwards to the JSP. Note, when it creates the Result object, it will load in all of the rows of the query. No big deal with 100 rows, potential issue with 1M rows.
You can see it display the column headers from the columnNames collection of the Result, and then it iterates over each of the rows in the Result and across each column of each row.
ReportServlet:
showResult.jsp