Hi All,
I have JSP and Servlet that need to "talk" to each other. Actually I need to get record from database, fill it in JSP file. I have created Servlet that does the query and gets the result. I need those results to be shown on JSP file. In PHP I will just include the PHP file that does the query but I cannot find that simple way in JSP.

Trying to fix I came up with this method. When link is first clicked, it goes to servlet. Servlet processes it and posts results back to JSP. I'm using session to communicate. But Session is always null at JSP. Please see code and help me point out the error.

Also is this good method for table with thousands of data?
Thanks

Servlet code

package lam;

import javax.servlet.http.HttpServlet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.sql.*;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;

public class LAMHistory extends HttpServlet {

    public void GetHistory(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        PrintWriter out = resp.getWriter();
        try {
            //Write a page with only rows. The code should be put between <table> </table> tags
            ResultSet res = this.getAllTableRows();
            int i; //iterator counter
            //test variable - DELETE IT
            int count = 0;
            String pageContents = "";
            ResultSetMetaData md = res.getMetaData();
            int colCount =  md.getColumnCount();
            while (res.next()) {
                if (count > 50) {
                    break;
                }
                //extract one row at a time and put it in table row
                pageContents = pageContents + "<tr>";
                for (i = 1; i <= colCount; i++) {
                    pageContents = pageContents + "<td>" + res.getString(i) + "</td>";
                }
                pageContents = pageContents + "<tr>";
                count++;
            }
            //put on session
            HttpSession session = req.getSession();
            session.setAttribute("pageContents", pageContents);
            RequestDispatcher dispatcher = req.getRequestDispatcher("/history.jsp");
            if (dispatcher != null) {
                //redirect to history page
                dispatcher.forward(req, resp);
            } else {
                //redirect to error page
                out.print("Sorry, redirection failed");
            }
        } catch (Exception e) {
            e.printStackTrace();
            out.print("Error: This servlet failed to do any processing!");
            //redirect to error page
        }
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        //call histroy
        this.GetHistory(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        doGet(req, resp);
    }

    //get attributes
    protected ResultSet getAllTableRows() {
        //returns array of *FullName, LeaveApplicationDate, TotalLeaveDays, LeaveStatus, TakeAction*
        DBClass db = new DBClass();
        String sql = "SELECT user.full_name, application.start_date, application.end_date,  application.working_days,  "
                + "application.application_status WHERE user.employee_number=application.employee_number";
        sql="SELECT * FROM application";
       try{
           ResultSet rs = db.dbSelect(sql);
           return rs;
       }catch(Exception e){
           e.printStackTrace();
           return null;
       }


    }

  
}//end class

JSP file

<%-- 
    Document   : history
    Created on : May 12, 2010, 4:11:19 PM
    Author     : smtangoo
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
   "http://www.w3.org/TR/html4/loose.dtd">
<link rel="stylesheet" type="text/css" href="history.css" />

<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>History - NMC Leave Management Application</title>
    </head>
    <body>
        <!-- Header Text, may be a logo -->
        <center><h1 id="headertext">Welcome - LAM History</h1></center>

        <!-- History table -->
        <table align="center" border="1" cellpadding="5" id="historyTable">
            <thead>
                <tr>

                    <th class="headerRow">Full Name</th>
                    <th class="headerRow"> Leave Application Date</th>
                    <th class="headerRow">Total Leave Days</th>
                    <th class="headerRow">Leave Status</th>
                    <th class="headerRow">Take Action</th>

                </tr>

            </thead>
            <tbody>
                <!--  
                //fill in rows from history by getting contentPage attribute and echo it
                -->
                <%
                    //get string
                    //HttpSession session=req.getSession();
                    String historyPage = (String) request.getSession().getAttribute("contentPage");
                    out.println(historyPage);
                %>
                

                
            </tbody>
        </table>


    </body>
</html>

Here is my error
In servlet I declare
session.setAttribute("pageContents", pageContents); while in JSP I use request.getSession().getAttribute("contentPage");

Now, is it good to pass thousands of table values into session object? Why?

I have tried and see that If I pass 400 rows it works fine but if I pass 500 rows it fails! Is that limitation to sessions?

Actually Session is used to store small number of variables. so may be u can tell tat it has limitaions.

can u tell me wat is different between

HttpSession s = request.getSession();
String s2=(String)s.getAttribute("a);//a is some vari

and

String historyPage = (String) request.getSession().getAttribute("contentPage");

No difference as I can see.
Different ways of doing the same thing right?

Oh ya. Ur way is smart.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.