Reading a properties file in a servlet and passing its contents to a JSP pa

Hi all,
I'm totally new to Servlet pgmg n JSP. Please can ne1 tell how to read a simple properties file (in a servlet) and pass its contents to a JSP page.Actually the reason is to fill a combo box in a JSP page with the contents of a properties file.If calling a servlet for the same is d best way to do that, plz can ne1 tell me :
1> whether to override the doPost method in the servlet in which to read d file using FileInputStream
2> Putting the contents in an array and then how to pass this array to the JSP page.
Thanks,
deepthy.

I'm using a properties file to let my web application know what the name of the database is. I'm using an abstract class GeneralDao which will be extended by all the DAO's (Data Access Objects or java classes containing SQL statements).
Here's the code :
protected Connection getDatabaseConnection()
          throws Melding
     Connection dbconn = null;     
     ResourceBundle resBundle;
     try
     Class.forName("com.mysql.jdbc.Driver").newInstance();
     resBundle = ResourceBundle.getBundle("gcoConfig");
     String dbConnectie = resBundle.getString("databaseconnection");
     gcoLogger.debug("lezen databaseconnection in resourceBundle " );
     dbconn = DriverManager.getConnection(dbConnectie);
     } catch (InstantiationException exc)The ResourceBundle is used to read the properties file, named gcoConfig.properties.
With the getString() command I read the content of the string named databaseconnection.
The gcoConfig.properties file is placed inside the folder C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\gco\WEB-INF\classes
The GeneralDao is placed in the folder C:\Program Files\Apache Software Foundation\Tomcat 5.0\webapps\gco\WEB-INF\classes\org\gertcuppens\cluifDao.
So this class is placed some folder below the WEB-INF\classes folder of gcoConfig.properties.
And the content of the properties file is just one line :
databaseconnection=jdbc:mysql://localhost/cluif
If you want to let the JSP know what's inside the properties file, wrap the content in a Javabean, put it in the request or even the session and pass the control to the JSP.

Similar Messages

  • Help: Servlet can't read from properties file

    I am working on a web application running in Tomcat on Linux.My java source file reads some parameters from a properties file (data.properties)in the same directory. This works well in a simple application. However, if it is used in the Tomcat environment, it can't be read by a servlet file (LoginServlet.java). I put both the "LoginServlet.class" and "data.properties" in the following directory: /webapps/myapp/WEB-INF/classes. When I run the web application in Tomcat, the error is "data.properties not found". What is the problem? Do I need to modify my "web.xml" and/or Tomcat's "server.xml"? If so, how to modify them?
    This web application contains a lot of serlets. So I don't want to hardcode the parameters into the servlet codes.
    Any info will be appreciated. Thanks in advance!:)

    Putting the properties file in webapps/myapp may or may not help.
    My assumption is that you are trying to open the file by brute force, with something like
    InputStream propis = new FileInputStream ("data.properties");
    Properties props = new Properties ( );
    props.load (propis);
    What you want is to have the class loader find a file in the same place as the class file, and give you back an input stream reading from that file, which you can then pass to the Properties.load(InputStream) method. This is called a "resource," and the way to do it is:
    InputStream propis = getServletContext().getResourceAsStream("data.properties");
    // remaining code as above
    This will cause the class loader for the servlet context (a/k/a the Web application) to find the file in the same manner as it might find a class, but instead of treating it as compiled JVM code, and loading it, it simply passes you back an InputStream from which you do whatever you want.
    Cheers!
    Jerry Oberle
    perl -e 'printf "mailto%cg%s%cearthlink%cnet\n", 58, "oberle", 64, 46;'

  • Can a servlet read a jsp file and display its contents?

    Hi,
    I would like to know if Servlets can read a Jsp file and display its contents.. Right now for our website, I am using a html file to be displayed after a successful post operation through the Servlets...
    -Thanks!

    I posted this in another thread.
    Here's some code that reads using a URL. This doesn't work with JSPs as the server executes JSP when it connects but it's useful for other file types. Note that the filename is a URI</h1>This is <code>show.jsp</code></h1>
    <hr>
    <%! String file = null; %>
    <%! java.io.InputStream is = null; %>
    <%
    file = request.getParameterValues("filename")[0];
    try {
       is = (new java.net.URL(file)).openStream();
    } catch (java.io.IOException ioe) { out.write(file + " not found!<br>"); }
    java.io.BufferedReader in = new java.io.BufferedReader(new java.io.InputStreamReader(is));
    String line = "";
    %>
    <pre>
    <%
    while((line = in.readLine()) != null) {
    %>
    <%=line%>
    <%
    %>
    </pre>

  • How do I read a properties file in WEB-INF without hard-coding a path?

    Hello,
    How do I read a properties file in WEB-INF without hard-coding a path?
    I tried:
    Properties properties = new Properties();
    properties.load(new FileInputStream("db.properties"));
    driver = properties.getProperty("driver");
    but it cannot find the db.properties file.
    Thanks for the help.
    Frank

    Don't use a File to read those properties.
    Better to use the servlet context and
    getResourceAsStream() method to get the InputStream.
    It'll look for any file in the CLASSPATH. If you put
    that properties file in the WEB-INF/classes directory
    you'll have no problems, even if you deploy with a
    WAR file.Completely agree with this approach. Just have to mention the following for completeness
    according to the API,
    "This method is different from java.lang.Class.getResourceAsStream, which uses a class loader. This method allows servlet containers to make a resource available to a servlet from any location, without using a class loader. "
    So using this method, the resource can be anywhere under your web context, not just in the classpath.
    Cheers,
    evnafets

  • How to read the properties file available in Server File structure in webdy

    hi all,
    I have developed one webdynpro application. In this application i need to access mdm server to continue. For getting the connection i need to pass the IP addresses.
    Can i have code  how to read the properties file which is residing in the server file. with out included along with the application. keeping some where in the file structure in the server. I want to read that properties file by  maintain the iP addresses and users in  properties file based on the key i want to read like below.
    servername="abcServer"
    username="john"
    password="test123"
    Please send me the code how to read this properties file from the file structure and how to read this values by key  in webdynpro application
    Regards
    Vijay

    Hi Vijay,
    You can try this piece of code too:
    Properties props = new Properties();
    //try retrieve data from file
    //catch exception in case properties file does not exist
    try {
             props.load(new FileInputStream("c:\property\Test.properties")); //File location
             String serverName = props.getProperty("servername"); //Similarly, you can access the other properties
             if(serverName==null)
               //....do appropriate handling
         }     catch(IOException e)
                   e.printStackTrace();
    Regards,
    Alka.

  • Read a Properties File in a Static Floating Block

    I am trying to read a properties file in a static floating block:
       static
          try
             Properties p = new Properties();  
             String path = "/WEB-INF/classes";
             InputStream is = getClass().getResourceAsStream( path + "artimus_message_MessagInboxConfig.properties" );
             p.load(is); // load the stream into the Properties object
             WEBSITE_HOME = p.getProperty( "WEBSITE_HOME" );
             setWebSiteHome( WEBSITE_HOME );
          catch { ......}
       }I got a compilation error saying that the non-static method getClass() cannot be referenced from a static context. There is almost no way to make this static floating block non-static. What should I do?

    Thanks for the reply. But, huh... I do not quite
    understand. Which class is MyClass?It's a generic placeholder for whichever class your put that block into. You wouldn't put it there literally--replace it with the name of the actual class. If that block is in Foo.java, then use Foo.class instead of MyClass.class.
    >
    Okay, this static floating block is in a class called
    MessageInboxConfig.java. Then use MessageInboxConfig.class.getResourceAsStream(...)
    And inside this static
    floating block, I am reading a properties file and
    this properties file is in the
    ContextRoot/WEB-INF/classes/artimus_message_MessagInbox
    onfig.propertiesHow do I read this properties file?
    Properties p = new Properties();  
    InputStream is = MessageInboxConfig.class.getResourceAsStream("artimus_message_MessagInboxConfig.properties" );
    ... etc. ...You shouldn't need to specify "WEB-INF/classes," since it should be in your classpath. What you pass to getResource is a path relative to a directory in your classpath.

  • How can load properties file for one time and use in entire application

    Hi folks,
    I dont want to read properties file every time , and want to get property value in any servelet or jsp page.(means i want to read only property file only for once and want to get value in any where ) , how to do this.
    Message was edited by:
    RajeshwarReddyT

    means we have to read file every time Know but i dont
    want to be happen that ??? No you don't . You read the file once. You store it in the hashmap. Then you hand that hashmap to whatever class needing the data.
    getProperties() returns the hashmap, doesn't read the file.
    Maybe I should have called the method getMap or something.
    Message was edited by:
    karma-9

  • How to read from properties file

    Hi,
    I am using JSR 168.
    while creating a new portlet, a folder gets created with the name as "portlet". Under which is resource package and <PortletName>Bundle.java.
    pls tell me how to read from .properties file.
    waiting eagerly for some reply
    Thanks & Regards,
    HP
    Edited by: user9003827 on Apr 13, 2010 3:42 AM

    I think i have mixed it up :)
    I have looked at it again and believe you are using regular JSP portlets.
    Can you tell what you want to achieve by reading .properties file. Are you meaning the preferences of the portlet or what exactly are you trying to do?
    Reading propertie files is easy:
    // Read properties file.
    Properties properties = new Properties();
    try {
        properties.load(new FileInputStream("filename.properties"));
        String myKey = properties.getProperty("yourKey");
    } catch (IOException e) {
    }Edited by: Yannick.O on 13-Apr-2010 05:52

  • URGENT.........File Upload using Servlets and jsp

    I am a new servlet programmer.......
    iam using tomcat server......
    can any one pls help in writing code for file upload using servlets and jsp without using multipart class or any other class like that....
    Please URGENT..

    Slow down! "Urgent" is from your perspective alone. I, myself, am not troubled or worried in the least.
    hi ugniss
    thanks for ur reply....sorry i was not
    y i was not asked not to use multipart class or any
    other class like that...is there any other
    possibility to do file uploading from jsp to
    servlet...
    Just as an aside, a JSP is a Servlet. But even if I move beyond that, the question does not make sense. If you want a "JSP to upload to a Servlet", then simply do so in memory. You are still (likely) within the same scope of a given request. However, if instead you are referring to a JSP that is displayed on a browser, then really you are talking about HTML, which is what the browser will receive. And since you are now talking about a browser, your only real, viable option is a multi-part file upload. So, it is either server or it is browser. And either way, the question leads to very established options, as outlined above.
    the main concept is.. in the browser the user selects
    a particular file and clicks the button upload..after
    clicking upload the jsp should sent the file to the
    servlet in streams...there the servlet gets in and
    saves in a server location........this is wat i hav
    to do...
    Okay. So, after reading my previous (redundant) paragraph, we have arrived at the crux of the issue. You have a JSP that will be output as HTML to a client (browser) which you want to upload content to your server (handled by a Servlet). So, you are now stuck again with multi-part. The requirement to not use multi-part is non-sensical. You can overcome it, say, if you write your own applet or standalone Swing client. However, if your users are invoking this functionality from a browser, you are limited by the options that W3C has provided you. Use multi-part.
    is there aby possibilty to do this.....can any one
    pls help....Take the advice to download and review Jakarta Commons FileUpload. Inform your management that their requirement makes no technical sense. Research on your own. There are dozens of examples (and tutorials) on file upload using multi-part. Embrace it. Live it. Love it.
    - Saish

  • I got ZipException to read Jndi.Properties file

    hello friends,
    here i got ZipException to get Jndi.Properties file.
    i place Jndi.Properties file in my directory and i set classpath to weblogic.jar&Jndi.Properties file.
    but i didn't get InitialContext obj.though i got zipException.
    jvm displays Jndi.Properties file is not read.

    To try out I pasted the code given by u in my application as a demo
         private static Connection connect() throws Exception{
         InputStream in = QueryTest.class.getResourceAsStream("JDBC.properties");
              Properties props = new Properties();
              props.load(in);
              //in.close();
              String driver = props.getProperty("JDBC.driver");
              System.out.println(driver);
              String url = props.getProperty("JDBC.url");
              System.out.println(url);
              String user = props.getProperty("JDBC.user");
              System.out.println(user);
              String pwd = props.getProperty("JDBC.password");
              System.out.println(pwd);
              in.close();
              Class.forName(driver);
              return DriverManager.getConnection(url, user, pwd);
         public static void main(String[] args) throws Exception{
              Connection con = connect();
              //Put your code here
    JDBC.properties file is
         url = jdbc:mysql://localhost:3306/mysql
              user= root
                   password =password
                   driver=com.mysql.jdbc.Driver
    And the error messages are
    null
    null
    null
    null
    Exception in thread "main" java.lang.NullPointerException
         at java.lang.Class.forName0(Native Method)
         at java.lang.Class.forName(Unknown Source)
         at Generic.QueryTest.connect(QuerryTest.java:28)
         at Generic.QueryTest.main(QuerryTest.java:35)

  • Java.lang.NullPointerException   in the code to read a properties file

    I have written the following code to read a properties file...........
    <b>
    public Property(String fileName)
        try
           InputStream is = MyClassName.class.getClass().getClassLoader().getResourceAsStream(fileName);     
           prop.load(is);
           is.close();
        catch (Exception ex)
            System.out.println("The Exception is:        " + ex.getMessage());
            ex.printStackTrace();
    </b>
    But this code is giving <b> java.lang.NullPointerException </b> at <b> prop.load(is) </b>
    please help me....
    regards
    Brahmachaitanya

    hi,
        If you are loading a resource (property) file from a jar file you can use
    getResourceAsStream("com/test/test.properties").
        if the propery file is in outside of your jar file . you can use
    Property portalProps = new Property ();
    try {
                   FileInputStream fileInputStream = new FileInputStream("<FilePath + FileName>");
                   portalProps.load(fileInputStream);
                   fileInputStream.close();
              } catch (IOException e) {
                   //Log the error
    refer the following link for more details
    http://www.javaworld.com/javaworld/javaqa/2003-08/01-qa-0808-property.html

  • I have made .indd file with some form fields in it, now haw to read these fields and manipulate its content through script in indesign

    I have made .indd file with some form fields in it, now haw to read these fields and manipulate its content through script in indesign

    It's probably best to ask in the InDesign Scripting forum:
    InDesign Scripting

  • How to create a file and store its contents into another file?

    Hi,
    I'm having some trouble trying to create a code where I have to to create a file and store its contents into another file?
    I read the API, but I'm not certain how this file thing works.
    Here's my code so far:
    public static void main(String[] args) throws Exception
              File file = new File("tasks.txt");
              if (file.exists())
                   System.out.println("File already exists");
                   System.exit(0);
              Scanner scan = new Scanner(System.in);
              Scanner scan2 = new Scanner(System.in);
              //Scans the input line by line
              scan.useDelimiter("\\n");
              //Scans the input by tabs
              scan2.useDelimiter("\\t");
              PrintWriter outputs = new PrintWriter("newtasks.txt");
              outputs.print("ok");
              outputs.println(3);
              outputs.close();
         }

    I managed to change my text into uppercase, but how do I store the uppercase content into another file.
    -So this is what I did so far, I took a text file and modified its strings to uppercase.
    -Now I need to put those modified strings into another text file, is there a way where I can do that with my current code?
    -I already tried printwriter, but it doesn't seem to work
    public static void main(String[] args)throws IOException
              //Task[] oneHundredTasks = new Task[100];
              String uppercase;
              String combine;
              Scanner scan = null;
              FileInputStream in = null;
            FileOutputStream out = null;
            PrintWriter output = null;
            try
                 scan = new Scanner(new BufferedReader(new FileReader("tasks.txt")));
                 scan.useDelimiter("\\n");
                 scan.useDelimiter("\\t");
                while (scan.hasNext())
                     if(!scan.hasNext())
                          scan.next();
                     combine = scan.next();
                     uppercase = combine.toUpperCase();
                     System.out.println(uppercase);
            finally
                if (scan != null)
                    scan.close();
            //The program will try the input and output files
            try
                 in = new FileInputStream("tasks.txt");
                out = new FileOutputStream("newtasks.txt");
                int c;
                //The number "-1" is used to indicate that it has reached the end of the stream.
                while ((c = in.read()) != -1)
                    out.write(c);
            finally
                if (in != null)
                    in.close();
                if (out != null)
                    out.close();
         }

  • How to browse a file and extract its contents

    i want to browse a file and extract its contents.My code is given below but its not working .Can anybody help me please
    JFileChooser fc = new JFileChooser();
              int returnVal = fc.showOpenDialog(jfrm);
              if (returnVal == JFileChooser.APPROVE_OPTION)
              File file = fc.getSelectedFile();
              //This is where a real application would open the file.
              fileName=file.getName();
              //This is a file function to extract data from a file.
              //It reads data from a file that can be viewed on cmd
              jlab3.setText(fileName);
              try
    // Open the file that is the first
    // command line parameter
    FileInputStream fstream = new FileInputStream(fileName);
    // Convert our input stream to a
    // DataInputStream
              DataInputStream in =new DataInputStream(fstream);
    // Continue to read lines while
    // there are still some left to read
    // while (in.available() !=0)
    // Print file line to screen
              fileName1=in.readLine();
              jlab3.setText(fileName1);
              in.close();
    catch (Exception e)
              System.err.println("File input error");
              }

    JFileChooser fc = new JFileChooser();
    int returnVal = fc.showOpenDialog(jfrm);
    if (returnVal == JFileChooser.APPROVE_OPTION)
    File file = fc.getSelectedFile();
    //This is where a real application would open the file.
    fileName=file.getName();
    //This is a file function to extract data from a file.
    //It reads data from a file that can be viewed on cmd
    jlab3.setText(fileName);
    try
    // Open the file that is the first
    // command line parameter
    FileInputStream fstream = new FileInputStream(fileName);
    // Convert our input stream to a
    // DataInputStream
    DataInputStream in =new DataInputStream(fstream);
    // Continue to read lines while
    // there are still some left to read
    // while (in.available() !=0)
    // Print file line to screenHere you are reading the first line of the file
      fileName1=in.readLine();
    //}and here you are displaying the line in a (I suppose) JLabel. A JLabel is not very suitable for displaying a file content, except is the file contain few characters !!!
    jlab3.setText(fileName1);
    in.close();
    catch (Exception e)
    System.err.println("File input error");
    }If you want to read the complete file content you must uncomment lines inside while instruction, like this
    while (in.available() > 0) {  // I prefer to test in.available like this, instead of !=
      // append text to a StringBuffer (variable named sb here) or directly in a textarea.
      sb.append(in.readLine());
    ...

  • Upload 2 files and compare its contents

    Hi guys,
    I want to upload 2 files in SAP and compare its contents.
    How am i going to do that?
    Please provide sample code... Thanks a lot!
    rgds,
    Mark

    Hi Mark,
    I expected to use this code, once u can try this code.
      OPEN DATASET lv_filename FOR OUTPUT IN TEXT MODE ENCODING DEFAULT.
      IF sy-subrc = 0.
        LOOP AT gi_output1 INTO gwa_output1.
          CLEAR lv_string.
          CONCATENATE gwa_output1-matnr
                      gwa_output1-maktx
                      gwa_output1-werks
                      gwa_output1-bmeng
                      gwa_output1-posnr
                      gwa_output1-idnrk
                      gwa_output1-ojtxp
                      gwa_output1-mngko
                      gwa_output1-mmein
                      gwa_output1-flag
                      INTO lv_string
                      SEPARATED BY cl_abap_char_utilities=>horizontal_tab.
          TRANSFER lv_string TO lv_filename.
          IF sy-subrc <> 0.
            MESSAGE e006(zpdm).
          ENDIF.              "if sy-subrc <> 0.
        ENDLOOP.
         OPEN DATASET lv_filename FOR appending IN TEXT MODE ENCODING DEFAULT.
      IF gi_output2[] is not initial.
        LOOP AT gi_output2 INTO gwa_output2.
          CLEAR lv_string.
          CONCATENATE gwa_output2-matnr
                      gwa_output2-ojtxb
                      gwa_output2-werks
                      gwa_output2-bmeng
                      gwa_output2-posnr
                      gwa_output2-idnrk
                      gwa_output2-ojtxp
                      gwa_output2-mngko
                      gwa_output2-mmein
                      gwa_output2-flag
                INTO  lv_string
           SEPARATED BY cl_abap_char_utilities=>horizontal_tab.
          TRANSFER lv_string TO lv_filename.
          IF sy-subrc <> 0.
            MESSAGE e007(zpdm). " WITH text-006.
          ENDIF.           "if sy-subrc <> 0.
        ENDLOOP.
      ENDIF.

Maybe you are looking for

  • Different color text in one cell

    How do I set a color for a group of words within a cell leaving the rest of the words black? I can make all the text within a cell the same color but when I select the words I want to be a different color the color selector in the toolbar goes away a

  • Missing information by Apple about handling album cover in general

    I have just read several threads about the album cover question and it seems to me as if some helpful and official words by Apple would be necessary. How is cover art handled? Is there a new technique for local storage? Are covers no longer embedded

  • Intermedia in oracle 10g

    Hi friends, thinking about migration from oracle 9i to oracle 10g. We use intermedia indexes on text columns of some tables. Is there any advantage with oracle 10g intermedia? Which are the most significant changes? Thanks for answers.

  • Help with the date field!!! in opportunity

    hello friends!!!! I have a requirement that in opportunity tab milestone we have created date profile with 4 different date types and position them to milestone tab in opportunity header data. Now the issue is out these 4, 2 of them we wish to have a

  • How do I manually change the genre or track name

    I'm new here, so forgive me if this is easily done. I would like to know how to manually change a song's track name, or genre in iTunes. If i feel like a song is more appropriately labeled "pop" vs "rock" can I change the label? Any help would be gre