polymorphism

class A {
    public void test(){
        System.out.println("hello");
    }
    
    public void foo(){
        System.out.println("fooo");
    }
}

class B extends A {
    @Override
    public void test(){
        System.out.println("world");
    }
    public void bar(){
        System.out.println("baar");
    }
}


public class PolymorphismDemo {

    public static void main(String[] args) {
        
        A a = new A();
        a.test(); // allowed: will print hello
        a.foo(); // allowed: will print fooo
        //a.bar(); // not allowed: compile time error
        
        B b = new B();
        b.test(); // allowed: will print world
        b.foo(); // allowed: will print fooo
        b.bar(); // allowed: will print baar
        
        A c = new B();
        c.test(); // allowed: will print world
        c.foo(); // allowed: will print fooo
        //c.bar(); // not allowed: compile time error
        
        //B d = new A(); // not allowed: compile time error
        
        A e = new B();
        A f = (A)e;
        f.test(); // allowed: will print world
        f.foo(); // allowed: will print fooo
        //f.bar(); // not allowed: compile time error
        
        B g = new B();
        A h = (A)g;
        h.test(); // allowed: will print world
        h.foo(); // allowed: will print fooo
        //h.bar(); // not allowed: compile time error
    }    
}

 

Sorting User Defined Collection Using Comparator

public class Student {
    String name;
    int age;

    public Student(String name, int age) {
        this.name = name;
        this.age = age;
    }

    @Override
    public String toString() {
        return "Student{" + "name=" + name + ", age=" + age + '}';
    }
}

 

package collections;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Hashtable;
import java.util.Iterator;


/**
 *
 * @author Shailesh Sonare
 */
public class MyCollections {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        // TODO code application logic here
        ArrayList<Integer> list = new ArrayList<Integer>();
        list.add(0, 5);
        list.add(1, 2);
        list.add(2, 3);
        list.add(3, 8);
        
        Collections.sort(list, new Comparator<Integer>(){
            @Override
            public int compare(Integer o1, Integer o2) {
                return o1.compareTo(o2);
            }            
        });
        
        for(Iterator i = list.iterator(); i.hasNext();) {
            System.out.println("" + i.next());
        }
        
        
        Hashtable ht = new Hashtable();
        ht.put(0, "Shailesh Sonare");
        
        HashMap hm = new HashMap();
        hm.put(0, "Mahesh Sonare");
        
        ArrayList<Student> sl = new ArrayList<Student>();
        
        sl.add(new Student("Shailesh", 28));
        sl.add(new Student("Mahesh", 20));
        sl.add(new Student("Shilpa", 22));
        
        Collections.sort(sl, new Comparator<Student>(){
            @Override
            public int compare(Student o1, Student o2) {
                if(o1.age > o2.age) {
                    return 1;
                } else if(o1.age < o2.age) {
                    return -1;
                } else {
                    return 0;
                }
            }
        });
        
        for(Iterator i = sl.iterator(); i.hasNext();) {
            System.out.println((Student)i.next());
        }
        
    }
    
}

 

equals and hashcode

equals() method

The equals() method compares two objects for equality and returns true if they are equal. The equals() method provided in the Object class uses the identity operator (==) to determine whether two objects are equal. For primitive data types, this gives the correct result. For objects, however, it does not. The equals() method provided by Object tests whether the object references are equal—that is, if the objects compared are the exact same object.

To test whether two objects are equal in the sense of equivalency (containing the same information), you must override the equals() method.

hashCode() method

hashCode() is used for bucketing in Hash implementations like HashMap, HashTable, HashSet, etc.

The value received from hashCode() is used as the bucket number for storing elements of the set/map. This bucket number is the address of the element inside the set/map.

When you do contains() it will take the hash code of the element, then look for the bucket where hash code points to. If more than 1 element is found in the same bucket (multiple objects can have the same hash code), then it uses the equals() method to evaluate if the objects are equal, and then decide if contains() is true or false, or decide if element could be added in the set or not.

__________________________

A hashcode is a number generated from any object. This is what allows objects to be stored/retrieved quickly in a Hashtable.
Imagine the following simple example:
On the table in front of you you have nine boxes, each marked with a number 1 to 9. You also have a pile of wildly different objects to store in these boxes, but once they are in there you need to be able to find them as quickly as possible.
What you need is a way of instantly deciding which box you have put each object in. It works like an index; you decide to find the cabbage so you look up which box the cabbage is in, then go straight to that box to get it.
Now imagine that you don’t want to bother with the index, you want to be able to find out immediately from the object which box it lives in.
In the example, let’s use a really simple way of doing this – the number of letters in the name of the object. So the cabbage goes in box 7, the pea goes in box 3, the rocket in box 6, the banjo in box 5 and so on. What about the rhinoceros, though? It has 10 characters, so we’ll change our algorithm a little and “wrap round” so that 10-letter objects go in box 1, 11 letters in box 2 and so on. That should cover any object.
Sometimes a box will have more than one object in it, but if you are looking for a rocket, it’s still much quicker to compare a peanut and a rocket, than to check a whole pile of cabbages, peas , banjos and rhinoceroses.
That’s a hash code. A way of getting a number from an object so it can be stored in a Hashtable. In Java a hash code can be any integer, and each object type is responsible for generating its own. Lookup the “hashCode” method of Object.

Spring Resources

Step 1. Create resource directory


Step 2. Add tags in web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>2</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
        <url-pattern>*.htm</url-pattern>
        <url-pattern>*.css</url-pattern>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
    <welcome-file-list>
        <welcome-file>redirect.jsp</welcome-file>
    </welcome-file-list>
</web-app>

 


Step 3. Configure dispatcher-servlet.xml

 

<?xml version='1.0' encoding='UTF-8' ?>
<!-- was: <?xml version="1.0" encoding="UTF-8"?> -->
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
       http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd
       http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd
       http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd">

    <context:component-scan base-package="shaileshsonare.com.blog.controller"/>

    <!--<mvc:resources mapping="/resources/**" location="/resources/" cache-period="10000" />-->
    <mvc:annotation-driven />
        <mvc:resources mapping="/resources/**" location="/resources/red/"/>

    <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver"
          p:prefix="/WEB-INF/jsp/"
          p:suffix=".jsp" />
</beans>

 


Step 4. link or include in jsp page

<head>
    <meta charset="UTF-8">
    <title>Welcome to Spring Web MVC project</title>
    <link href="<c:url value="/resources/css/default.css" />" rel="stylesheet">
          <link href="<c:url value="/resources/js/default.css" />" rel="stylesheet">
</head>

 


<img width="100px" height="50px" src="<c:url value="/resources/images/logo.gif"/>"/>

 

BeanFactory and Application Context

Bean Factory

  • Bean instantiation/wiring

Application Context

  • Bean instantiation/wiring
  • Automatic BeanPostProcessor registration
  • Automatic BeanFactoryPostProcessor registration
  • Convenient MessageSource access (for i18n)
  • ApplicationEvent publication

Bean Factory

 

BeanFactory beanFactory = new DefaultListableBeanFactory();
XmlBeanDefinitionReader reader = new XmlBeanDefinitionReader((BeanDefinitionRegistry) beanFactory);
reader.loadBeanDefinitions(new ClassPathResource("spring.xml"));

ComponentClass cc = (ComponentClass) beanFactory.getBean("compclass");

 


<bean id="compclass" class="com.classes.ComponentClass" />

 


Application Context

ApplicationContext context = new ClassPathXmlApplicationContext("spring.xml");
ComponentClass cc = (ComponentClass) context.getBean("compclass");

 


 

<bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"
      p:location="myproperties.properties" />

<bean id="compclass" class="com.classes.ComponentClass" p:age="${myp.age}" />

 


<bean id="compclass" class="com.classes.ComponentClass">
    <property name="age" value="30"/>
</bean>

 


Ref:

  1. http://stackoverflow.com/questions/243385/beanfactory-vs-applicationcontext
  2. http://stackoverflow.com/questions/5231371/springs-xmlbeanfactory-is-deprecated

Collections

 

ArrayList list = new ArrayList();
        list.add("h");
        list.add("e");
        list.add("l");
        list.add("l");
        list.add("o");

        for (int i = 1; i < 10; i++) {
            list.add(i);
        }

        Iterator it = list.iterator();

        while (it.hasNext()) {
            out.println(it.next() + "<br/>");
        }

        HashSet hs = new HashSet();
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("C");
        hs.add("C");

        HashMap hm = new HashMap();
        hm.put("a", "A");
        hm.put("b", "B");

        Iterator its = hs.iterator();

        while (its.hasNext()) {
            out.println(its.next() + "<br/>");
        }

        Iterator itr = hm.entrySet().iterator();

        while (itr.hasNext()) {
            Map.Entry pair = (Map.Entry) itr.next();
            out.println(pair.getKey() + " => " + pair.getValue() + "<br/>");
        }

        String[] strarr = new String[10];

        for (int i = 0; i < 10; i++) {
            strarr[i] = "abc" + i;
        }

        for (String valu : strarr) {
            out.println(valu);
        }

 
Ref:

  1. http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work
  2. http://stackoverflow.com/questions/4131655/what-is-the-difference-between-lists-arraylists-maps-hashmaps-collections-et
  3. https://www.quora.com/What-is-the-difference-between-a-Set-and-a-Map-in-Java
  4. http://stackoverflow.com/questions/1066589/iterate-through-a-hashmap
  5. http://stackoverflow.com/questions/1200621/how-to-declare-an-array-in-java
  6. http://stackoverflow.com/questions/1665834/how-can-i-initialize-a-string-array-with-length-0-in-java

Session Management in Java

List of Files

  1. header.jsp
  2. login.jsp
  3. home.jsp
  4. logout.jsp

header.jsp

<a href="login.jsp">Login</a>
<a href="home.jsp">Home</a>
<a href="logout.jsp">Logout</a>

 


login.jsp

 

<%
    HttpSession sess = request.getSession();

    if (sess.getAttribute("sess_username") != null) { // check is session variable exist in session pool or not
        response.sendRedirect("home.jsp"); // if session variable is already set then redirect it to home page else stay on login page
    }
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Login</h1>
        <form action="home.jsp" method="post">
            Username <input type="text" name="username"/><br/>
            Password <input type="password" name="password"/><br/>
            <input type="submit" value="Login"/>
        </form>
    </body>
</html>

 


home.jsp

 

<%
    HttpSession sess = request.getSession(); //get the session object from getSession() method of request object

    if (sess.getAttribute("sess_username") == null) { // check whether the session variable is exist in session pool or not
        sess.setAttribute("sess_username", request.getParameter("username")); // create session variable if it is not present in session pool
    }
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Home</h1>
        <h2>Hello <%=sess.getAttribute("sess_username")%> </h2>
    </body>
</html>

 


logout.jsp

 

<%
    HttpSession sess = request.getSession();
    sess.invalidate(); // this will terminate the session and destroy all variables stored in session pool
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Logout</h1>
    </body>
</html>

 


Display Session variables from pool

Console o/p:

 

Enumeration attributeNames = sess.getAttributeNames();

while (attributeNames.hasMoreElements()) {

    String name = (String) attributeNames.nextElement();

    String value = (String) sess.getAttribute(name);

    out.println(name + "=" + value);

}

 

JSTL(Java Server Pages Standard Tag Library) o/p:

<c:forEach var="session" items="${sessionScope}">

    ${session.key} = ${session.value}

</c:forEach>

 

 

Spring Hibernate Jars

MySQL Connection Jars

http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm

http://www.java2s.com/Code/Jar/m/Downloadmysqlconnectorjava5123binjar.htm

Bcrypt Password Jars

http://www.java2s.com/Code/Jar/s/Downloadspringsecuritycrypto310RELEASEjar.htm