Friday, December 28, 2012

Configuring Jetty, Maven, and Eclipse together


Environment Information:
JDK 1.5+
Eclipse 3.4.0
maven 2.0.10
m2eclipse 0.9.7 (maven plugin for eclipse)
Jetty 6.1.10
Spring
JPA,Hibernate
Maven Jetty Configuration:
In your maven project's pomx.xml, in your <build> section, add the jetty plugin.  An example can be found at the Jetty website here:
It is very important to keep <scanIntervalSeconds> set to zero.  This setting tells Jetty how often (in seconds) to scan the webapp for changes and if changes are found, it re-cycles the web container.  You don't want to do this and setting it to zero will disable it.
Configuring Jetty to start within Eclipse:
Next, create an easy way to launch your jetty server.  I'm using Jetty through Maven and Eclipse.  Here is how I setup an Eclipse External Tool to launch my Jetty server:
To make sure it is listening for a debugger, make sure that a MAVEN_OPTS environment variable is set with the following options:
-Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=n
The address parameter is what port the jetty server will be listening on for the remote debugger.
Click 'Run' and your jetty server should start running in Eclipse's console window.  It should look something like this (depending on your log4j config):
Listening for transport dt_socket at address: 4000
  [INFO] Scanning for projects...  [INFO] Searching repository for plugin with prefix: 'jetty'.  [INFO] ------------------------------------------------------------------------  [INFO] Building myProject  [INFO]    task-segment: [jetty:run]  [INFO] ------------------------------------------------------------------------  [INFO] Preparing jetty:run  2010-05-27 15:39:25.733::INFO:  Started SelectChannelConnector@0.0.0.0:8080  [INFO] Started Jetty Server
Attaching the Debugger:
Next, setup a debugger.  In Eclipse open 'Debug Configurations', and create a new 'Remote Java Debugger'.   Select your eclipse project, set the host to localhost, and set the port to 4000, or whatever you defined earlier.
Press the Debug Button and the remote debugger should attach to your jetty server.
Finally, make sure Build Automatically is enabled in eclipse (Project->Build Automatically).
At this point your environment is enabled for debugging code on your Jetty server through Eclipse.  Breakpoints, watch variables, you name it.
Hot deploy is also enabled.  If you modify some java code, the automatic builder should compile the .java file to a .class file.  The remote debugger will see it and use it, all without restarting your jetty server or its web container.  This will not work for things like adding static variables, new domain classes, or new injectable service methods that require the application to acknowledge them on startup.

Configuring Jetty, Maven, and Eclipse together


 external tool:
Dirigirse a External Tools Configuration y crear una nueva configuración, especificando la ruta hacia la instalación de maven local, el working directory y como arguments jetty:run.
Luego dirigirse a la pestaña Environment, y agregar la variable MAVEN_OPTS y asignarle el valor: -Xdebug -Xnoagent -Djava.compiler=NONE -Xrunjdwp:transport=dt_socket,address=4000,server=y,suspend=y
Luego se debe crear un Debug Configuration:
Para crear esta configuración de Debug se debe ir a Debug Configurations, especificar el proyecto que se depurará y el mismo puerto que se estableció en la variable de entorno MAVEN_OPTS
Después de esto se deberán ejecutar los dos de forma consecutiva (uno depende el otro).
Primero se ejecutará la configuración de External Tools, con lo cual en la consola se podrá ver un mensaje como el siguiente en la consola.
Y solo después de ejecutar el Debug Configuration la aplicación comenzará a correr, y estaremos listos para hacer el debugging.

Sunday, December 23, 2012

ORA-28002: the password will expire within 7 days


Cause: The user's account is about to about to expire and the password needs 
to be changed.
Action: Change the password or contact the database administrator.

Reference: Oracle Documentation 

Solutions:

1) Simply change the password to avoid it temporary

  [oracle@lnxsvr ~]$ sqlplus scott/tiger

  SQL*Plus: Release 11.2.0.1.0 Production on Wed Jun 20 14:08:01 2012

  Copyright (c) 1982, 2009, Oracle.  All rights reserved.

  ERROR:
  ORA-28002: the password will expire within 7 days

  Connected to:
  Oracle Database 11g Release 11.2.0.1.0 - 64bit Production

  SQL> PASSWORD
  Changing password for SCOTT
  Old password:
  New password:
  Retype new password:
  Password changed


2) Set PASSWORD_LIFE_TIME of the profile assigned user to UNLIMITED 
   then change the password to avoid it permanently
   
  [oracle@lnxsvr ~]$ sqlplus scott/tiger

  SQL*Plus: Release 11.2.0.1.0 Production on Wed Jun 20 14:08:01 2012

  Copyright (c) 1982, 2009, Oracle.  All rights reserved.

  ERROR:
  ORA-28002: the password will expire within 7 days

  Connected to:
  Oracle Database 11g Release 11.2.0.1.0 - 64bit Production   

  SQL> SELECT PROFILE FROM dba_users WHERE username = 'SCOTT';

  PROFILE
  ------------------------------
  DEFAULT

  SQL> SELECT  LIMIT FROM DBA_PROFILES WHERE PROFILE='DEFAULT' 
  AND RESOURCE_NAME='PASSWORD_LIFE_TIME';

  LIMIT
  ----------------------------------------
  60

  SQL> ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;

  Profile altered.

  SQL> SELECT ACCOUNT_STATUS FROM DBA_USERS WHERE USERNAME='SCOTT';

  ACCOUNT_STATUS
  --------------------------------
  EXPIRED(GRACE)

  SQL> PASSWORD
  Changing password for SCOTT
  Old password:
  New password:
  Retype new password:
  Password changed


ORA-28002: the password will expire within 7 days

ORA-28002: the password will expire within 7 days  Cause: The user's account is about to about to expire and the password needs   to be changed.  Action: Change the password or contact the database administrator.    Reference: Oracle Documentation     Solutions:    1) Simply change the password to avoid it temporary      [oracle@lnxsvr ~]$ sqlplus scott/tiger      SQL*Plus: Release 11.2.0.1.0 Production on Wed Jun 20 14:08:01 2012      Copyright (c) 1982, 2009, Oracle.  All rights reserved.      ERROR:    ORA-28002: the password will expire within 7 days      Connected to:    Oracle Database 11g Release 11.2.0.1.0 - 64bit Production      SQL> PASSWORD    Changing password for SCOTT    Old password:    New password:    Retype new password:    Password changed      2) Set PASSWORD_LIFE_TIME of the profile assigned user to UNLIMITED      then change the password to avoid it permanently         [oracle@lnxsvr ~]$ sqlplus scott/tiger      SQL*Plus: Release 11.2.0.1.0 Production on Wed Jun 20 14:08:01 2012      Copyright (c) 1982, 2009, Oracle.  All rights reserved.      ERROR:    ORA-28002: the password will expire within 7 days      Connected to:    Oracle Database 11g Release 11.2.0.1.0 - 64bit Production         SQL> SELECT PROFILE FROM dba_users WHERE username = 'SCOTT';      PROFILE    ------------------------------    DEFAULT      SQL> SELECT  LIMIT FROM DBA_PROFILES WHERE PROFILE='DEFAULT'     AND RESOURCE_NAME='PASSWORD_LIFE_TIME';      LIMIT    ----------------------------------------    60      SQL> ALTER PROFILE DEFAULT LIMIT PASSWORD_LIFE_TIME UNLIMITED;      Profile altered.      SQL> SELECT ACCOUNT_STATUS FROM DBA_USERS WHERE USERNAME='SCOTT';      ACCOUNT_STATUS    --------------------------------    EXPIRED(GRACE)      SQL> PASSWORD    Changing password for SCOTT    Old password:    New password:    Retype new password:    Password changed


Wednesday, December 12, 2012

MAVEN Setup


Windows 2000/XP

  1. Unzip the distribution archive, i.e. apache-maven-3.0.4-bin.zip to the directory you wish to install Maven 3.0.4. These instructions assume you chose C:\Program Files\Apache Software Foundation. The subdirectory apache-maven-3.0.4 will be created from the archive.
  2. Add the M2_HOME environment variable by opening up the system properties (WinKey + Pause), selecting the "Advanced" tab, and the "Environment Variables" button, then adding the M2_HOME variable in the user variables with the value C:\Program Files\Apache Software Foundation\apache-maven-3.0.4. Be sure to omit any quotation marks around the path even if it contains spaces. Note: For Maven < 2.0.9, also be sure that the M2_HOME doesn't have a '\' as last character.
  3. In the same dialog, add the M2 environment variable in the user variables with the value %M2_HOME%\bin.
  4. Optional: In the same dialog, add the MAVEN_OPTS environment variable in the user variables to specify JVM properties, e.g. the value -Xms256m -Xmx512m. This environment variable can be used to supply extra options to Maven.
  5. In the same dialog, update/create the Path environment variable in the user variables and prepend the value %M2% to add Maven available in the command line.
  6. In the same dialog, make sure that JAVA_HOME exists in your user variables or in the system variables and it is set to the location of your JDK, e.g. C:\Program Files\Java\jdk1.5.0_02 and that %JAVA_HOME%\bin is in your Path environment variable.
  7. Open a new command prompt (Winkey + R then type cmd) and run mvn --version to verify that it is correctly installed.

Unix-based Operating Systems (Linux, Solaris and Mac OS X)

  1. Extract the distribution archive, i.e. apache-maven-3.0.4-bin.tar.gz to the directory you wish to install Maven 3.0.4. These instructions assume you chose/usr/local/apache-maven. The subdirectory apache-maven-3.0.4 will be created from the archive.
  2. In a command terminal, add the M2_HOME environment variable, e.g. export M2_HOME=/usr/local/apache-maven/apache-maven-3.0.4.
  3. Add the M2 environment variable, e.g. export M2=$M2_HOME/bin.
  4. Optional: Add the MAVEN_OPTS environment variable to specify JVM properties, e.g. export MAVEN_OPTS="-Xms256m -Xmx512m". This environment variable can be used to supply extra options to Maven.
  5. Add M2 environment variable to your path, e.g. export PATH=$M2:$PATH.
  6. Make sure that JAVA_HOME is set to the location of your JDK, e.g. export JAVA_HOME=/usr/java/jdk1.5.0_02 and that $JAVA_HOME/bin is in your PATH environment variable.
  7. Run mvn --version to verify that it is correctly installed.

Optional configuration

Maven will work for most tasks with the above configuration, however if you have any environmental specific configuration outside of individual projects then you will need to configure settings. The following sections refer to what is available.



Monday, July 16, 2012

doGet() and doPost()


DoGet

DoPost

In doGet Method the parameters are appended to the URL and sent along with header information

In doPost, parameters are sent in separate line in the body

Maximum size of data that can be sent using doget is 240 bytes

There is no maximum size for data

Parameters are not encrypted

Parameters are encrypted

DoGet method generally is used to query or to get some information from the server

Dopost is generally used to update or post some information to the server

DoGet is faster if we set the response content length since the same connection is used. Thus increasing the performance

DoPost is slower compared to doGet since doPost does not write the content length

DoGet should be idempotent. i.e. doget should be able to be repeated safely many times

This method does not need to be idempotent. Operations requested through POST can have side effects for which the user can be held accountable, for example, updating stored data or buying items online.

DoGet should be safe without any side effects for which user is held responsible

This method does not need to be either s

Wednesday, July 11, 2012

Database Connection Pooling in Tomcat


Database Connection Pooling in Tomcat 


tomcat-connection-poolingDatabase Connection Pooling is a great technique used by lot of application servers to optimize the performance. Database Connection creation is a costly task thus it impacts the performance of application. Hence lot of application server creates a database connection pool which are pre initiated db connections that can be leverage to increase performance.

Apache Tomcat also provide a way of creating DB Connection Pool. Let us see an example to implement DB Connection Pooling in Apache Tomcat server. We will create a sample web application with a servlet that will get the db connection from tomcat db connection pool and fetch the data using a query. We will use Eclipse as our development environment. This is not a prerequisite i.e. you may want to use any IDE to create this example.

Step 1: Create Dynamic Web Project in Eclipse

Create a Dynamic Web Project in Eclipse by selecting:
File -> New -> Project… ->Dynamic Web Project.
dynamic-project-eclipse

Step 2: Create context.xml

Apache Tomcat allow the applications to define the resource used by the web application in a file called context.xml (from Tomcat 5.x version onwards). We will create a file context.xml under META-INFdirectory.
db-connection-pooling-eclipse
Copy following content in the context.xml file.

    <?xml version="1.0" encoding="UTF-8"?>  <Context>  	<!-- Specify a JDBC datasource -->  	<Resource name="jdbc/testdb" auth="Container"  		type="javax.sql.DataSource" username="DB_USERNAME" password="DB_PASSWORD"  		driverClassName="oracle.jdbc.driver.OracleDriver"  		url="jdbc:oracle:thin:@xxx:1525:dbname"  		maxActive="10" maxIdle="4" />    </Context>  

In above code snippet, we have specify a database connection pool. The name of the resource isjdbc/testdb. We will use this name in our application to get the data connection. Also we specify db username and password and connection URL of database. Note that I am using Oracle as the database for this example. You may want to change this Driver class with any of other DB Providers (like MySQL Driver Class).

Step 3: Create Test Servlet and WEB xml entry

Create a file called TestServlet.java. I have created this file under package: net.viralpatel.servlet. Copy following code into it.

package net.viralpatel.servlet;    import java.io.IOException;  import java.sql.Connection;  import java.sql.ResultSet;  import java.sql.SQLException;  import java.sql.Statement;    import javax.naming.Context;  import javax.naming.InitialContext;  import javax.naming.NamingException;  import javax.servlet.ServletException;  import javax.servlet.http.HttpServlet;  import javax.servlet.http.HttpServletRequest;  import javax.servlet.http.HttpServletResponse;  import javax.sql.DataSource;    public class TestServlet extends HttpServlet {  	  	private DataSource dataSource;  	private Connection connection;  	private Statement statement;  	  	public void init() throws ServletException {  		try {  			// Get DataSource  			Context initContext  = new InitialContext();  			Context envContext  = (Context)initContext.lookup("java:/comp/env");  			dataSource = (DataSource)envContext.lookup("jdbc/testdb");    			  		} catch (NamingException e) {  			e.printStackTrace();  		}  	}    	public void doGet(HttpServletRequest req, HttpServletResponse resp)  			throws ServletException, IOException {  		  		ResultSet resultSet = null;  		try {  			// Get Connection and Statement  			connection = dataSource.getConnection();  			statement = connection.createStatement();  			String query = "SELECT * FROM STUDENT";  			resultSet = statement.executeQuery(query);  			while (resultSet.next()) {  				System.out.println(resultSet.getString(1) + resultSet.getString(2) + resultSet.getString(3));  			}  		} catch (SQLException e) {  			e.printStackTrace();  		}finally {  			try { if(null!=resultSet)resultSet.close();} catch (SQLException e)   			{e.printStackTrace();}  			try { if(null!=statement)statement.close();} catch (SQLException e)   			{e.printStackTrace();}  			try { if(null!=connection)connection.close();} catch (SQLException e)   			{e.printStackTrace();}  		}  	}  }  

In the above code we initiated the datasource using InitialContext lookup:

    Context initContext  = new InitialContext();  Context envContext  = (Context)initContext.lookup("java:/comp/env");  dataSource = (DataSource)envContext.lookup("jdbc/testdb");  

Create test servlet mapping in the web.xml file (deployment descriptor) of the web application. The web.xml file will look like:

<?xml version="1.0" encoding="UTF-8"?>  <web-app id="WebApp_ID" version="2.4"  	xmlns="http://java.sun.com/xml/ns/j2ee"  	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"  	xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">  	<display-name>TomcatConnectionPooling</display-name>  	<welcome-file-list>  		<welcome-file>index.jsp</welcome-file>  	</welcome-file-list>    	<servlet>  		<servlet-name>TestServlet</servlet-name>  		<servlet-class>  			net.viralpatel.servlet.TestServlet  		</servlet-class>  	</servlet>  	<servlet-mapping>  		<servlet-name>TestServlet</servlet-name>  		<url-pattern>/servlet/test</url-pattern>  	</servlet-mapping>  </web-app>  

Now Run the web application in Tomcat using Eclipse (Alt + Shift + X, R). You will be able to see the result of the query executed.
db-connection-run-project-eclipse
Thus this way we can create a database pool in Tomcat and get the connections from it.


Sunday, July 1, 2012

Struts 1 Vs Struts 2



Feature Struts 1Struts 2
Action classesStruts 1 requires Action classes to extend an abstract base class. A common problem in Struts 1 is programming to abstract classes instead of interfaces. An Struts 2 Action may implement an Action interface, along with other interfaces to enable optional and custom services. Struts 2 provides a base ActionSupport class to implement commonly used interfaces. Albeit, the Action interface is not required. Any POJO object with a execute signature can be used as an Struts 2 Action object.
Threading Model Struts 1 Actions are singletons and must be thread-safe since there will only be one instance of a class to handle all requests for that Action. The singleton strategy places restrictions on what can be done with Struts 1 Actions and requires extra care to develop. Action resources must be thread-safe or synchronized. Struts 2 Action objects are instantiated for each request, so there are no thread-safety issues. (In practice, servlet containers generate many throw-away objects per request, and one more object does not impose a performance penalty or impact garbage collection.)
Servlet Dependency Struts 1 Actions have dependencies on the servlet API since the HttpServletRequest and HttpServletResponse is passed to the execute method when an Action is invoked. Struts 2 Actions are not coupled to a container. Most often the servlet contexts are represented as simple Maps, allowing Actions to be tested in isolation. Struts 2 Actions can still access the original request and response, if required. However, other architectural elements reduce or eliminate the need to access the HttpServetRequest or HttpServletResponse directly.
Testability A major hurdle to testing Struts 1 Actions is that the execute method exposes the Servlet API. A third-party extension, Struts TestCase, offers a set of mock object for Struts 1. Struts 2 Actions can be tested by instantiating the Action, setting properties, and invoking methods. Dependency Injection support also makes testing simpler.
Harvesting InputStruts 1 uses an ActionForm object to capture input. Like Actions, all ActionForms must extend a base class. Since  other JavaBeans cannot be used as ActionForms, developers often create redundant classes to capture input. DynaBeans can used as an alternative to creating conventional ActionForm classes, but, here too, developers may be redescribing existing JavaBeans. 
Struts 2 uses Action properties as input properties, eliminating the need for a second input object. Input properties may be rich object types which may have their own properties. The Action properties can be accessed from the web page via the taglibs. Struts 2 also supports the ActionForm pattern, as well as POJO form objects and POJO Actions. Rich object types, including business or domain objects, can be used as input/output objects. The ModelDriven feature simplifies taglb references to POJO input objects. 
Expression Language Struts 1 integrates with JSTL, so it uses the JSTL EL. The EL has basic object graph traversal, but relatively weak collection and indexed property support. Struts 2 can use JSTL, but the framework also supports a more powerful and flexible expression language called "Object Graph Notation Language" (OGNL).
Binding values into viewsStruts 1 uses the standard JSP mechanism for binding objects into the page context for access. Struts 2 uses a "ValueStack" technology so that the taglibs can access values without coupling your view to the object type it is rendering. The ValueStack strategy allows reuse of views across a range of types which may have the same property name but different property types. 
Type Conversion Struts 1 ActionForm properties are usually all Strings. Struts 1 uses Commons-Beanutils for type conversion. Converters are per-class, and not configurable per instance. Struts 2 uses OGNL for type conversion. The framework includes converters for basic and common object types and primitives.
ValidationStruts 1 supports manual validation via a validate method on the ActionForm, or through an extension to the Commons Validator. Classes can have different validation contexts for the same class, but cannot chain to validations on sub-objects. Struts 2 supports manual validation via the validate method and the XWork Validation framework. The Xwork Validation Framework supports chaining validation into sub-properties using the validations defined for the properties class type and the validation context.
Control Of Action Execution Struts 1 supports separate Request Processors (lifecycles) for each module, but all the Actions in the module must share the same lifecycle. Struts 2 supports creating different lifecycles on a per Action basis via Interceptor Stacks. Custom stacks can be created and used with different Actions, as needed.

Saturday, May 26, 2012

Log4j for Java Web Applications



There are different ways to setup log4j for you web application. Here I will present 2 of ways to setup log4j, particularly aimed at simple java web applications (eg. plain servlets/jsp webapps).

First you can download the following basic log4j.properties file. Just replace <appname> with your application name (eg. FunkyWebApp).

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

log4j.logger.<appname>logger=DEBUG, C, fileappender

 

log4j.additivity.<appname>logger=false

log4j.appender.C=org.apache.log4j.ConsoleAppender

log4j.appender.C.layout=org.apache.log4j.PatternLayout

#basic pattern

log4j.appender.C.layout.ConversionPattern=[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m %n

#advanced pattern (slow)

#log4j.appender.C.layout.ConversionPattern=[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m - in %M() at line %L of class %C %n

 

log4j.appender.fileappender=org.apache.log4j.RollingFileAppender

log4j.appender.fileappender.File=${appRootPath}WEB-INF/logs/<appname>.log

log4j.appender.fileappender.MaxFileSize=500KB

 

## Keep one backup file

log4j.appender.fileappender.MaxBackupIndex=3

log4j.appender.fileappender.layout=org.apache.log4j.PatternLayout

log4j.appender.fileappender.layout.ConversionPattern=%p %t %c - %m%n

#log4j.appender.C.layout.ConversionPattern=[%c] [%d{dd MMM yyyy - hh:mm:ss}] %5p - %m %n

Now use one of the methods below to add and enable Log4J in your web application

Method 1: Use Servlet to initialize log4j

Step 1: Put log4j.properties file in the right place

  • Place 'log4j.properties' into the root of your classpath. See an example web application layout here

Tip: when web application is deployed it should be in /WEB-INF/classes/log4j.properties.

  • If using eclipse place 'log4j.properties' under your project_name/src directory

Step 2: Define the servlet mapping in web.xml

Add the following code to WEB-INF/web.xml

 

 

 

 

 

 

 

 

<servlet>

     <servlet-name>log4j-init</servlet-name>

     <servlet-class>com.FunkyWebapp.servlets.Log4jInit</servlet-class>

     <init-param>

       <param-name>log4j-init-file</param-name>

       <param-value>WEB-INF/classes/log4j.properties</param-value>

     </init-param>

     <load-on-startup>1</load-on-startup>

</servlet>

Make sure to change the java class file path to be relevant to your project. 'com.FunkyWebapp.servlets.Log4jInit'

Step 3: Add the servlet you mapped in Step 2 to your application

Add the following servlet to your project

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

import javax.servlet.http.HttpServlet;

import org.apache.log4j.PropertyConfigurator;

 

public class Log4jInit extends HttpServlet {

 

 public void init()

 {

     String prefix =  getServletContext().getRealPath("/");

     String file = getInitParameter("log4j-init-file");

  

     // if the log4j-init-file context parameter is not set, then no point in trying

     if(file != null){

      PropertyConfigurator.configure(prefix+file);

      System.out.println("Log4J Logging started: " + prefix+file);

     }

     else{

      System.out.println("Log4J Is not configured for your Application: " + prefix + file);

     }    

 }

}

Make sure the <servlet-class> element in Step 2 matches the fully qualified name of your servlet. And make sure it's in the right package.

Step 4: Initialize the logger and start logging from other servlets in your web application

 

 

 

 

 

 

 

 

 

public class MyServlet extends HttpServlet {

...

private Logger log = Logger.getLogger("<appname>logger");

.

.

.

log.debug("Some string to print out");

 

}

Make sure the <appname> part matches with the line

log4j.logger.<appname>logger in the log4j.properties file

Notes:
When you initialize log4j in a servlet you will only be able to log from classes which are loaded after the servlet (eg. other servlets). You won't be able to do logging from a ServletContextListener for example.

Method 2: Initialize log4j in a ServletContextListener

Step 1: Put properties file in the right place

  • Place 'log4j.properties' into the root of your classpath. See an example web application layout here

Tip: when web application is deployed it should be in /WEB-INF/classes/log4j.properties.

  • If using eclipse place 'log4j.properties' under your project_name/src directory

Step 2: Define a listener mapping in web.xml

Add the following servlet listener mapping in web.xml:

 

 

 

 

 

<listener>

  <listener-class>

   com.package.listeners.ApplicationServletContextListener

  </listener-class>

</listener>

Step 3: Add the SerlvetContextListener class to the application

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

public class ApplicationServletContextListener implements ServletContextListener

{

 public void contextInitialized(ServletContextEvent event)

 {

     ServletContext ctx = e.getServletContext();

    

  String prefix =  ctx.getRealPath("/");    

  String file = "WEB-INF"+System.getProperty("file.separator")+"classes"+System.getProperty("file.separator")+"log4j.properties";

           

     if(file != null) {

       PropertyConfigurator.configure(prefix+file);

       System.out.println("Log4J Logging started for application: " + prefix+file);

     }

     else

     {

      System.out.println("Log4J Is not configured for application Application: " + prefix+file);

     }

        

      

 }

 

 public void contextDestroyed(ServletContextEvent event)

 {

   

 }

 

}

Step 4: Define the logger and start logging from other servlets in your applications

 

 

public class MyServlet extends HttpServlet {

...

private Logger log = Logger.getLogger("<appname>logger");

.

.

.

log.debug("Some string to print out");

 

}

Notes:

  • Easier to implement that Method 1
  • All web application now has access to log4j (including listeners)
  • Placing log4j initialization in a ServletContextListener allows initialization of log4j when your web application is loaded for the first time.