1

UPDATED: I have included the whole code to clear the ambiguity.

This is the CompileClass that I am using for getter and setter methods:

 package user;

public class CompileClass {
    public String date1;
    public String date2;
    public String p_code;
    
    
    public CompileClass(){
    }    
    
    public void setDate1( String name ) {
        date1 = name;
    }
    public void setDate2( String name ) {
        date2 = name;
    }
    public void setP_code( String name ) {
        p_code = name;
    }

     public String getDate1() { 
        return date1;
    }
    
     public String getDate2() { 
         return date2;
     }

     public String getP_code() { 
         return p_code;
     }
}

And this is my BEAN duplicaterecords.jsp:

package user;

import java.io.* ;
import java.sql.*;
import java.text.*;
import javax.servlet.*;//modified for JSP
import javax.servlet.http.*;//modified for JSP

import user.CompileClass;
 /*to find duplicate records and their time stamps*/
public class duplicaterecords extends HttpServlet{//modified for JSP
    public static void main(String[] args,HttpServletRequest request, HttpServletResponse response)//modified for JSP 
    {
    int l,x=0,y=0,tow,i=0,tower1=0,t=0;
    String p_code,date[],date1,date2,getdate,date3,tower,t_split;
    
    String time2;
              //tow=new int[1000];
    date=new String[100];
    
    CompileClass c=new CompileClass();//modified for JSP
    
    //HttpServletRequest request;//modified for JSP     
    
     DecimalFormat df = new DecimalFormat("#.##");
     try
         {  
  
                                  BufferedReader b = new BufferedReader(new InputStreamReader(System.in)); //input buffer 
                        Class.forName("com.mysql.jdbc.Driver");
                                  Connection
                                  con=DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
                                  Statement stmt=con.createStatement();
                
              String query1="select distinct(date) FROM `report_data` WHERE date>= ? and date<= ? "; //Query one for date input 
               PreparedStatement ps=con.prepareStatement(query1);
             
               //System.out.println("Enter the 1st DATE"); //Date 1 is entered 
                date1 = c.getDate1();//modified for JSP
                //System.out.println("Enter the 2nd DATE"); //Date 2 is entered 
                //date2=b.readLine();
                date2 = c.getDate2();//modified for JSP
                                    ps.setString(1,date1);
                ps.setString(2,date2);
                         //System.out.println("enter the param_code"); // param_code is entered 
                //p_code= b.readLine();
                  p_code=c.getP_code();//modified for JSP
                  
               ResultSet result=ps.executeQuery();  
                          //System.out.print("Tow_id");
           
                         while(result.next() )
                        {
                          getdate=result.getString("date");
                          //System.out.print("\t"+getdate);
                          request.setAttribute("dates", getdate);//modified for JSP
                    date3='%'+getdate+'%';
                                    date[x]=date3;
                    x++;
                         }
           
                          l=x;
         
                
              String query2="SELECT distinct(tow_id) FROM  `tower_data` WHERE TIME_STAMP LIKE ? "; //query 2 for finding tower-id 
                                   PreparedStatement ps1=con.prepareStatement(query2);
                ps1.setString(1,date[0]);      
                ResultSet result1=ps1.executeQuery(); 
                while(result1.next())
                 { 
                  //System.out.println("");
                  tower=result1.getString("tow_id");
                   tower1= Integer.parseInt(tower);
            
                 
                 t=y;
                 //System.out.print(tower1);
                 request.setAttribute("towers", tower1);//modified for JSP
                           int count=0;
                 x=0;
                
                           while(count<l)
                   {
                          String query3="SELECT time_stamp FROM tower_data WHERE `TIME_STAMP` LIKE ? AND `PARAM_CODE` = ? AND `TOW_ID`=? GROUP BY time_stamp HAVING count( * ) >1";
                                       //Query 3 for finding time stamps with duplicate data 
                    PreparedStatement ps2=con.prepareStatement(query3); 
                    ps2.setString(2,p_code);
                     ps2.setString(1,date[x]);
                    ps2.setInt(3,tower1);
                    ResultSet result2=ps2.executeQuery();
    
                                       int row=0;
                                      while(result2.next())
                  {
                        
                  t_split=result2.getString("time_stamp");
                         
                 String[] parts= t_split.split(" "); //splitting time_stamp to extract only time without date 
                                      time2=parts[1]; //time stored in time2
                //System.out.println("\t"+time2);
                                      request.setAttribute("times", time2);//modified for JSP
                row++;
                         
                }
               if(row==0)
                                    {
                                    //System.out.println("\t"+"no duplicate");                          
                }
                      // System.out.print("\t"+"\t");
                      
                 
                          
                                  x++;
             count++;
                   }                   
        }
        con.close();   
           
                          }
                         catch (Exception e)
                        {
                        e.printStackTrace();
                      
                        }
                        }

                       }

This is my Result.jsp:

<%@ page import="java.net.*"%>
<%@ page import="javax.servlet.*"%>
<%@ page import="java.util.ArrayList"%>

<jsp:useBean id="user" scope="session" class="user.duplicaterecords" />
<jsp:setProperty property="*" name="user"/>
<html>
  
  <body>
   Dates:<BR>    

<%--<%= request.getAttribute("dates")  %><br/>--%>
<%--Email: <%= user.getMail() %><BR>--%>
<%-- Age: <%= user.getAge() %><BR> --%>   

<c:forEach items="${sessionScope.dates}" var="item">
  <c:out value="${item}"/>
</c:forEach>  

  </body>
</html>

As clear from the code

s.setAttribute("dates", getdate);

getdate will contain an array of string values.

Now I want to call it in my JSP like this:

<%= request.getAttribute("dates") %>

But calling the value like is returning null. So I wanted to know how can I access getdate attribute as an array and print all the values. Help?

Community
  • 1
  • 1
Anurag
  • 723
  • 3
  • 13
  • 31
  • Some important code is missing and some variables are far from self-documenting. Are you sure that `s` is a `HttpServletRequest` and not a `HttpSession`? As to the entire top-bottom approach, I'd suggest to get yourself through [this answer](http://stackoverflow.com/questions/3177733/how-to-avoid-java-code-in-jsp-files/3180202#3180202) as a good starting point. – BalusC Mar 24 '11 at 19:45
  • Then it's not the same request or it is been accessed *before* it's been set. – BalusC Mar 24 '11 at 20:00
  • @BalusC My big apologies. `s` is a `HttpSession`. – Anurag Mar 24 '11 at 20:05
  • No problem. I reposted it as an answer. I'd however warmly recommend to get yourself through the aforementioned link. What you're trying to do here doesn't look a good start at all since you're using *scriptlets*. Do not read 10 year old books/tutorials. – BalusC Mar 24 '11 at 20:21
  • why duplicaterecords extends HttpServlet and has main() ?? – lukastymo Mar 24 '11 at 22:52
  • @smas that is because this Java class was first being used standalone module and was taking input from command-line. Now I am trying to turn it into a Bean. I have to pass input and take output from it. – Anurag Mar 24 '11 at 23:02

2 Answers2

6

If it doesn't work, then it means that the s in your bean is not the same HttpServletRequest instance as request in your JSP. Even though the code is far from self-documenting, the letter s suggests that it's a HttpSession instead of a HttpServletRequest. Fix it accordingly.


Unrelated to the concrete problem, the approach is odd and clumsy. Not only the while loop is odd, you're overwriting the attribute value everytime with data from each row, but also a healthy javabean intented as an entity shouldn't have any javax.servlet import lines.

Just add a getter to the bean

private List<Date> dates;

public List<Date> getDates() {
    if (dates == null) {
        loadDates();
    }
    return dates;
}

private void loadDates() {
    dates = new ArrayList<Date>();
    // Fill it based on data from DB.
}

and access it as follows in your page

<jsp:useBean id="bean" class="com.example.Bean" />
...
<c:forEach items="${bean.dates}" var="date">
    ${date}<br/>
</c:forEach>

That's better, but normally you use a HttpServlet class to create and populate the bean based on data from DB.


Update: as per your question update. You're mixing several concepts, the setup is heavily flawed. The CompileClass class is a bean (albeit the classname is far from self-documenting). The duplicaterecords class is a servlet, not a bean (albeit the right servlet methods are not been overriden). The main() method is not invoked at all when you construct a bean using jsp:useBean. The JDBC code is mingled in a servlet class. The while loop on ResultSet is also attempting to overwrite the request attribute on every loop. There is too much wrong that it's impossible to post a single-sentence answer to fix the concrete problem.

I am right now also not in a mood to rewrite it all for you. So I'd suggest to put this all aside and restart based on some basic hello world examples. Here are some links to get started:

After you have read the above pages and played around with basic examples in order to grasp the basic concepts, then rewrite the whole fluff as follows:

  1. Have a Javabean class Report with the necessary properties which represents a single report.
  2. Have a DAO class with a list(Date start, Date end) method which uses JDBC to return a List<Report> from the DB with reports between the given dates.
  3. Have an search.jsp page with a <form action="reports" method="post"> with necessary input fields.
  4. Have a reports.jsp page with a <c:forEach items="${reports}" var="report"> which displays the reports.
  5. Have a Servlet which listens on /reports and does the following in doPost() method:
    • Gather start date and end date as request parameters.
    • Get a List<Report> based on start and end dates.
    • Put it in request scope by request.setAttribute("reports", reports);
    • Forward to result JSP by request.getRequestDispatcher("reports.jsp").forward(request, response);
Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
  • @BaluC I changed `s` to `HttpServletRequest` but still the same problem. – Anurag Mar 24 '11 at 20:33
  • 1
    Then it's not the *same* request or it is been accessed *before* it's been set. Grabbing the request inside a Javabean is also a quite odd design. Usually a Javabean class shouldn't be aware about the request at all. You normally prepare the list as a bean property and then just invoke the bean method. – BalusC Mar 24 '11 at 20:34
  • @BaluC the recursive while loops are making it tough to include the getter method. I have updated the whole code. Mind having a look? BTW still no output, not even **null** – Anurag Mar 24 '11 at 22:37
1

If you call setAttribute from HttpSession you add object/value to session context so you should ask session scope about your attribute not request scope

<%
List bla = (ArrayList) request.getSession().getAttribute(dates);
for( Iterator i = bla.iterator() ; iter.hasNext(); ) {
   out.println( (String) iter.next() );
}%>

in jstl:

<c:forEach items="${sessionScope.dates}" var="item">
  <c:out value="${item}"/>
</c:forEach>

edited

Now you've changed the code and dates is into request scope. Your Servlet implementation is very incorrect - has main() method?!, change it - this is the reason why you in reality don't put dates into request scope

<c:forEach items="${dates}" var="item">
  <c:out value="${item}"/>
</c:forEach>
lukastymo
  • 26,145
  • 14
  • 53
  • 66
  • @smas I used the jstl tag given by you but now I am not getting any output. Not even **null** – Anurag Mar 24 '11 at 20:39
  • oh, sorry :) try this.. should work (I guess in array you have Strings) – lukastymo Mar 24 '11 at 20:44
  • @smas I have updated the whole code now in the question. Still no output, not even **null** – Anurag Mar 24 '11 at 22:37
  • @Anurag this is because my example regarding to your previous code - where you was putting dates into session scope. Now you put dates into request scope. So try change ${sessionScope.dates} to ${profileArray}, should work if rest of your application is correct – lukastymo Mar 24 '11 at 22:42
  • oh I know what's the problem :) You have bad Servlet implementation. You have duplicaterecords extends HttpServlet but actually you have main methods there() - this is incorrect – lukastymo Mar 24 '11 at 22:53
  • @smas I know my current code is PITA but some guidelines to quickly fix it would be big help. After I make it work but surely refine it to stick to standards. – Anurag Mar 24 '11 at 23:04
  • @smas also `request.getAttribute("dates")` gives **null** output – Anurag Mar 24 '11 at 23:08
  • you must create a method which will has code from main() and after it you should call this method from jsp. Now you don't call code which put your "dates" so this is why you have nothing in request scope. – lukastymo Mar 24 '11 at 23:11