Solved

How to read a file using JSP?

Posted on 2001-06-27
25
201 Views
Last Modified: 2010-04-16
Anyone can help me on this? I will be grateful if there is a kind soul offering his/her help.

I need to read information from a file and put into my SELECT statement in my JSP file. Something like the codes below...

<SELECT NAME="test" ><%= function getfile()%></SELECT>

So function getfile() will generate all my OPTIONS.

Thank you.
0
Comment
Question by:jason101799
  • 16
  • 9
25 Comments
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6233922
Do u want read the text from Server file or Client File?
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6233923
package logging;
import java.io.*;

public class UsersReader
{
     public FileReader filer=null;
     StringBuffer data=null;

     public String read(String file)throws Exception
     {
          filer=new FileReader (file);
          data=new StringBuffer();
          while(true)
          {
               int c=filer.read();
               if(c==-1) break;
               data.append(""+(char)c);
          }
          return data.toString();
     }
}

here is the file to read text
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6233939
<%@ page import=logging.*%>
<%
     UsersReader ur= new UsersReader();
     String s=ur.read("/weblogic/myserver/public_html/MyText.txt");
     out.println(s);

%>

here is jsp code
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6233945
<%@ page import=logging.*%>
<%
     UsersReader ur= new UsersReader();
     String s=ur.read("/weblogic/myserver/public_html/MyText.txt");
     out.println(s);

%>

here is jsp code
0
 

Author Comment

by:jason101799
ID: 6236612
sudhakar,

Thanks for your reply, what if I need to spilt the line that i read earlier? Is there any function to do so?
I have comma delimited records in my text file for ex:
AP,SWE,SWEDEN

Cheers
Jason
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6236838
Use StringTokenizer class that is available with java.util package

Here is sample code

StringTokenizer st=new StringTokenizer("AP,SWE,SWEDEN",",");

while(st.hasMoreTokens())
{
%>
<SELECT NAME="test" ><%= st.nextToken()%></SELECT>
<%

}



Regards
Sudhakar
0
 

Author Comment

by:jason101799
ID: 6243384
sudhakar,

How do I call a function?? For example:-

-----------------------------------------------------------
<%@ page language="java" %>
<%@ page import="java.util.*, java.io.*, java.net.*" %>
<%! public String getCountries() {                                              
String addText="";
String cntry_cd="";
String cntry_nm="";

Class.forName("com.sun.jdbc.driver");
String url= "jdbc:sqli://123.256.456:1234/test";

Connection conn = DriverManager.getConnection(url,"test","test");

DatabaseMetaData meta = conn.getMetaData();
Statement stmt = conn.createStatement();
String sql = "select * from country";
ResultSet rslt = stmt.executeQuery(sql);
while ( rslt.next() )
{
cntry_cd = rslt.getString("ctry_cd");
cntry_nm = rslt.getString("ctry_nm");

addText = addText + "<OPTION VALUE=\"" + cntry_cd + "\">" + cntry_nm + "</OPTION>\n";
}                    

stmt.close();
conn.close();
return addText;
}
%>
<HTML>
<HEAD>
<TITLE>Commodity Page</TITLE>                                        
</HEAD>                                                    <BODY>                                                     <center>                                                   <IMG SRC=/images/wsisupport/webshipping.gif height=100>              
<HR>                                                       </center>                                                  <FORM NAME="login" ACTION="test.jsp" METHOD="post">              
<TABLE BORDER=0 CELLSPACING=4 CELLPADDING=3 WIDTH="100%">
<TR>
<TH>Commodity Search</TH>
</TR>

<TR>                                                       <TD>Select Country</TD>
<TD><SELECT NAME="country"><%= getCountries() %></SELECT></TD>
</TR></TABLE>
</BODY>
</HTML>

-----------------------------------------------------------

I would be grateful if you can point out my errors. By the way how I call a function in JSP, I am getting uncomfortable using JSP, how do I brush up my Java? Any comments?

Thanks for your guidence.


Cheers
Jason
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6243726
what is the exeption u r getting?
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6243727
what is the exception u r getting?
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6243759
  <%@ page language="java" %>
<%@ page import="java.util.*, java.io.*, java.net.*,java.sql" %>
<%! public String getCountries() throws Exception{                                              
String addText="";
String cntry_cd="";
String cntry_nm="";

Class.forName("com.sun.jdbc.driver");
String url= "jdbc:sqli://123.256.456:1234/test";

Connection conn = DriverManager.getConnection(url,"test","test");

DatabaseMetaData meta = conn.getMetaData();
Statement stmt = conn.createStatement();
String sql = "select * from country";
ResultSet rslt = stmt.executeQuery(sql);
while ( rslt.next() )
{
cntry_cd = rslt.getString("ctry_cd");
cntry_nm = rslt.getString("ctry_nm");

addText = addText + "<OPTION VALUE=\"" + cntry_cd + "\">" + cntry_nm + "</OPTION>\n";
}                    

stmt.close();
conn.close();
return addText;
}
%>
<HTML>
<%

try
{
%>
<HEAD>
<TITLE>Commodity Page</TITLE>                                        
</HEAD>                                                    <BODY>                                  
                  <center>                                                   <IMG SRC=/images/wsisupport/webshipping.gif
height=100>              
<HR>                                                       </center>                                
                  <FORM NAME="login" ACTION="test.jsp" METHOD="post">              
<TABLE BORDER=0 CELLSPACING=4 CELLPADDING=3 WIDTH="100%">
<TR>
<TH>Commodity Search</TH>
</TR>

<TR>                                                       <TD>Select Country</TD>
<TD><SELECT NAME="country"><%= getCountries() %></SELECT></TD>
</TR></TABLE>
</BODY>
<%

}
catch(Exception e)
{
}
%>

Check this code
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6243771
u missed to import java.sql classes
u missed to include try and catch statements
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6243777
String sql = "select * from country";
cntry_cd = rslt.getString("ctry_cd");
cntry_nm = rslt.getString("ctry_nm");

if u check above three lines


as u need only two columns
modify ur sql statement as

"select cntry_cd,cntry_nm from country";
if(the country have more than 2 columns only)

so that u can reduce the burden to database



0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:jason101799
ID: 6243804
Sudhakar,

I have another question. How can I separate the connection to the database using another function. I have written some codes but I need to know why it fails. The error message was refering to the "return conn;" It says that this may not have been initialised.

Please help.

Below is the code:

-----------------------------------------------------------
<%@ page language="java" %>
<%@ page import="java.util.*, java.io.*, java.net.*, java.sql.*" %>
<%! public static java.sql.Connection Dbopen()
{
        Connection conn;  
        try{            
        Class.forName("com.informix.jdbc.IfxDriver");
String url = "jdbc:informix-sqli://199.40.141.122:2222/webship:I
NFORMIXSERVER=wsi_srv;ONCONFIG=onconfig.wsi;DBDATE=DMY2;DBCENTURY=C";
        conn = DriverManager.getConnection(url,"webship","wsp123");                                
         } catch (ClassNotFoundException cnfe){ System.err.println("Error loading driver");            
                        } catch (SQLException sqle){  System.err.println(sqle);}                            
        return conn; <----------------ERROR HERE!    
 }                                                                    
public String getCountries()            
{
String addText="";    
String cntry_cd="";    
String cntry_nm="";    
Connection conn1 = Dbopen();  
Statement stmt = conn1.createStatement();
try{
    String sql = "select cntry_cd,cntry_nm from country";
    ResultSet rslt = stmt.executeQuery(sql);
    while ( rslt.next() )
    {
     cntry_cd = rslt.getString("ctry_cd");
     cntry_nm = rslt.getString("ctry_nm");

     addText = addText + "<OPTION VALUE=\"" + cntry_cd    + "\">" + cntry_nm + "</OPTION>\n";
    }catch (SQLException sqle){                    
       System.err.println(sqle);
    }
    stmt.close();
    conn1.close();
    return addText;
}
try
{
%>
<HEAD>
<TITLE>Commodity Page</TITLE>                                        
</HEAD>                                                    <BODY>                                  

                 <center>                                                   <IMG SRC=/images/wsisupport/webshipping.gif

height=100>              
<HR>                                                       </center>                                

                 <FORM NAME="login" ACTION="test.jsp" METHOD="post">              
<TABLE BORDER=0 CELLSPACING=4 CELLPADDING=3 WIDTH="100%">
<TR>
<TH>Commodity Search</TH>
</TR>

<TR>                                                       <TD>Select Country</TD>
<TD><SELECT NAME="country"><%= getCountries() %></SELECT></TD>
</TR></TABLE>
</BODY>
<%

}
catch(Exception e)
{
}
%>

-----------------------------------------------------------
Please help.


Thank you



Cheer
Jason
0
 
LVL 14

Accepted Solution

by:
sudhakar_koundinya earned 100 total points
ID: 6247307
Yes obviously u will get that error
you have to initialise the objects to some value;

For example :

String s=new String();
Vector vect=null;
StringTokenizer st=new StringTokenizer("Welcome to Java World");

and so on.

In ur case initialse conn object to null;

Connection conn=null;
Just think ur case. u r initialsing conn object in try block.If any exceptoin raises it comes out o the block and u r try ing to return a value whaich has no value.

So it is safe and suggestable to initialise the objects to null even u r re initialising them or not.


in calling method

let if ur method name is getConnection()
Connection con=null;
try
{
con=getConnection();

if(con!=null)
{
//ur code goes here
}
else
{
out.println("Problem with database .contact ur server administrator");
}

}
}
catch(Exception e)
{
//some exception
//may be sql or some other exceptions
}


it is suggested that u have to eliminate all exceptions before calling the method in calling method.



Regards
Sudhakar
0
 

Author Comment

by:jason101799
ID: 6248101
How do i do paging in jsp?? I wanted to display 10 records per page. Do u mind to provide me the skeleton structure so that I can study on it? Your help is much appreciated.

Thank you

Cheers
Jason
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6249105
Okay u can do one thing

<%
int page=1;

int n=1;
while(rs.next())
{
n++;
if(n%10==0)
{
%>
<a href =doposting(<%=page%>)<%=page%></a>
<%
page++;
}
}
%>


This is some what a rough skeleton

If u understand this idea u can do further


Cheers

Sudhakar
0
 

Author Comment

by:jason101799
ID: 6250956
Sudhakar,

I understand the skeleton structure that you sent, but how do i control the the records to be shown? If the first page ends with 10 records, how do I control such that the second page that I clicked will continue from the eleventh records onward for the next ten records?
 I have come across ASP and the have a Page Size and Page count to actually do this trick. Does java have this technique?

Thanks


Cheers
JAson
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6258407
Hi


First tell me what is the database u r using?

If u r using oracle


modify ur sql statement as


String page="0";
if(request.getParameter("page")==null)
{
  page="0";
}

String sql="select cntry_cd,cntry_nm from country where rownum<"+Integer.parseInt(page)+
minus select cntry_cd,cntry_nm from country where rownum<"+Integer.parseInt(page)-1;

regards

Sudhakar
0
 

Author Comment

by:jason101799
ID: 6258468
Sudha,

I am using Informix. Will there be any problem?

Cheers
Jason
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6262744
Hi Jason ,

Yes this query string will work in oracle only.Because rownum is special keyword provided  in oracle.
If u find the equivalent let me know that.


String sql="select cntry_cd,cntry_nm from country where rownum<"+Integer.parseInt(page)+
minus select cntry_cd,cntry_nm from country where rownum<"+Integer.parseInt(page)-1;


By the way try this idea. but this is slow.


String page="0";
if(request.getParameter("page")==null)
{
 page="1";
}


int start =Integer.parseInt(page)-1*10;
int end=Integer.parseInt(page)*10;

int n=0;
while rs.next())
{
if(n>=start && n<=end)
{
//print the info u want here
}
if(n>end)
   break;
n+=1;    
}

Regards sudhakar


By this is my personal interest.Where r u from?

because only Indians call sudhakar as sudha (In friends circle and family only)
0
 

Author Comment

by:jason101799
ID: 6263436
Sudha,

I am a Malaysian chinese by the way, in that case can you suggest other solution with reagrds to my qs?


Cheers
Jason
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6282249
Hi Jason

I think we have to close this session now.

Don't u think this session is boring now.If 4-5 friends are in discussion we can exchange more ideas.Just close this session and start the new session.When u start new thread just mail me to sudhakar_koundinya@yahoo.com . I will help u by participating in the new thread.

Cheers

Koundinya
0
 

Author Comment

by:jason101799
ID: 6284399
Sure do mate.....

By the way how do i close this session?????



Cheers
0
 
LVL 14

Expert Comment

by:sudhakar_koundinya
ID: 6284727
u will find accept comment option ur side.just click on that and site ask u to grade this session.just click on one of the grades accept it.


Cheers
Koundinya.
0
 

Author Comment

by:jason101799
ID: 6284742
It's all yours mate!
0

Featured Post

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

Suggested Solutions

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
This tutorial covers a step-by-step guide to install VisualVM launcher in eclipse.

747 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

17 Experts available now in Live!

Get 1:1 Help Now