Sunday, 26 August 2012

Add a Object of Class using TreeSet

When we add an Object of a class in Using TreeSet then it accept it but when we add  more than one object of a class then it throws an exception because TreeSet is unable to compare those object that are added in it. To overcome this problem we have to implements the Comparable interface in that class that has to be added in the treeset as follows:

1. Create a class Student and implements the Comparable Interface.

public class Student implements Comparable<Student> {
    String name;
    int age;

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

    @Override
    public int compareTo(Student std) {
        int i;
        i = this.age - std.age;
        return i;
    }
    public String toString(){
        return "Name:"+name+" "+"Age:"+age;
    }

}
2. Now Create other class named it TreeSetExample

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class TreeSetExample{
    public static void main(String args[]) throws ClassCastException {
        Set<Student> students = new TreeSet<Student>();

        students.add(new Student("Vikash", 21));
        students.add(new Student("Manohar", 32));
        students.add(new Student("Kittoo", 7));
        Iterator<Student> itr = students.iterator();
        while (itr.hasNext()) {
            Student std = itr.next();
            System.out.println(std);
        }
    }

}

Java Thread

Creating a Thread Example


We can create a thread in two ways:

1. Extends the Thread Class
2. Implements the Thread Interface

1. Creating the Thread extending Thread Class


class Test extends Thread{
    Test(){
    super("Thread One");
    }
}
public class ThreadTest2 {
    public static void main(String args[]){
        Test t=new Test();
      
        System.out.println(t);
    }

}
2. Creating the thread implementing the runnable Interface
When we implement the runnable interface then we must override the run() method.

class MyThread implements Runnable{
    String name;
    int number;
public MyThread(String n,int num) {
    this.name=n;
    this.number=num;
   
}

    @Override
    public void run() {
        System.out.println("Hello");
    }
   
    public String toString(){
        return "Thread Name:"+name+":"+"Number:"+number;
    }
}
public class ThreadTest {
public static void main(String args[]){
    MyThread myThread1=new MyThread("Testing Thread",1);
    myThread1.run();
    System.out.println(myThread1);
}
}

Sunday, 12 August 2012

Spring MVC (Annotation Based)

Annotation Based Spring MVC

Follow the directory structure for Annotation Based Spring MVC
For Eclipse IDE

1.Create a Dynamic Web Project named it Test
2. In SRC folder create the package com.vikash.web
3.Under this create a Class UserController
4. Now come under WebContent Folder uder this create a jsp page index.jsp
5. Under WEB-INF folder create a sub-folder named JSP.
6. Under JSP folder create a jsp page named welcome.jsp

Directory Structure for this Application is as follows:
Test
    |
  SRC
       |
     com.vikash.web
          |
     HelloWorldController.java

 WebComponent
          |
   index.jsp
  WEB-INF
          |
     web.xml-> It's a deployement descriptor file contain the information about servlet mappings.
     vikash-servlet.xml-> Keeps Configuration information contains the information about spring related      configration information.
     JSP-> Contains the jsp pages.
       |
      userPage.jsp
      welcome.jsp

Now follow the following Step:
Step 1:
@Controller
Class HelloWorldController
{
 @RequestMapping(value="/userPage.htm",  method=RequestMethod.GET)
  public ModelAndView userView(HttpServletRequest request)
{
  return new ModelAndView("userPage");
}
  @RequestMapping(value="/welcomePage.htm",  method=RequestMethod.POST)
  public ModelAndView helloWorld(HttpServletRequest request, HttpSession session)
{
  String name=  request.getParameter("name");
  session.setAttribute("name",name);
  return new ModelAndView("welcome");
}
}

Step2: index.jsp- under webcomponent folder parallel to WEB-INF foler.
<%response.sendRedirect("userPage.htm");%>

 Step 3:
Create the jsp page name it userPage.jsp
<html>
<head>
<title>User Page</title>
</head>
<body>

<form action="welcomePage.htm" method="post">
Name:<input type="text" name="name"></br>
<input type="submit" value="Submit">
</body>
</html>

Step 4:
Now, create the jsp page named it welcome.jsp

<html>
<head>
<title>Welcome Page</title>
</head>
<body>
Welcome,<%=session.getAttribute("name");
</body>
</html>
Step 5:
          Add the following lines in the web.xml file

<servlet>
        <servlet-name>vikash</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>vikash</servlet-name>
        <url-pattern>*.htm</url-pattern>
    </servlet-mapping>
 <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
Step 6: Now in the vikash-servlet.xml file add the following lines

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"
    xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
               http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
            http://www.springframework.org/schema/context
               http://www.springframework.org/schema/context/spring-context-3.0.xsd
            http://www.springframework.org/schema/mvc
            http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd">
    <!--This line is for find the main Contoller that handle the request-->
    <context:component-scan base-package="com.vikash.web"></context:component-scan>
    <!-- Declare a view resolver -->
    <bean id="viewResolver"
        class="org.springframework.web.servlet.view.InternalResourceViewResolver"
        p:prefix="/WEB-INF/jsp/" p:suffix=".jsp" />
</beans>

How to run:
Go under the webcontent folder and select the index.jsp and right click on it the select run as ->run on servler option.

Wednesday, 3 August 2011

Simple Java Script Example

<input type="button" value="Cick Me"  onclick="show()">
<script>
function show(){
alert("This is a test");
}
</script>
Here as you see I used <script> means it default treated as <script language="javascript">

Lest See another example..


<html>
<head>
<title>JavaScript Example</title>
</head>
<body>
<table>
<tr><td>Please Enter Your Name:</td><td><input type="text" id="name"></td></tr>
<tr><td>&nbsp; &nbsp;&nbsp;&nbsp;</td><td><input type="button" onClick="test()" value="Click on Me."></td></tr>
</table>
</body>
<script language="javascript">
function test()
{
   var name=document.getElementById('name').value;
   alert("Welcome"+name);
}
</script>
</html>

Simple Hibernate Example

Here I put Simple Hibernate Example.




This is My Fist Program For Hibernate.
Using Eclipse
 It requires three things.
1. Simple bean class
2. Simple Hibernating Mapping Xml file.
3.Hibernate Configuration File.
4. And the one Main class under the scr folder.


In scr folder create the following package.

com.vikash.core.bean
   now ceate the class Student.java
as follows
package com.vikash.core.beans;

public class Student {
long id;
String name;
public long getId() {
    return id;
}
public void setId(long id) {
    this.id = id;
}
public String getName() {
    return name;
}
public void setName(String name) {
    this.name = name;
}

}


create the file student.hbm.xml  at the same place as Student.java resides.
<?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC
    "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
    "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="com.vikash.core.beans.Student" table="STD_TABLE">
<id name="id" type="long" column="ID">
<generator class="assigned"/>
</id>
<property name="name">
<column name="STD_NAME"/>
</property>
</class>
</hibernate-mapping>

now in src folder create the file name hibernate.cfg.xml



<?xml version='1.0' encoding='utf-8'?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">

<hibernate-configuration>
<session-factory>

      <!-- Database connection settings -->

      <property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
      <property name="hibernate.connection.url">jdbc:mysql://localhost:3306/test</property>
      <property name="hibernate.connection.username">root</property>
      <property name="hibernate.connection.password">vikash</property>

         <!-- JDBC connection pool (use the built-in) -->
        <property name="hibernate.connection.pool_size">10</property>

        <!-- SQL dialect -->
          <property name="dialect">org.hibernate.dialect.MySQLDialect</property>

        <!-- Enable Hibernate's automatic session context management -->
   
        <property name="current_session_context_class">thread</property>

        <!-- Disable the second-level cache  -->
        <property name="cache.provider_class">org.hibernate.cache.NoCacheProvider</property>

        <!-- Echo all executed SQL to stdout -->

        <property name="show_sql">true</property>

        <!-- Drop and re-create the database schema on startup -->
   
        <property name="hibernate.hbm2ddl.auto">update</property>
 
  <mapping resource="com/vikash/core/beans/student.hbm.xml" />
    <!--<mapping resource="beans/player.hbm.xml" />
    --></session-factory>
  </hibernate-configuration>

Now create the main class under scr as follows:




import java.util.Iterator;
import java.util.List;
import java.util.Scanner;

import org.hibernate.Query;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;
import org.hibernate.cfg.Configuration;
import org.hibernate.classic.Session;

import com.vikash.test.Employee;


public class MainClazz {
    public static void main(String args[]){

    try{
        Configuration cfg=new Configuration();
        SessionFactory sessionFactory=cfg.configure("/hibernate.cfg.xml").buildSessionFactory();
        session=sessionFactory.openSession();
        Transaction tx=session.beginTransaction();
        Student std=new Student();
        std.setId(System.currentTimeMillis());
        std.setName("Manohar Kumar");
        session.save(std);
        tx.commit();
        }catch(Exception e){
            e.printStackTrace();
        }
        finally{
            if(session!=null)
                session.flush();
                session.close();
              
        }
         }
    }
   
   
If any query then let me know.