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.

Similar Messages

  • How to get and read a file from META-INF directory

    how to get and read a file from META-INF directory in a EJB project

    Use this.getClass().getResourceAsStream("/META-INF/filename");This should work. Probably, you would need to set the Manifest Class-Path attribute.

  • 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

  • Cannot seem to read properties file from JSP

    Hi all,
    In an ISA 4.0 application I want to read a properties file from a JSP to decide whether or not to execute some specific JavaScript code. I want the properties file because in it I can easily configure this externally. I put my properties file in /WEB-INF/classes.
    I develop on an environment using Tomcat where this works fine. On an acceptance machine using the SAP J2EE engine however this won't work, to my surprise. Can anyone give me a suggestion on why my properties file is not read?
    Here's the Java scriptlet code:
    UserSessionData userSessionData = UserSessionData.getUserSessionData(session);
    // theme will be something like "themes/zester":
    String theme = (String) userSessionData.getAttribute(Constants.THEME_KEY);
    boolean showScript = false;
    int slashIndex = theme.indexOf('/');
    String themeKey = null;
    // get the "zester"-like part from the theme:
    if(theme != null && slashIndex > -1) {
      themeKey = theme.substring(slashIndex + 1);
    Properties props = new Properties();
    InputStream is = application.getResourceAsStream("/WEB-INF/classes/script.properties");
    if(is != null) {
      props.load(is);
      is.close();
      Enumeration keysEnum = scriptProps.propertyNames();
      while (themeKey != null && keysEnum.hasMoreElements()) {
       if(theme.toUpperCase().endsWith((String) keysEnum.nextElement())) {
        showScript = true;
        break;
       showScript = false;

    Hi Kishor,
    Thank you for taking the time!
    I agree, this issue may have to do with the deployment. There is however a remark in the <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html">ServletContext</a>  interface documentation on methods <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html#getResource(java.lang.String)">getResource()</a> and <a href="http://java.sun.com/products/servlet/2.3/javadoc/javax/servlet/ServletContext.html#getResourceAsStream(java.lang.String)">getResourceAsStream()</a> that may also be of interest here:
    "The servlet container must implement the URL handlers and URLConnection objects that are necessary to access the resource."
    Is this remark of relevance to the subject, or is this thought too far fetched? Mind you, the documentation also states that "This method allows the servlet container to make a resource available to servlets from any source. Resources can be located on a local or remote file system, in a database, or in a .war file". It should, therefore, be possible to read a file from disk???
    Cheers,
    Peter-Jan Bosch

  • Tomcat6 does not load class files from WEB-INF/lib/myjarfile.jar  WHY???

    I have placed my jar file in c:\tomcat6\webapps\my-application\WEB-INF\lib\myjarfile.jar
    But, after restarting tomcat6, when i try to import the class file contained in the myjarfile.jar in a servlet, it says
    ProcessFileUpload.java:4: package test.test1 does not exist
    import test.test1.*;
    ^It clearly tomcat's class loading problem.
    As i unzipped my jar and placed the packagefolder structure to
    c:\tomcat6\webapps\my-application\WEB-INF\classes\testand it works perfectly.
    Anyone knows its workaround? please suggest if any configuration changes is required in tomcat or so.
    Thanks.
    ---Sujoy

    Thank you gimbal2 . There was error in creating the jar file myjarfile.jar.
    But, now I have created it again and placed it in place
    c:\tomcat6\webapps\my-application\WEB-INF\lib\myjarfile.jarand tried to use one on the Class file included within the jar to compile my servlet. But, still I am getting error at servlet compilation time. I want to place executable jar files in
    c:\tomcat6\webapps\my-application\WEB-INF\lib\myjarfile.jar and compile my servlet and execute the servlet.
    I DO NOT WANT TO unzip the jar, placing all unzipped files to
    c:\tomcat6\webapps\my-application\WEB-INF\classes\ folder and comiple my servlet and execute the servlet. But, I am failing to user WEB-INF\lib\ folder facility....please help me why i am not getting class files from WEB-INF\lib\ folder.
    If you please see the small code bit and tell me any possible error that would be very helpful.
    Step 1: my library java file MyClass.java
    package test.test1;
    public class MyClass {
         String myName = "Default return string value";
         public void setMyName(String varName) {
              this.myName = varName;
         public String getMyName() {
              return this.myName;
    }Step2 : Creating jar file of my library class files
    C:\jdk1.6\bin>jar cvf myjarfile.jar test
    added manifest
    adding: test/(in = 0) (out= 0)(stored 0%)
    adding: test/test1/(in = 0) (out= 0)(stored 0%)
    adding: test/test1/MyClass.class(in = 452) (out= 296)(deflated 34%)
    adding: test/test1/MyClass.java(in = 230) (out= 140)(deflated 39%)
    C:\jdk1.6\bin>Step3 : Double checking the created jar file content by listing its content
    C:\jdk1.6\bin>jar tf myjarfile.jar
    META-INF/
    META-INF/MANIFEST.MF
    test/
    test/test1/
    test/test1/MyClass.class
    test/test1/MyClass.java
    C:\jdk1.6\bin>Step4 : Placed myjarfile.jar to
    c:\tomcat6\webapps\my-application\WEB-INF\lib\Step5 : Restarted standalone Tomcat6 in my Windows XP SP2.
    Step6 : Created a simple servlet LibFolderTest.java within my-application\WEB-INF\classes\ folder with code
    import java.io.*;
    import javax.servlet.*;
    import javax.servlet.http.*;
    import test.test1.*;
    public class LibFolderTest extends HttpServlet {
         public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              response.setContentType("text/html");
              PrintWriter out = response.getWriter();
              MyClass mc = new MyClass();
              out.println(mc.getMyName());
    }Step7 : Tried to compile my servlet LibFolderTest.java and got the following error
    LibFolderTest.java:4: package test.test1 does not exist
    import test.test1.*;
    ^
    LibFolderTest.java:11: cannot find symbol
    symbol  : class MyClass
    location: class LibFolderTest
                    MyClass mc = new MyClass();
                    ^
    LibFolderTest.java:11: cannot find symbol
    symbol  : class MyClass
    location: class LibFolderTest
                    MyClass mc = new MyClass();
                                     ^
    3 errorsThe above servlet compilation error on Step7 is telling me that myjarfile.jar is not loaded by Tomcat6 or not available for use when compiling servlet. I want to use myjarfile.jar from within WEB-INF\lib\ folder but I can not. please help.
    ---Sujoy

  • 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 can I read a file in WEB-INF?

    I have a file under WEB-INF/classes/properties that I want a webapp to be able to read. I'm doing
    BufferedReader in = new BufferedReader(new InputStreamReader(fin));But I don't know what to set "fin" to.

    ner0 wrote:
    I'm not using a servlet. I ended up just doing creating a Properties class and doing a load using ClassName.class.getResourceAsStream("/properties/"+filename) and creating key value pairs inside the property file read from the properties class. I had a suggestion against me doing this so I was trying to find another way, but since this works I'll just use it.That's exactly what evnafets second suggestion does.
    I mentioned the static error because I was wondering if there was a static way to do it since all this is being done within a synchronized static method.You should know that the 'this' reference is unknown in a static context, simply because there is no instance of the current object.

  • Applet can't read local file on web server, security issue!

    There is any way to read/write files of web server through the applet except the Signed Applet.
    If any idea the reply me soon.
    Thanks in advance

    Applets are downloaded from web servers and execute on the client machine.
    Therefore they have no access to the web server file system, signed or not.
    They could have access to the client file system (the machine where they run),
    but for security reasons only signed applets have this privilege.
    So to answer your question, you sign if you want to access client files.
    To access web server files, you don't need to sign the applet, but you need
    to provide some method of accessing files remotely, for instance:
    - Files published for the web can be read using HTTP
    - Files can be read or writen with the help of an FTP server on the same machine as the web server
    - A servlet running on the HTTP server can collaborate with your applet to exchange files

  • Unable to read Properties file from Java code

    Hi,
    The directory structure of my application is as follows:-
    My App
    ++++++ src
    ++++++++com
    ++++++++++readProp.java
    ++++++++resource
    ++++++++++message.properties
    I am trying to read the file as follows:-
    <code>
    public Static final string FilePath="resource.message.properties"
    Here the code to read the file. I tried using the following two techniques but to no use... :(
    File accountPropertiesFile = new File(FacesContext.getCurrentInstance()
    .getExternalContext().getRequestContextPath()
    + FilePath);
    properties.load(externalContext.getResourceAsStream(FilePath));
    </code>
    But none yeild any sucess while reading through the Bean class. please help...

    Your source code isn't there at run time, at least it shouldn't be, so the directory structure you've shown is irrelevant.
    If the file is in the corresponding position under WEB-INF/classes at runtime, the second technique should work, but you need to fix FilePath to agree with what it says under Class.getResource() and friends.

  • Read XML file in WEB-INF works in exploded format but fails in EAR

    I'm able to read an XML file stored in the WEB-INF when my application is deployed in the exploded format, but when its deployed in an EAR, the reading fails.
              I read from forums that getRealPath could fail, so I added in the getResourceAsStream to fall back on. But in the EAR format, both fails.
              What did I miss out?
              Here's my codes:
                          StringBuffer configFileName = new StringBuffer();
                configFileName.append(File.separatorChar).append("WEB-INF");
                configFileName.append(File.separatorChar).append("app-config.xml");
                String fileName = getServletContext().getRealPath(configFileName.toString());
                if (fileName == null) {
                  request.setAttribute("efs/xmlmappings-is", getServletContext().getResourceAsStream(configFileName.toString()));
                } else {
                  request.setAttribute("efs/xmlmappings-str", fileName);
              

    Hi          > Thread.currentThread().getContextClassLoader().getReso
              > urceAsStream()
              >
              > getClass().getClassLoader().getResourceAsStream()
              > should also work
              > if the file is in WEB-INF/classes
              >
              > regards
              > deepak
              It works, thanks!

  • Read xml file from jsp/servlet

    Hi all,
    I am a new comer to jsp and really appreciate if someone can help me on this:
    I will like to use a xml file to control access to my web app instead of using a database. Let say user.xml that will contains user name and password. Questions:
    1. where should I put this file? Under WEB-INF?
    2. In my jsp or servlet, how do i read the xml file, i mean how to i refer to the file (depend on question 1 as where the file should be placed)?
    Thank you very much.
    Sim

    Hi jlsim,
    you can place the xml file where you want, but remember that placing it under /WEB-INF is the most security way.
    I had a similar problem and I placed the xml file under /WEB-INF directory.
    To refer to it I did something like this:
    String realPath=getServletContext().getRealPath("WEB-INF/xml/workspaces.xml");//obtain the real path
    File f=new File(realPath);//obtain an instance of your file usable
    //to create an InputStream

  • ADF Faces - access to content in WEB-INF directory

    Hello,
    I create simple JSF application that use ADF Faces and deploy it to Oracle iAS. But why can i also access files in WEB-INF directory? For example, the following URL - http://myserver.si/MyApp/faces/WEB-INF/web.xml - will return the content of XML file. By my knowledge of J2EE architecture, access to this directory should be forbidden.
    Should I set some parameter on javax.faces.webapp.FacesServlet servlet filter to prevent access to WEB-INF directory? Thank you for help.
    Google also found the following links:
    - http://mail-archives.apache.org/mod_mbox/myfaces-dev/200602.mbox/%[email protected]%3E
    - http://svn.apache.org/viewcvs.cgi//myfaces/core/trunk/api/src/main/java/javax/faces/webapp/FacesServlet.java/?rev=375489&view=diff&r1=375489&r2=375488&p1=/myfaces/core/trunk/api/src/main/java/javax/faces/webapp/FacesServlet.java&p2=/myfaces/core/trunk/api/src/main/java/javax/faces/webapp/FacesServlet.java
    Regards,
    Matic

    Hi,
    the reason for this is that the WEB-INF directory is protected against direct client (browser) requests. Using Faces, the JSF servlet performs this access as a server side forward request in which case there is no container-managed protection.
    If you want to avoid this then you can write a servlet filter in fron of JSF in which you check for any occurences of directories you want to prohibit access to.
    Its not a bug, its the way J2EE is designed ;-(
    Frank

  • How can I reference a dtd in the Web-Inf directory from an xml file?

    Hi,
    I've placed my test.xml and test.dtd files in the following
    direcory (part of my web application)
    weblogic\config\MyDomain\applications\sample\Web-inf
    When I refer to the dtd from the xml file, as follows,
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE application SYSTEM "test.dtd">
    Weblogic tries to look for the dtd in the weblogic directory(the
    place where I started the server from). How can I get it to read
    the dtd in the Web-inf directory?
    I'm using Weblogic6.0 SP1 on Windows NT 4.0
    Thanks.

    Two options:
    1) Use SYSTEM "http://localhost:7001/sample/test.dtd"
    2) Or use XML registry in WLS6.0
    Cheers - Wei
    "Paromita" <[email protected]> wrote in message
    news:3aaff997$[email protected]..
    >
    Hi,
    I've placed my test.xml and test.dtd files in the following
    direcory (part of my web application)
    weblogic\config\MyDomain\applications\sample\Web-inf
    When I refer to the dtd from the xml file, as follows,
    <?xml version="1.0" encoding="ISO-8859-1" ?>
    <!DOCTYPE application SYSTEM "test.dtd">
    Weblogic tries to look for the dtd in the weblogic directory(the
    place where I started the server from). How can I get it to read
    the dtd in the Web-inf directory?
    I'm using Weblogic6.0 SP1 on Windows NT 4.0
    Thanks.

  • Find path to Web-inf directory from root

    Hi All,
    I have a application for which the "config.txt" file is placed in "Web-inf" directory. I want to get the complete path to this file so that I can access it and read config info.
    I am able to acheive this if I write the following piece of code and it gives me the complete path.
    String configPath = getServletContext().getRealPath("config.txt");
    My problem is that this code works only if the class extends from HttpServlet. I want to get the complete path to this file from a normal java bean, where I don't have the servlet context.
    If there is any alternative way to achieve this or if somehow I can get the servlet context in the java bean then please let me know. We use iPlanet 6.0 server.
    Thanks for your help.
    RM

    Thanks for your reply. Do you mean, I should use
    getResourceasStream() method which return inputstream.
    But even that would require servletcontext object ?No it doesn't require the servlet context; if it did, you'd still be able to get the servlet context from the servlet itself.
    Maybe I have not understood, your approach. Can you
    please give me some example.
    class SomeServlet extends HttpServlet {
        // servlet stuff
        private void handleConfiguration() {
            InputStream configStream = getClass().getResourceAsStream("config.txt"); // may return null
            YourBean bean = getYourBeanInstance();
            bean.someMethod(configStream);
            // close configStream
    public class YourBean {
        public void someMethod(InputStream configStream) {
            // handle configStream
    }

  • Classes are not loading from WEB-INF/classes directory

    Hi All,
    I am in a deep troble because the class files in the WEB-INF/classes directory are not loading.
    I have deployed the application in Tomcat 6 server. And stored all class files under WEB-INF/classes dirctory. But when I execute a JSP page, I am getting following error:
    HTTP Status 500 -
    type Exception report
    message
    description The server encountered an internal error () that prevented it from fulfilling this request.
    exception
    org.apache.jasper.JasperException: Unable to compile class for JSP:
    JSP FileName:/hello.jsp
    An error occurred at line: 1 in the jsp file: /hello.jsp
    com.flt.Test cannot be resolved to a type
    1: <%=new com.flt.Test().hello()%>
    Stacktrace:
         org.apache.jasper.compiler.DefaultErrorHandler.javacError(DefaultErrorHandler.java:98)
         org.apache.jasper.compiler.ErrorDispatcher.javacError(ErrorDispatcher.java:330)
         org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:435)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:298)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:277)
         org.apache.jasper.compiler.Compiler.compile(Compiler.java:265)
         org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:564)
         org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:302)
         org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:329)
         org.apache.jasper.servlet.JspServlet.service(JspServlet.java:265)
         javax.servlet.http.HttpServlet.service(HttpServlet.java:803)The classes are available in the WEB-INF/classes directory and the folder name and package name of the classes are correct. I have also tried to execute the application by creating a jar file and put it in the WEB-INF/lib directory. But I am getting same result.
    Is it the problem with Tomcat configuration? When I gone through Tomcat documentation, I get to know that the WebAppX class loader in Tomcat, loads application specific classes for a web application. Is it possible to start/stop WebAppx classloader manually?
    Please help me to solve this issue.
    Many Thanks,
    Francis Lukose
    Edited by: francis_ on May 13, 2008 10:03 AM

    Thanks for your reply, Soultech2012.
    <%=new com.flt.Test().hello()%>is the only code in the JSP page. Just a single line. Nothing more than that.
    The code in Test.java is as follows:
    * To change this template, choose Tools | Templates
    * and open the template in the editor.
    package com.flt;
    * @author Francis Lukose
    public class Test {
        public static String hello()    {
            return "hello";
    }Many Thanks,
    Francis
    Edited by: francis_ on May 13, 2008 6:45 PM

Maybe you are looking for