Solved

How to read a file using JSP?

Posted on 2001-06-27
25
244 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
[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
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 

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

Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

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

An old method to applying the Singleton pattern in your Java code is to check if a static instance, defined in the same class that needs to be instantiated once and only once, is null and then create a new instance; otherwise, the pre-existing insta…
In this post we will learn how to make Android Gesture Tutorial and give different functionality whenever a user Touch or Scroll android screen.
Viewers learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:

728 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