Академический Документы
Профессиональный Документы
Культура Документы
Every one who is using tomcat and java, face problem of starting program automatically on tomcat startup. To run java program automatically on tomcat startup, need to use Servlet and this Servlet initialized on tomcat startup automatically. How it will work, we will explain in next phase. Most of small and big web application needs to execute some queries and java program in background, without opening on the web browser and user interaction. If we want to start scheduler for newsletter which has to send newsletter on everyday in evening, you have to start timer when tomcat started. This timer works in background for waiting to come evening to send newsletter, without opening script on web browser and manual process by user. To execute our program, we have to use Servlet and Servlet should define in deployment descriptor web.xml file in WEB-INF. web.xml file contain tags <load-on-startup> and <servlet> tag. Servlet tag keep information of Servlet class. When tomcat starts, all Servlet loads in web container and init method of Servlet loaded first. Any java statement in init method of Servlet can be executed on running tomcat startup batch or shell. In init method we can define our scripts which have to be executed e.g. sending emails, sending newsletters, starting scheduler.
<?xml version="1.0" encoding="UTF-8"?> <web-app> <servlet> <servlet-name>ServletInitializer</servlet-name> <servlet-class>com.cron.ServletInitializer</servlet-class> <load-on-startup>1</load-on-startup> </servlet> </web-app>
ServletInitializer.java
package com.cron; import java.io.*; import import import import javax.servlet.*; javax.servlet.http.HttpServletRequest; javax.servlet.http.HttpServlet; javax.servlet.http.HttpServletResponse;
public void init() throws ServletException { /// Automatically java script can run here System.out.println("************"); System.out.println("*** Servlet Initialized successfully ***.."); System.out.println("***********"); } public void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
determines how full the hash table can be before it is resized upward. Specifically, when the number of elements is greater than the capacity of the hash table multiplied by its fill ratio, the hash table is expanded. If you do not specify a fill ratio, then 0.75 is used. Finally, the fourth version creates a hash table that is initialized with the elements in m. The capacity of the hash table is set to twice the number of elements in m. The default load factor of 0.75 is used. The fourth constructor was added by Java 2.
The following example uses a Hashtable to store the names of bank depositors and their current balances: // Demonstrate a Hashtable import java.util.*; class HTDemo { public static void main(String args[]) { Hashtable balance = new Hashtable(); Enumeration names; String str; double bal; balance.put("John Doe", new Double(3434.34)); balance.put("Tom Smith", new Double(123.22)); balance.put("Jane Baker", new Double(1378.00)); balance.put("Todd Hall", new Double(99.22)); balance.put("Ralph Smith", new Double(-19.08)); // Show all balances in hash table. names = balance.keys(); while(names.hasMoreElements()) { str = (String) names.nextElement(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = ((Double)balance.get("John Doe")).doubleValue(); balance.put("John Doe", new Double(bal+1000)); System.out.println("John Doe's new balance: " + balance.get("John Doe")); } } The output from this program is shown here: Ralph Smith: -19.08 Tom Smith: 123.22 John Doe: 3434.34 Todd Hall: 99.22
Jane Baker: 1378.0 John Doe's new balance: 4434.34 One important point: like the map classes, Hashtable does not directly support iterators. Thus, the preceding program uses an enumeration to display the contents of balance. However, you can obtain set-views of the hash table, which permits the use of iterators. To do so, you simply use one of the collection-view methods defined by Map, such as entrySet( ) or keySet( ). For example, you can obtain a set-view of the keys and iterate through them. Here is a reworked version of the program that shows this technique: // Use iterators with a Hashtable. import java.util.*; class HTDemo2 { public static void main(String args[]) { Hashtable balance = new Hashtable(); String str; double bal; balance.put("John Doe", new Double(3434.34)); balance.put("Tom Smith", new Double(123.22)); balance.put("Jane Baker", new Double(1378.00)); balance.put("Todd Hall", new Double(99.22)); balance.put("Ralph Smith", new Double(-19.08)); // show all balances in hashtable Set set = balance.keySet(); // get set-view of keys // get iterator Iterator itr = set.iterator(); while(itr.hasNext()) { str = (String) itr.next(); System.out.println(str + ": " + balance.get(str)); } System.out.println(); // Deposit 1,000 into John Doe's account bal = ((Double)balance.get("John Doe")).doubleValue(); balance.put("John Doe", new Double(bal+1000)); System.out.println("John Doe's new balance: " + balance.get("John Doe")); } }
HashMap( ) HashMap(Map m) HashMap(int capacity) HashMap(int capacity, float fillRatio) The first form constructs a default hash map. The second form initializes the hash map by using the elements of m. The third form initializes the capacity of the hash map to capacity. The fourth form initializes both the capacity and fill ratio of the hash map by using its arguments. The meaning of capacity and fill ratio is the same as for HashSet, described earlier. HashMap implements Map and extends AbstractMap. It does not add any methods of its own. You should note that a hash map does not guarantee the order of its elements. Therefore, the order in which elements are added to a hash map is not necessarily the order in which they are read by an iterator. The following program illustrates HashMap. It maps names to account balances. Notice how a set-view is obtained and used. import java.util.*; class HashMapDemo { public static void main(String args[]) { // Create a hash map HashMap hm = new HashMap(); // Put elements to the map hm.put("John Doe", new Double(3434.34)); hm.put("Tom Smith", new Double(123.22)); hm.put("Jane Baker", new Double(1378.00)); hm.put("Todd Hall", new Double(99.22)); hm.put("Ralph Smith", new Double(-19.08)); // Get a set of the entries Set set = hm.entrySet(); // Get an iterator Iterator i = set.iterator(); // Display elements while(i.hasNext()) { Map.Entry me = (Map.Entry)i.next(); System.out.print(me.getKey() + ": "); System.out.println(me.getValue()); } System.out.println(); // Deposit 1000 into John Doe's account double balance = ((Double)hm.get("John Doe")).doubleValue(); hm.put("John Doe", new Double(balance + 1000)); System.out.println("John Doe's new balance: " + hm.get("John Doe"));
} } Output from this program is shown here: Ralph Smith: -19.08 Tom Smith: 123.22 John Doe: 3434.34 Todd Hall: 99.22 Jane Baker: 1378.0 John Doe's current balance: 4434.34 The program begins by creating a hash map and then adds the mapping of names to balances. Next, the contents of the map are displayed by using a set-view, obtained by calling entrySet(). The keys and values are displayed by calling the getKey() and getValue() methods that are defined by Map.Entry. Pay close attention to how the deposit is made into John Doe's account. The put() method automatically replaces any preexisting value that is associated with the specified key with the new value. Thus, after John Doe's account is updated, the hash map will still contain just one "John Doe" account.
public class MapExample { public static void main(String[] args) { Map<Object,String> mp=new HashMap<Object, String>(); // adding or set elements in Map by put method key and value pair mp.put(new Integer(2), "Two"); mp.put(new Integer(1), "One"); mp.put(new Integer(3), "Three"); mp.put(new Integer(4), "Four"); //Get Map in Set interface to get key and value Set s=mp.entrySet();
//Move next key and value of Map by iterator Iterator it=s.iterator(); while(it.hasNext()) { // key=value separator this by Map.Entry to get key and value Map.Entry m =(Map.Entry)it.next(); // getKey is used to get key of Map int key=(Integer)m.getKey(); // getValue is used to get value of key in Map String value=(String)m.getValue(); System.out.println("Key :"+key+" } } } Value :"+value);
Output Key :1 Value :One Key :2 Value :Two Key :3 Value :Three Key :4 Value :Four
public class HashMapExample { public static void main(String[] args) { HashMap<Object,String> hm=new HashMap<Object,String>(); // adding or set elements in HashMap by put method key and value pair hm.put(new Integer(2), "Two"); hm.put(new Integer(1), "One");
hm.put(new Integer(3), "Three"); hm.put(new Integer(4), "Four"); // Get hashmap in Set interface to get key and value Set s=hm.entrySet(); // Move next key and value of HashMap by iterator Iterator it=s.iterator(); while(it.hasNext()) { // key=value separator this by Map.Entry to get key and value Map.Entry m =(Map.Entry)it.next(); // getKey is used to get key of HashMap int key=(Integer)m.getKey(); // getValue is used to get value of key in HashMap String value=(String)m.getValue(); System.out.println("Key :"+key); System.out.println("value :"+value); } } }
Output Key :1 value :One Key :2 value :Two Key :3 value :Three Key :4 value :Four
import java.util.Enumeration; public class HashTableExample { public static void main(String[] args) { Hashtable<Integer,String> hTable=new Hashtable<Integer,String>(); //adding or set items in Hashtable by put method key and value pair hTable.put(new Integer(2), "Two"); hTable.put(new Integer(1), "One"); hTable.put(new Integer(4), "Four"); hTable.put(new Integer(3), "Three"); hTable.put(new Integer(5), "Five"); // Get Hashtable Enumeration to get key and value Enumeration em=hTable.keys(); while(em.hasMoreElements()) { //nextElement is used to get key of Hashtable int key = (Integer)em.nextElement(); //get is used to get value of key in Hashtable String value=(String)hTable.get(key); } } } System.out.println("Key :"+key+" value :"+value);
public class HashTableJava { public static void main(String[] args) { Hashtable<Integer,String> hTable=new Hashtable<Integer,String>(); hTable.put(new hTable.put(new hTable.put(new hTable.put(new hTable.put(new Integer(2), Integer(1), Integer(4), Integer(3), Integer(5), "Two"); "One"); "Four"); "Three"); "Five");
Map.Entry m=(Map.Entry)i.next(); int key = (Integer)m.getKey(); String value=(String)m.getValue(); System.out.println("Key :"+key+" } } } value :"+value);
Output Key :5 value :Five Key :4 value :Four Key :3 value :Three Key :2 value :Two Key :1 value :One
public class MapRemoveExample { public static void main(String[] args) { Map<Object,String> mp=new HashMap<Object, String>(); mp.put(new mp.put(new mp.put(new mp.put(new Integer(2), Integer(1), Integer(3), Integer(4), "Two"); "One"); "Three"); "Four");
// remove map object mp.remove(new Integer(3)); // remove map by object Set s=mp.entrySet(); Iterator it=s.iterator(); while(it.hasNext()) {
Map.Entry m =(Map.Entry)it.next(); int key=(Integer)m.getKey(); String value=(String)m.getValue(); } } } System.out.println("Key :"+key+" Value :"+value);
public class IteratorExample { public static void main(String[] args) { Hashtable<Integer,String> hTable=new Hashtable<Integer,String>(); hTable.put(new hTable.put(new hTable.put(new hTable.put(new Integer(2), Integer(1), Integer(4), Integer(3), "Two"); "One"); "Four"); "Three");
Set s =hTable.entrySet(); // Using iterator in hashtable Iterator i=s.iterator(); while(i.hasNext()) { Map.Entry m=(Map.Entry)i.next(); int key = (Integer)m.getKey(); String value=(String)m.getValue(); } } } System.out.println("Key :"+key+" value :"+value);
Output
Key :4 value :Four Key :3 value :Three Key :2 value :Two Key :1 value :One
Output List Value ne List Value :Three List Value :two List Value :four
public class ListClearExample { public static void main(String[] args) { List<String> ls=new ArrayList<String>(); ls.add("one"); ls.add("Three"); ls.add("two"); ls.add("four"); ls.clear(); // clear all elements from list collection } } System.out.println("Size of list after clear :"+ls.size());
timer.schedule(new TimerTask(),1000); run one time after 1 second 2. timer.schedule(new TimerTask(),1000,1000); start after one 1 second and repeat every 1 second infinitely
The example will run statement after 10 second and run every 1 second
import java.util.Timer; import java.util.TimerTask; public class TimerClass { public static void main(String[] args) { Timer timer= new Timer();
int startingTime=10000; //millisecond 10 seconds=10000 int delayTime=1000; // millisecond 1 second timer.schedule(new TimerTask() { public void run() { System.out.println("Timer repeat statement"); } },startingTime,delayTime); } }
// add vector elements vc.add("Vector Object 1"); vc.add("Vector Object 2"); vc.add("Vector Object 3"); vc.add("Vector Object 4"); vc.add("Vector Object 5"); // add vector element at index vc.add(3, "Element at fix position"); // vc.size() inform number of elements in Vector System.out.println("Vector Size :"+vc.size()); // get elements of Vector for(int i=0;i<vc.size();i++) { System.out.println("Vector Element "+i+" :"+vc.get(i)); } } }
import java.util.Vector; public class VectorSize { public static void main(String[] args) { Vector vc=new Vector(); System.out.println("Default Capacity of Vector is :"+vc.capacity()); vc.add("first element"); System.out.println("Default Capacity of Vector after one element :"+vc.capacity()); vc.add("second element"); System.out.println("Default Capacity of Vector after two elements :"+vc.capacity()); } }
Output Default Capacity of Vector is :10 Default Capacity of Vector after one element :10 Default Capacity of Vector after two elements :10
// remove Vector element by index number vc.remove(3); // remove Vector element by Object value vc.remove("Vector Element 5"); // get elements of Vector for(int i=0;i<vc.size();i++) { System.out.println("Vector Element "+i+" :"+vc.get(i)); }
} }
output Vector Element 0 :Vector Element 1 Vector Element 1 :Vector Element 2 Vector Element 2 :Vector Element 3
} }
Output
String array and int array. ArrayList contains many useful methods. To add element in ArrayList, we can use add() method of ArrayList class. To add elements at fix position, we have to use add(index, object) method. To get value from ArrayList, ArrayList provides get() method and ArrayList size() method. Size() method returns total number of elements in ArrayList. Example of ArrayList in java
import java.util.ArrayList; public class ArrayListExample { public static void main(String[] args) { ArrayList<String> arlist=new ArrayList<String>(); //<E> it is return type of ArrayList arlist.add("First Element"); // adding element in ArrayList arlist.add("Second Element"); arlist.add("Third Element"); arlist.add("forth Element"); arlist.add("fifth Element"); // add element with index for fix order arlist.add(2, "Fixed Order of Element"); // arlist.size() inform number of elements in ArrayList System.out.println("ArrayList Size :"+arlist.size()); // get elements of ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList Element "+i+" :"+arlist.get(i)); } } }
output ArrayList Size :6 ArrayList Element 0 :First Element ArrayList Element 1 :Second Element ArrayList Element 2 :Fixed Order of Element ArrayList Element 3 :Third Element ArrayList Element 4 :forth Element ArrayList Element 5 :fifth Element
Java ArrayList
ArrayList arlist=new ArrayList(); arlist.add("1 arlist.add("2 arlist.add("3 arlist.add("4 arlist.add("5 Arraylist"); // adding element in ArrayList Arraylist"); Arraylist"); Arraylist"); Arraylist");
System.out.println("ArrayList Size :"+arlist.size()); // Display ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList "+i+" :"+arlist.get(i)); }
ArrayList<String> arlist=new ArrayList<String>(); //<E> it is return type of ArrayList arlist.add("First Element"); // adding element in ArrayList arlist.add("Second Element"); arlist.add("Third Element"); arlist.add("forth Element"); arlist.add("fifth Element"); // remove array list element by index number arlist.remove(3); // remove ArrayList element by Object value arlist.remove("fifth Element"); // get elements of ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList Element "+i+" :"+arlist.get(i)); } } }
Output Remove ArrayList Element 0 :First Element Remove ArrayList Element 1 :Second Element Remove ArrayList Element 2 :Third Element
arlist.add("fifth Element"); // remove array list element by index number arlist.remove(3); // remove ArrayList element by Object value arlist.remove("fifth Element"); // get elements of ArrayList for(int i=0;i<arlist.size();i++) { System.out.println("ArrayList Element "+i+" :"+arlist.get(i)); }
} }
Output Remove ArrayList Element 0 :First Element Remove ArrayList Element 1 :Second Element Remove ArrayList Element 2 :Third Element
System.out.println("Value :"+value); } } }
public class SortedMapExample { public static void main(String[] args) { SortedMap<Integer,String> sm=new TreeMap<Integer, String>(); sm.put(new sm.put(new sm.put(new sm.put(new sm.put(new Integer(2), Integer(1), Integer(4), Integer(3), Integer(5), "Two"); "One"); "Four"); "Three"); "Five");
Set s=sm.entrySet(); // Using iterator in SortedMap Iterator i=s.iterator(); while(i.hasNext()) { Map.Entry m =(Map.Entry)i.next(); int key = (Integer)m.getKey(); String value=(String)m.getValue(); System.out.println("Key :"+key+" } } } value :"+value);
Output Key :1 value :One Key :2 value :Two Key :3 value :Three Key :4 value :Four Key :5 value :Five
public class ListExample { public static void main(String[] args) { // List Example implement with ArrayList List<String> ls=new ArrayList<String>(); ls.add("one"); ls.add("Three"); ls.add("two"); ls.add("four"); Iterator it=ls.iterator(); while(it.hasNext()) { String value=(String)it.next(); } } } System.out.println("Value :"+value);
Output List Value ne List Value :Three List Value :two List Value :four