Simple Chat Application Using Applet




1. Client.java
package chatterapi;
/*
 @navindra k. jha
 */

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
import java.io.*;

public class Client extends Applet implements ActionListener, Runnable
{

        Image Icon = Toolkit.getDefaultToolkit().getImage("D:/Example/emperian/jsf/ChatterAPI/src/chatterapi/hi.gif") ;

Hit Counter for a Web site, time of hitting and no. of current users



Many times you would be interested in knowing total number of hits of your site, time of hitting, and number of users currently using your site.

This post is about creating a hit counter that counts number of site visit. There are various ways for creating hit counter in servlet but here we have implemented hit counter using ServletContextListener. ServletContextListener is a listener interface that gets notified when the context is initialized and destroyed.

index.html
<body>
        <form name="loginForm" method="get" action="LoginServlet">
            Username<input type="text" name="txtname" size="20"><br>
            Password<input type="password" name="txtpass" size="20"><br>
            <input type="submit" value="Login">
        </form>
    </body>

How to export data from database to excel sheet




It is very simple to import data from database to Excel, follow below steps

I have “student” table in “stu” database and book1.xlsx excel file in x drive.
Student table has three field name, roll, and marks

Before importing data you must have an Excel file in which data is imported and specify field name in cell like NAME, ROLL, and MARKS in different cells.

NAME
ROLL
MARKS







I am using MySql database.

Abstraction and Encapsulation



In an object-oriented programming language Encapsulation and Abstraction are very confusing words, everyone feels confused to understand.
Here I give in my own style of explanation.
Abstraction:
 The essential characteristics of an entity that distinguishes it from all other kinds of entities.

In other word,

“Only the characteristics of the system that are essential to the problem being studied are modelled; minor or irrelevant details are ignored.”

 It defines a boundary relative to the perspective of the viewer. It allows us to manage complexity by concentrating on the essential characteristics of an entity.

ARE YOU KNOW ANSWER OF THIS QUESTION?


1. How to get last inserted id in hibernate?
2. How to insert date in database?
3. You can override static method in java?
4. Which one is better struts2 or spring?
5. How many ways to create object in java?
6. Why java use both compiler and interpreter?
7. Why and where uses throw keyword?
8. When stack over follow error is occurred?
9. Difference between heap and stack memory, why not everything store in heap?
10. Difference between abstract factory and factory design pattern?

ANSWER:

DatabaseMetaData



The simple meaning of metadata is data about data. There are two metadata available in the JDBC API - ResultSetMetaData and DatabaseMetaData.

This interface provides method to find out information about the database product being used, Driver Information, Operation Supported by Database, Details of Table, Procedures, Sequence etc.

getMetaData() method of Connection interface is used to obtained the reference of database metadata object.

Commonly used methods:

ResultSetMetaData



The simple meaning of metadata is data about data. There are two metadata available in the JDBC API - ResultSetMetaData and DatabaseMetaData.

This interface provide method to find out information such as number of columns return in the result set , name and types of column their source table etc.

getMetaData() method of ResultSet Interface is used to obtained the reference of ResultSetMetaData.
public  ResultSetMetaData getMetaData();


Reflection API


Reflection API provide the facility find out the details of a class at execution time as well as facility to load a class, to create an instance of a class to invoke a constructor or method on a class object to get and set value of a field etc.
java.lang.reflect package provide classes of reflection API. Commonly use class of Reflection API
Method:
A Method provides information about, and access to, a single method on a class or interface. The reflected method may be a class method or an instance method (including an abstract method).
Field:
A Field provides information about, and dynamic access to, a single field of a class or an interface. The reflected field may be a class (static) field or an instance field.
Constructor:
Constructor provides information about and access to, a single constructor for a class.

Scanner Class and Static Import with Example


java.util.Scanner class provides convenient methods to read data in the form of primitive type as well as string from the keyboard. A simple text scanner which can parse primitive types and strings using regular expressions.
A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. The resulting tokens may then be converted into values of different types using the various next methods.
Constructor:
public Scanner(InputStream)
Methods:

What is Applet with Simple Example ?



An Applet is a java program that is transmitted over the network from server to the client and execute within browser of client. Applets are used to provide interactivity in web application.
It is a managed object. Managed object is an object that is created and managed by a run time environment.  Lifecycle methods are used to manage the lifecycle of a managed object.
Applets are managed object because their objects are created and managed by the Browser or another Java applet viewing program, such as the Applet Viewer.

Lifecycle Methods of Applet:

Command Line Arguments in NetBeans IDE


Problem of a student:
I need to pass the command line arguments to my java program, 
I'm using netbeans IDE, anyone please let me know how to pass comand line arguments to our program(to main method) in netbeans. 
Solution:
We will create a new Java Application project and will add some code to the Main method which will print the provided command line arguments on the console.

Steps:

What is J2ME with simple example ?


The Java 2 Micro Edition (J2ME): J2ME is a Java platform that is designed for small devices. It contains specially designed, lightweight virtual machines; a bare minimum of core-class libraries; and lightweight substitutes for standard Java libraries. J2ME is the ideal mobile client platform for wireless PDAs and enhanced mobile phones.
J2ME is divided into configurations, profiles, and optional APIs, which provide specific information about APIs and different families of devices.
 A configuration is designed for a specific kind of device based on memory constraints and processor power. It specifies a Java Virtual Machine (JVM) that can be easily ported to devices supporting the configuration. It also specifies some subset of the Java 2 Platform, Standard Edition (J2SE) APIs that will be used on the platform, as well as additional APIs that may be necessary.
Profiles are more specific than configurations. A profile is based on a configuration and adds APIs for user interface, persistent storage, and whatever else is necessary to develop running applications.
Optional APIs define specific additional functionality that may be included in a particular configuration.

Can we override static method in Java ?


In sort,
 Static method belongs to the class, rather than to an object of the class. As you know overriding a method means redefining behaviour of an object, but static method show the behaviour of a class as whole and it is referred by class name. So it does not redefine the behaviour of an object.

In details,
Static method should be invoked with the class name, without the need for creating an instance of the class, as below
ClassName.methodName(if args)
You can also refer to static methods with an object reference, as bellow
instanceName.methodName(if args)
A subclass inherits all the members including static member (fields, methods, and nested classes) from its superclass.

How to define custom Exception ?


To define custom exception crate a sub class of exception and either override toString() method or provide default as well as augmented constructor. Argumented constructor must receive message as String.
public class MyException extends Exception{
    String msg="Exception";
    public MyException() {
        super();
    }
    public MyException(String msg){
        super(msg);
    }
//or
    @Override
    public String toString(){
        return msg;
    }
}

Magic of Finally block


‘finally’ keyword is use to define a block of statement that is to be executed when an exception occurs or non.

Magic of finally block

public class Main {
    public static int divide(int x, int y) throws Exception{
        boolean flag=false;
        try{
            if(y==0)
                throw new ArithmeticException("divide by zero");
            int c = x / y;
            return c;
        }catch(Exception e){
            System.out.println("Excetion is rethrowing..");
            flag=true;
            throw(e);
        }finally{
            if(flag==true){
                 System.out.println("Returning exception");
            }            
            else
                System.out.println("Returning Result");
        }
    }

Reasons to use throw keyword


1. To customize the message display in case of an exception.
Public Exception ();
Public Exception (String msg);
2. To throw user defined exception
throw new MyException(“ Emp is empty”);
3. To re-throw caught exception
throw (e);

Example of 1: customizing message

public class Main {
    public static void main(String[] args) {
        try {
            Scanner s=new Scanner(System.in);
            System.out.println("Enter two no.");
            int a = s.nextInt();
            int b = s.nextInt();
            if(b==0)
                throw new ArithmeticException("divide by zero");
            int c = a / b;
            System.out.println("Result is:" + c);
        } catch (NumberFormatException e) {
            System.out.println("Argument must be Number"+e);
        } catch (ArithmeticException e) {
            System.out.println("Second statement must be non zero"+e);
        } catch (ArrayIndexOutOfBoundsException e) {
            System.out.println("Invalid number of arguments"+ e);
        }catch(Exception e){
            System.out.println("Some thing wrong."+e);
        }

    }
}

Checked and Unchecked Exceptions


Except for RuntimeException, Error, and their subclasses, all exceptions are called checked exceptions. The compiler ensures that if a method can throw a checked exception, directly or indirectly, then the method must explicitly deal with it. The method must either catch the exception and take the appropriate action, or pass the exception on to its caller.
Exceptions defined by Error and RuntimeException classes and their subclasses are known as unchecked exceptions, meaning that a method is not obliged to deal with these kinds of exceptions. They are either irrecoverable (exemplified by the Error class) and the program should not attempt to deal with them, or they are programming errors (examplified by the RuntimeException class) and should be dealt with as such and not as exceptions.
Any method that can cause a checked exception to be thrown, either directly by using the throw statement or indirectly by invoking other methods that can throw such an exception, must deal with the exception in one of three ways. It can

Why java uses both compiler and interpreter?


The JVM runtime executes bytecode by interpreting it or using a just-in-time compiler (JIT). The Java compiler translates Java source code into a platform independent language called Java bytecode. Although bytecode is similar to machine language, but it is not the machine language of any actual computer. A Java interpreter or a just-in-time compiler (JIT) is used to run the compiled Java bytecode . Each platform needs its own Java bytecode interpreter, but all these interpreters interpret the same bytecode . JIT compiling, not interpreting, is used in most JVMs today to achieve greater speed.

Multiple Inheritance In Java?



Most of the Java lover say that Java does not support multiple inheritance but this is not hundred percent correct. We will try to understand inheritance in java in detail with all possibilities.

A relationship among classes where one class share the structure and/or behaviour of one of more classes. This mechanism is known as the name of inheritance.

Type of inheritance                                       purpose

1.       Implementation inheritance           Code Reusability and Runtime Polymorphism

2.       Interface inheritance                      Runtime Polymorphism

Syntax: implementation inheritance

Class ClassName extends SuperClassName{

//additional methods of class

}

What is JSF with Simple Example JSF



JSF is a specification given by Java Community Process (JCP).  JSF web application is based on the MVC design pattern. In addition it provides richer GUI based MVC environment than other web application frameworks. User events, like changed value in a text field or a clicked button, are main tasks to handle in GUI application. However, previously made web application only recognize the HTTP request. For a Web application to recognize these events, it has to process all request parameter. For example, if a user enters a text field in a standard desktop user interface, the client application is able to display a message as if the entered data is invalid to the user directly. A web application does not have this opportunity because the first HTTP request-response cycle is completed. It needs to redisplay the page and input fields including the previously entered data and an additional error message.

JSF User interface components remember their value, which are called statefulness. That means View in JSF architecture is managed as component tree that’s made of the stateful user interface components.

FaceServlet (controller) is a Servlet that manages the request processing life-cycle for web applications that are utilizing JSF to construct the user interface

HOW TO ACCESS SESSION IN STRUTS 2 WITH EXAMPLE


Some of my friends are confused, how to deal with session in struts2, because struts 2 is Servlet API independent. We will try to understand all possible way to deal with session.

You can obtain the session attributes by asking the ActionContext or implementing SessionAware. Implementing SessionAware is preferred.

Using ActionContext:

getContext()  static method of ActionContext return instance of ActionContext, on which getSession() method  is called which return Map of HttpSession value.

Map attmap = ActionContext.getContext().getSession();

Now get(), put() and remove() method of Map is used for getting, putting and removing attribute in session scope.

Association, Aggregation, and Composition with example




Most confusing topics of java are association, aggregation, and composition. In this post, we will try to understand three important concepts: association, aggregation, and composition.

The association relationship is a way of that a class holds a reference to another class. The relationship can be bi-directional with each class holding a reference to the other, but they have their own object life time. In this relationship no one is owner. They can exist without each other.

Aggregation is a special type of association. The aggregate class contains a reference to another class and is owner of this relationship. It is whole-part relationship. Each class referenced is considered to be part-of the aggregate (whole) class. The referenced class objects can not belong to any other object.

What do mean ownership?

If a class X contain reference of class Y and again class Y contain reference of class X then no clear ownership can be determined and the relationship is simply association.

If a class X contain reference of class Y and again class Y has no association with another object then class X has ownership and the relationship is aggregation.

LookupDispatchAction


LookupDispatchAction extends the functionality of DispatchAction class that support internationalization. LookupDispatchAction uses the value of the request parameter to reverse-map to a property in the Struts resource bundle file. ApplicationResources.properties. That is, the value of the request parameter is compared against the values of properties in the resource bundle until a match is found. The key for the matching property is then used as a key to another map that maps to a method in 

your LookupDispatchAction subclass that will be executed.

To use LookupDispatchAction, you must create a subclass from it and provide a set of methods that will be called to process requests. The subclass must also include a getKeyMethodMap( ) method that maps methods in the class to keys in the Struts resource bundle file.

DispatchAction class

The DispatchAction class provides a mechanism for modularizing a set of related functions into a single action, and thus eliminates the need to create separate, independent actions for each function. For example, consider a set of related functions for adding a user, updating a user, and removing a user. Instead of creating an AddUserAction class, an UpdateUserAction class, and a RemoveUserAction class, by extending DispatchAction, you can create one UserAction class that has three methods: add( ), update( ), and remove( ). At run time, DispatchAction manages routing requests to the appropriate method in its subclass. DispatchAction determines which method to call based on the value of a request parameter that is passed to it from the incoming request.
To use DispatchAction, you must create a subclass from it and provide a set of methods that will be called to process requests. Additionally, you have to set up for the action an action mapping that specifies the name of a request parameter that will be used to select which method should be called for each request.

hyperlinks in a struts 1


Global Forward: <html:link> tag is used to simulate hyperlinks in a struts application that is from hyperlinks request is send to the controller, Controller decide next view.

In jsp page:-
<html:link forward=”reg”>
In Mapping:-
<global-forwards>
<forward name=”reg” path=”/reg.jsp”>
</global-forwards>

DynaActionForm:



It is predefined form bean class that is use when no validation to be performs on the request data. Instead of creating a new ActionForm subclass and new get/set methods for each of your bean’s properties, you can list its properties, type, and defaults in the struts configuration file.
<form-beans>
    <form-bean name="DForm" type="org.apache.struts.action.DynaActionForm">
        <form-property name="name" type="java.lang.String" initial="Naveen"></form-property>
    </form-bean>
    </form-beans>

Validator Framework



Validator framework is an optional sub framework of struts that provides predefines validation logic for common validation problem. Validation logic is provided in the form of static methods called validation rules. When validator framework is used for form data validation your ActionForm must be extends ValidatorForm class.
Framework has following components:
1.    Set of rules defined in a xml file known as validator-rules.xml
2.    An xml file named validation.xml used by the application developer to apply validation rules on a form.

Validator-rules.xml
<form-validation>
    <global>
        <validator name="required"
                   classname="org.apache.struts.validator.FieldChecks"
                   method="validateRequired"
                   methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       org.apache.commons.validator.Validator,
                       javax.servlet.http.HttpServletRequest"
                   msg="errors.required"/>
<validator name="minlength"
                   classname="org.apache.struts.validator.FieldChecks"
                   method="validateMinLength"
                   methodParams="java.lang.Object,
                       org.apache.commons.validator.ValidatorAction,
                       org.apache.commons.validator.Field,
                       org.apache.struts.action.ActionMessages,
                       org.apache.commons.validator.Validator,
                       javax.servlet.http.HttpServletRequest"
                   depends=""
                   msg="errors.minlength"
                   jsFunction="org.apache.commons.validator.javascript.validateMinLength"/>
</global>
</form-validation>
Validation.xml
<form-validation>
<formset>
          <form name="MyActionForm">
            <field    property="name"   depends="required,minlength">
                    <arg0 key="MyActionForm.name"/>
                    <arg1 key="10" resource="false" />
                   <var>
                       <var-name>minlength</var-name>
                       <var-value>10</var-value>
                   </var>
            </field>
            <field   property="id"  depends="required,mask">
                    <arg key="MyActionForm.id"/>
                    <msg key="errors.email.msg" name="mask"/>
                    <var>
                        <var-name>mask</var-name>
                        <var-value>^[0-9a-zA-Z]*$</var-value>
                    </var>
            </field>
        </form>
    </formset>
</form-validation>

Exp:-
<form-validation> is the root element
<formset> sub element of <form-validation> contains set of form
<form name=”MyForm”> sub element of <formset> contains form element
<field  property="id"  depends="required,mask"> sub element of <form> contains field information for    validation

property define property name and depends define validation rule applied on that property.
<arg key="error.msg" resource="false"> sub element of <field> specify the value of error message place holder if resource is false that means value is directly replaced by key or true means value is get form property file.
<msg key="errors.email.msg" name="mask"> sub element of <field> specify message for a validation rule.
<var> sub element of <field> is used for provide input value for variable.

Mask Validation Rule is used to validate value of a field using regular expression.

<global>       
        <constant>
            <constant-name>postal</constant-name>
            <constant-value>^[0-9]{2}\*?[0-9]+$</constant-value>
        </constant>  
  </global>
<formset>
   <field
                property="id"
                depends="required,mask">
                    <arg key="MyActionForm.id"/>
                    <msg key="errors.email.msg" name="mask"/>
                    <var>
                        <var-name>mask</var-name>
                        <var-value>${postal}</var-value>
                    </var>
            </field>
        </form>
</fromset>

Tiles



An optional framework of a struts used on composite view design pattern that facilitated faster development of views. Normally in a web application a view consist of different sub-views which are arrange according to a predefine structure that is common for all views. Usually structure is defined with the help of frameset, html table and style sheet. Tiles frame work provides a mechanism to change the structured of all views without individually applying changes to them.

<titles:insert> tag is used to define place holder tiles.

myLayout.jsp

<table width="100%"  height="553">           
            <tr bgcolor="#CC9999"><td height="60" colspan="2"><titles:insert attribute="header"/></td>
            </tr>
            <tr><td width="25%" height="436" bgcolor="#9999CC">
<titles:insert attribute="menu"/></td>
            <td><titles:insert attribute="contents"/></td></tr>
            <tr bgcolor="#CCCCCC"><td colspan="2"><titles:insert attribute="footer"/></td></tr>
    </table>

WelcomeStruts.jsp

<tiles:insert page="myLayout.jsp">      
        <tiles:put name="header" value="header.jsp"/>
        <tiles:put name="footer" value="footer.jsp"/>
        <tiles:put name="contents" value="contents.jsp"/>
        <tiles:put name="menu" value="menu.jsp"/>
        <tiles:put name="title" value="Home Page"/>
 </tiles:insert>
Tiles Definition is used to provide the default value of parameter in a tiles layout. This is used to an tiles to be display in some region of the layout remain common for the more than one pages.

myDef.jsp

<logic:notPresent name="myDef" scope="application">
            <tiles:definition id="myDef" page="myLayout.jsp" scope="application">
                <tiles:put name="header" value="header.jsp"/>
                <tiles:put name="menu" value="menu.jsp"/>
                <tiles:put name="footer" value="footer.jsp"/>
            </tiles:definition>
        </logic:notPresent>

WelcomeStruts.jsp

<jsp:incude page=”myDef.jsp”>
<tiles:insert beanName=”myDef” beanScope=”application”>
<tiles:put name=””contents” value=”contents.jsp”/>
</tiles:insert>

Log4j


Log4j, a popular logging package for java. The package is distributed under the Apache Software License, a fully-fledge open source license.
Drawbacks          :               slow down an application, If two verbose.
Advantage          :               It provides the precise context about a run of the application. One inserted into code, the generation of logging output requires no human intervention (involvement). Log output can be saved in persistent medium to be studied at a later time. Now it was important component of the development cycle.
It has three main components:
  1. Logger
  2. Appender
  3. Layout
These three type of component work together to enable developers to log message according to message type and level and to control at runtime how these message are formatted and where they are reported.
Logger:
Logger is main class which provides functionality to log information for that purpose it provides several methods. This class extends Category class. In log4j version 1.2, Category class is replaced by Logger class as main logging class. So do not use Category.getCategory to get a logger. This is deprecated.

org.apache.log4j.Logger class provides methods to get Logger:
Logger(String name)  [constructor]
getRootLogger()               : Logger
getLogger(String  name):Logger
getLogger(Class class)    :Logger
To log(register) message  Methods that used by the Logger is defined its super class Category :
debug(Object Message) : void
info(Object Message) : void
warn(Object Message) : void
error(Object Message) : void
fatal(Object Message) : void
trace(Object Message):void [this method in Logger class]
log(Priority level,  Object message) : void
log() is very useful method that provide to log any type of message by defining message level.
Level is sub class of Priority which defines message level as a final static constant:
Level.DEBUG
Level.INFO
Level.WARN
Level.ERROR
Level.FATAL
Level.TRACE
Level.ALL
Level.OFF
Level Description
all          
All levels including custom levels
trace (since log4j 1.2.12)
developing only, can be used to follow the program execution.
debug
developing only, for debugging purpose
info
Production optionally, Course grained (rarely written informations), I use it to print that a configuration is initialized, a long running import job is starting and ending.
warn
Production, simple application error or unexpected behaviour. Application can
continue. I warn for example in case of bad login attemps, unexpected data during import jobs
error
 Production, application error/exception but application can continue. Part of the application
is probably not working.
Fatal
 Production, fatal application error/exception, application cannot continue, for example
database is down.
no
Do not log at all.

Appender:
Log4j allow logging results print to multiple destinations, an output destination is called an appender.                           An appender specifies where your log messages are written to. There is a wide choice of appenders available. All appenders are direct or indirect subclasses of the AppenderSkeleton.

ConsoleAppender           Logs to console
FileAppender                    Logs to a file
SMTPAppender                Logs by email
RollingFileAppender       Logs to a file, starts a new file once the max size is reached. (An alternative is the DailyRollingFileAppender which creates on file per day)
But there are as well:
AsyncAppender, JDBCAppender, JMSAppender, LF5Appender, NTEventLogAppender,
NullAppender, NullAppender, SMTPAppender, SocketAppender, SocketHubAppender,
SyslogAppender, TelnetAppender, DailyRollingFileAppender, RollingFileAppender.

Custom appenders can be created as well. The log4j download comes with a whole bunch of
samples in the examples directory.


Layout:
The layout specifies how a log message looks like.

DateLayout
HTMLLayout
PatternLayout
SimpleLayout
XMLLayout

SimpleLayout has no properties to be set. It is simple. We used PatternLayout in our example and we set a property named ConversionPattern. This property allows us to define the log output.

Steps:
  1. First you define the layout.
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout

  1. The pattern layout requires another parameter, i.e. the pattern.
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

%d{ABSOLUTE}                                 Date in Format Absolute
%5p %5                                defines a right justified print with 5 characters, p prints the priority of the log message
%c{1}:%L - %m%n            And the other settings. Very simple. They are all explained in the API.

Steps to use log4j:
  1. Create a Java project.
  2. Add the log4j.jar to the build path of the project.(add in project library)
  3. Create Configuration file (log4j.xml or log4j.properties) in src folder
  4. Create a class to getLogger and add log message

Using properties file to configure log4j

### direct log messages to stdout  using simple layout###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.SimpleLayout
log4j.rootLogger=debug, stdout


### direct log messages to stdout  using pattern layout###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=debug, stdout



### file appender
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.maxFileSize=100KB
log4j.appender.file.maxBackupIndex=5
log4j.appender.file.File=test.log
log4j.appender.file.threshold=info
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, file


Log messages with Level info to fatal to a file and send messages from error to fatal by email. The
file should be rolled every 100 KB.


#email appender
log4j.appender.mail=org.apache.log4j.net.SMTPAppender
#defines how othen emails are send
log4j.appender.mail.BufferSize=1
log4j.appender.mail.SMTPHost="smtp.myservername.xx"
log4j.appender.mail.From=fromemail@myservername.xx
log4j.appender.mail.To=toemail@myservername.xx
log4j.appender.mail.Subject=Log ...
log4j.appender.mail.threshold=error
log4j.appender.mail.layout=org.apache.log4j.PatternLayout
log4j.appender.mail.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
log4j.rootLogger=warn, mail

You need mail.jar and activation.jar libraries from J2EE to send emails. Further properties of the
SmtpAppender are described above.



Using xml is best option to configure Log4j

1      Add log4j.jar file
2      Create log4j.xml in src folder and Copy the log4j.dtd into the source folder as well.
3      Create a class to getLogger and add log message


< log4j:configuration > is root element which is used to configure log4j

<appender> sub element of < log4j:configuration>  is used to configure appender
<appender name=”” and class=””>

<layout> sub element of <appender> is used to configure layout
<layout class=””>

<root>sub element of < log4j:configuration>  is used to configure root logger



Examples:-


Using console appender with  simple layout and pattern layout:-

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.SimpleLayout"></layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="stdout"/>
</root>
</log4j:configuration>

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="stdout" class="org.apache.log4j.ConsoleAppender">
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n"/>
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="stdout"/>
</root>
</log4j:configuration>

Using Rolling file appender:
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="file"
class="org.apache.log4j.RollingFileAppender">
<param name="maxFileSize" value="100KB" />
<param name="maxBackupIndex" value="5" />
<param name="File" value="d:/test.log" />
<param name="threshold" value="info"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{ABSOLUTE} %5p %c{1}:%L = %m%n" />
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="file"/>
</root>
</log4j:configuration>

Using Rolling file appender and mail appender together
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd" >
<log4j:configuration>
<appender name="file"
class="org.apache.log4j.RollingFileAppender">
<param name="maxFileSize" value="100KB" />
<param name="maxBackupIndex" value="5" />
<param name="File" value="test.log" />
<param name="threshold" value="info"/>
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>
</appender>
<appender name="mail" class="org.apache.log4j.net.SMTPAppender">
<param name="SMTPHost" value="smtp.myservername.xx" />
<param name="From" value="email@fromemail.xx" />
<param name="To" value="toemail@toemail.xx" />
<param name="Subject" value="[LOG] ..." />
<param name="BufferSize" value="1" />
<param name="threshold" value="error" />
<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern"
value="%d{ABSOLUTE} %5p %c{1}:%L - %m%n" />
</layout>
</appender>
<root>
<priority value="debug"></priority>
<appender-ref ref="file" />
<appender-ref ref="mail"/>
</root>
</log4j:configuration>
<root>
<priority value="debug"></priority>
<appender-ref ref="file" />
<appender-ref ref="mail"/>
</root>
</log4j:configuration>