Link to home
Start Free TrialLog in
Avatar of jason101799
jason101799

asked on

How to read a file using JSP?

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.
Avatar of sudhakar_koundinya
sudhakar_koundinya

Do u want read the text from Server file or Client File?
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
<%@ page import=logging.*%>
<%
     UsersReader ur= new UsersReader();
     String s=ur.read("/weblogic/myserver/public_html/MyText.txt");
     out.println(s);

%>

here is jsp code
<%@ page import=logging.*%>
<%
     UsersReader ur= new UsersReader();
     String s=ur.read("/weblogic/myserver/public_html/MyText.txt");
     out.println(s);

%>

here is jsp code
Avatar of jason101799

ASKER

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
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
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
what is the exeption u r getting?
what is the exception u r getting?
  <%@ 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
u missed to import java.sql classes
u missed to include try and catch statements
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



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
ASKER CERTIFIED SOLUTION
Avatar of sudhakar_koundinya
sudhakar_koundinya

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
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
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
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
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
Sudha,

I am using Informix. Will there be any problem?

Cheers
Jason
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)
Sudha,

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


Cheers
Jason
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
Sure do mate.....

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



Cheers
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.
It's all yours mate!