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

Similar Messages

  • Log4J - reading properties file from /WEB-INF directory issue..

    I'm just learning to implement Log4J; the approach I am taking for my JSF application running under Tomcat 5.5x is to create an initialization servlet to initialize the logger, and then access the logger instance within my backing beans and application module services. I include log4j.jar file in /WEB-INF/lib and log4j.properties in /WEB-INF.
    First I wanted to see if this was a good approach, and secondly I'm having trouble accessing the log4j.properties file from the /WEB-INF directory (see below) - any suggestions on how to set up the path so that the properties file can be found (I receive a java.io.filenotfoundexception)?
    Where I'm looking for direction is how to define a single instance of the logger and then access that instance from my java classes versus re-creating the logger in each class.
    ----- web.xml --------
    <servlet>
    <servlet-name>LogServlet</servlet-name>
    <servlet-class>com.sidehire.view.util.LogServlet</servlet-class>
    <init-param>
    <param-name>setup</param-name>
    <param-value>/WEB-INF/log4j.properties</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
    </servlet>
    ------ LogServlet class ------
    public void init()
    throws ServletException {
    String config = getInitParameter("setup");
    PropertyConfigurator.configure(config);
    Thanks
    Message was edited by:
    javaX

    Try to put the log4j.properties in your WEB-INF/classes/ directory.
    You could wrap one log4j instance in a static method in a utility class, but then you would probably lose other information depending on your logger configuration.
    If you create an instance in each class, which after all is just one line like this:
    static Logger logger = Logger.getLogger(ChangePasswrdAction.class.getName());
    then you are able to get time and method information.

  • PLEASE HELP. How do you access properties files in WEB-INF  and classes directory

    We have a war file that needs to access properties files that are in the WEB-INF directory
    of the war file. We also need to load one of the properties files from the classpath.
    However, when we deploy the application ( an ear which inlcludes an ejbjar and a
    war and the libraries both the ejbjar (with a manifest setting the classpath ) and
    war need ) the properties don't get extracted.
    In some of our servlets we are trying to access those files with the path "WEB-INF/foo.properties"
    and we get a FileNotFoundException. Then we check and see that NO properties files
    have been extracted into their appropriate places ( not even those we throw into
    the WEB-INF/classes directory ).
    PLEASE HELP,
    Christian Hargraves

    The file doesn't have to be extracted from the war. For example, you can place
    test.properties into your app WEB-INF and write a simple JSP to see how it
    works:
    <%
    InputStream in = application.getResourceAsStream("/WEB-INF/test.properties");
    %>
    It will return you a zip inputstream if you deployed your application as a .war.
    Christian Hargraves <[email protected]> wrote:
    I try this, but I get a NullPointerException. The file never actually gets extracted
    from the war. Under tomcat and resin this works great ( that's why I am having all
    of the trouble i am having ), but there are absolutely no properties files in the
    extracted directories for WebLogic deploys. only:
    WEB-INF/some_tmp_dir/WEB-INF/lib
    and then some dynamically generated jor file with all of the classes that would normally
    go in WEB-INF/classes ( all except the properties, of course, which are no where
    to be found. ).
    There has to be some kind of setting I am missing. Please don't make me seperate
    these properties files from the war/ear and then put the path to these properties
    files in the CLASSPATH, changing one step to three steps to deploy!!
    I have found a documented bug where you can't even put the properties files in a
    jar file and that bug will never be fixed for WebLogic 6.1.
    "Dimitri I. Rakitine" <[email protected]> wrote:
    To access files in WEB-INF you can use ServletContext.getResourceXXX("/WEB-INF/filename")
    Christian Hargraves <[email protected]> wrote:
    We have a war file that needs to access properties files that are in theWEB-INF directory
    of the war file. We also need to load one of the properties files fromthe classpath.
    However, when we deploy the application ( an ear which inlcludes an ejbjarand a
    war and the libraries both the ejbjar (with a manifest setting the classpath) and
    war need ) the properties don't get extracted.
    In some of our servlets we are trying to access those files with the path"WEB-INF/foo.properties"
    and we get a FileNotFoundException. Then we check and see that NO propertiesfiles
    have been extracted into their appropriate places ( not even those wethrow into
    the WEB-INF/classes directory ).
    PLEASE HELP,
    Christian Hargraves--
    Dimitri
    Dimitri

  • How to get the table name in the trigger definition without hard coding.

    CREATE  TRIGGER db.mytablename
    AFTER UPDATE,INSERT
    AS
        INSERT INTO table1(col1)
        SELECT InsRec.col1   
        FROM
        INSERTED Ins
       --Below i am calling one sp for which i have to pass the table name
       EXEC myspname 'tablename'
      In the above trigger,presently i am hard coding the tablename
      but is it possible to get the table name dynamically on which the trigger is defined in order to avoid hard coding the table name

    I really liked your audit table concept.  You inspired me to modify it so that, the entire recordset gets captured and added a couple of other fields.  Wanted to share my end result.
    USE [YourDB]
    GO
    /****** Object: Trigger [dbo].[iudt_AutoAuditChanges] Script Date: 10/18/2013 12:49:55 ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    ALTER TRIGGER [dbo].[iudt_AutoAuditChanges]
    ON [dbo].[YourTable]
    AFTER INSERT,DELETE,UPDATE
    AS
    BEGIN
    SET NOCOUNT ON;
    Declare @v_AuditID bigint
    IF OBJECT_ID('dbo.AutoAudit','U') IS NULL BEGIN
    CREATE TABLE [dbo].[AutoAudit]
    ( [AuditID] bigint identity,
    [AuditDate] DateTime,
    [AuditUserName] varchar(128),
    [TableName] varchar(128) NULL,
    [OldContent] XML NULL,
    [NewContent] XML NULL
    ALTER TABLE dbo.AutoAudit ADD CONSTRAINT
    PK_AutoAudit PRIMARY KEY CLUSTERED
    [AuditID]
    ) WITH( STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    CREATE NONCLUSTERED INDEX [idx_AutoAudit_TableName_AuditDate] ON [dbo].[AutoAudit]
    ( [TableName] ASC,
    [AuditDate] ASC
    )WITH (STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    END
    Select * Into #AuditDeleted from deleted
    Select * Into #AuditInserted from inserted
    While (Select COUNT(*) from #AuditDeleted) > 0 OR (Select COUNT(*) from #AuditInserted) > 0
    Begin
    INSERT INTO [dbo].[AutoAudit]
    ( [AuditDate], [AuditUserName], [TableName], [OldContent], [NewContent])
    SELECT
    GETDATE(),
    SUSER_NAME(),
    [TableName]=object_name([parent_obj]),
    [OldContent]=CAST((SELECT TOP 1 * FROM #AuditDeleted D FOR XML RAW) AS XML),
    [NewContent]=CAST((SELECT TOP 1 * FROM #AuditInserted I FOR XML RAW) AS XML)
    FROM sysobjects
    WHERE
    [xtype] = 'tr'
    and [name] = OBJECT_NAME(@@PROCID)
    Set @v_AuditID = SCOPE_IDENTITY()
    Delete from AutoAudit
    Where AuditID = @v_AuditID
    AND Convert(varchar(max),oldContent) = Convert(varchar(max),NewContent)
    Delete top(1) from #AuditDeleted
    Delete top(1) from #AuditInserted
    End
    END

  • 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.

  • 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

  • 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.

  • How to give comments in .properties file?

    hi
    can any one tell how to give commens in .properties file
    any thing after first space will be treated as key value pair
    thanks in advance
    bye

    hi
    can any one tell how to give commens in .properties
    fileAny line that begins with a # is a comment in a properties file. These are single line comments.
    any thing after first space will be treated as key
    value pairEh?
    thanks in advance
    byePreemptive welcome.

  • Urgent. How may i update a properties file in execution time?

    Urgent, please. How may i update a properties file in execution time? I need to update the file by means of a web page and i need the changes be reflected immediately.
    Thanks

    Note the update must be made in memory. But i don�t know how.

  • How can i locate the properties files within a ejb container?

    when i develop servlet+javabean structure application,in order to imploement decoupling,i
    would like to write the config information in the properties files(key-value pair),in
    servlet,i use "getResourceAsStream(String relativePath)" method to retrieve the
    configuration information from the properties files(i even write the SQL clause
    in the files),it alwsys works well.
    now,i want to implement such function within the ejb container,that is to read
    a properties file from session bean,but i don't know how can i locate the file
    within the ejb container by using relative path,i wonder if there is the same
    method within ejb container as "getResourceAsStream(.......)" method within servlet
    container?
    thanks for any helps!
    the code snippet is appreciated!

    In general, you should look at using environment entries (variables) in the
    deployment descriptors (both the war and EJB jar rather than properties
    files for configuring J2EE applications. The reasons for this are many:
    1. This is the official way to do it according to the spec. Properties
    files are the J2SE way of doing things
    2. As you note, that it's not obvious how you would (legally) read a
    properties file inside an EJB.
    3. It's consistent between the web and EJB part of your code
    4. the weblogic console and tools have good capabilities to edit these
    fields.
    Kent
    "zhebincong" <[email protected]> wrote in message
    news:[email protected]..
    >
    when i develop servlet+javabean structure application,in order toimploement decoupling,i
    would like to write the config information in the propertiesfiles(key-value pair),in
    servlet,i use "getResourceAsStream(String relativePath)" method toretrieve the
    configuration information from the properties files(i even write the SQLclause
    in the files),it alwsys works well.
    now,i want to implement such function within the ejb container,that is toread
    a properties file from session bean,but i don't know how can i locate thefile
    within the ejb container by using relative path,i wonder if there is thesame
    method within ejb container as "getResourceAsStream(.......)" methodwithin servlet
    container?
    thanks for any helps!
    the code snippet is appreciated!

  • How can one  read a Excel File and Upload into Table using Pl/SQL Code.

    How can one read a Excel File and Upload into Table using Pl/SQL Code.
    1. Excel File is on My PC.
    2. And I want to write a Stored Procedure or Package to do that.
    3. DataBase is on Other Server. Client-Server Environment.
    4. I am Using Toad or PlSql developer tool.

    If you would like to create a package/procedure in order to solve this problem consider using the UTL_FILE in built package, here are a few steps to get you going:
    1. Get your DBA to create directory object in oracle using the following command:
    create directory TEST_DIR as ‘directory_path’;
    Note: This directory is on the server.
    2. Grant read,write on directory directory_object_name to username;
    You can find out the directory_object_name value from dba_directories view if you are using the system user account.
    3. Logon as the user as mentioned above.
    Sample code read plain text file code, you can modify this code to suit your need (i.e. read a csv file)
    function getData(p_filename in varchar2,
    p_filepath in varchar2
    ) RETURN VARCHAR2 is
    input_file utl_file.file_type;
    --declare a buffer to read text data
    input_buffer varchar2(4000);
    begin
    --using the UTL_FILE in built package
    input_file := utl_file.fopen(p_filepath, p_filename, 'R');
    utl_file.get_line(input_file, input_buffer);
    --debug
    --dbms_output.put_line(input_buffer);
    utl_file.fclose(input_file);
    --return data
    return input_buffer;
    end;
    Hope this helps.

  • How can I read the bootstrap files and extract the fragment-URLs and fragment-numbers in plain text?

    How can I read the bootstrap files of any HDS Live stream and extract the fragment-URLs and fragment-numbers in plain text?
    Could it be that it is some kind of compressed format in the bootstrap? Can I uncompress it wirh  f4fpackager.exe? Could not find any download for f4fpackager.exe. I would prefere less code to do so. Is there something in Java of JavaScript, that can extract the fragment-numbers?
    Thank you!

    Doesn't sound too hard to me. Your class User (the convention says to capitalize class names) will have an ArrayList or Vector in it to represent the queue, and a method to store a Packet object into the List. An array or ArrayList or Vector will hold the 10 user objects. You will find the right user object from packet.user_id and call the method.
    Please try to write some code yourself. You won't learn anything from having someone else write it for you. Look at sample code using ArrayList and Vector, there's plenty out there. Post in the forum again if your code turns out not to behave.

  • How do I read a pdf file in Acrobat Reader (vs. Preview)?

    How do I read a pdf file in Acrobat Reader (vs. Preview)? I have a Mac OS, need to know the process to read a pdf file document in Acrobat Reader instead of Preview. Much thanks for suggestions.

    Right click the PDF. Choose "Open With..." Select Reader.
    Or.
    Right click and "Get Info"
    under "Opens with" change the default app to Reader, and click "Change all" to set the preference for ALL PDFs.

  • How can i read local excel file into internal table in webdynpro for abap a

    Could someone tell me how How can i read local excel file into an internal table in webdynpro for abap application.
    thank u for your reply

    Deep,
    File manuplations...............................
    1. At the presentation level:
    ->GUI_UPLOAD
    ->GUI_DOWNLOAD
    ->CL_GUI_FRONTEND
    2. At the application server level:
    ->OPEN DATASET : open a file in the application server for reading or writing.
    ->READ DATASET : used to read from a file on the application server that has been opened for reading
    -> TRANSFER DATASET : writing data to a file.
    -> CLOSE DATASET : closes the file
    -> DELETE DATASET : delete file
    If file is on the local PC,use the function module GUI_UPLOAD to upload it into an internal table by passing the given parameters......
    call function 'GUI_UPLOAD'
    exporting
    filename = p_file
    filetype = 'ASC'
    has_field_separator = '#'
    tables
    data_tab = t_data
    p_file : excel file path.
    t_data : internal table
    <b>reward points if useful.</b>
    regards,
    Vinod Samuel.

  • How do I Read a .js File from Mime Repository

    How can i read a .js file from Mime Repository,
    Mime Respository is for Re-Usability
    Since i need to call a function from a .js file again and again, i keep my .js file in Mime Repository so that i can call the function anywhere by calling the .js File.
    I have kept my .js File in a Mime Repository but when iam calling the function from Portal the function is not being Triggered, Can i know why it is behaving like that.

    Not required right now.Not resolved

Maybe you are looking for