• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 264
  • Last Modified:

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.
0
jason101799
Asked:
jason101799
  • 16
  • 9
1 Solution
 
sudhakar_koundinyaCommented:
Do u want read the text from Server file or Client File?
0
 
sudhakar_koundinyaCommented:
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
 
sudhakar_koundinyaCommented:
<%@ 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
Upgrade your Question Security!

Your question, your audience. Choose who sees your identity—and your question—with question security.

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

I am using Informix. Will there be any problem?

Cheers
Jason
0
 
sudhakar_koundinyaCommented:
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
 
jason101799Author Commented:
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
 
sudhakar_koundinyaCommented:
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
 
jason101799Author Commented:
Sure do mate.....

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



Cheers
0
 
sudhakar_koundinyaCommented:
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
 
jason101799Author Commented:
It's all yours mate!
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

  • 16
  • 9
Tackle projects and never again get stuck behind a technical roadblock.
Join Now