Sunday, 3 February 2013

User validation using Sevlet and Ajax with DatabaseServlet, Jquey and Database

Here I'm Posting very Interesting and useful to validate a user using Servlet, ajax and jquery using database.

Download file a js file: jquery-1.3.2.js from here: http://jquery.com/download/

First Step:
1. Create a table user
                                  create table user(username varchar(30), password varchar(10));



2. Create a login page:

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Login Page</title>
<script type="text/javascript" src="js/jquery-1.3.2.js"></script>
<script type="text/javascript">

var x="<%=session.getMaxInactiveInterval()%>";


    function sendAjax()
    {
        var userName= $('#userName').val();
        var url='login';
        $.post("login",{userName:userName},showAlert);
    }

function showAlert(data)
{

    //if(data!=null && data!='NotFound'){
        if(data=="found"){
    $('#message').html('Congratulations! Correct user name')
    $('#message').css({"color":"white", "background-color":"green"});
    }
    else{
      
        $('#message').html('User Details Not Found!')
        $('#message').css({"color":"white", "background-color":"red","font-weight":"bold"});
        }
}
</script>
</head>

<body>
<form action="login" method="post">
<h1>Login Page!</h1>
<table>
    <tr>
        <td>Please enter your userName:</td>
        <td>
        <td><input type="text" name="userName"  id="userName" onchange="sendAjax();"></td><td><span  id="message" ></span></td>
    </tr>
    <tr>
        <td>Please enter Your password:</td>
        <td>
        <td><input type="password" name="pass"></td>
    </tr>
    <tr>

        <td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;</td>
        <td><input type="button" value="submit" onclick="sendAjax()"></td>
    </tr>
</table>
<div id="mm"></div>
</form>
</body>
</html>

1. Create a bean class for user information.

package com.vikash.model;

public class Bean {
String firstName;
String lastName;
public String getFirstName() {
    return firstName;
}
public void setFirstName(String firstName) {
    this.firstName = firstName;
}
public String getLastName() {
    return lastName;
}
public void setLastName(String lastName) {
    this.lastName = lastName;
}
}


 2. create a class DAOImpl


package com.vikash.service;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import com.vikash.model.Bean;

public class DAOImpl {
    static Connection con = null;
    static ResultSet resultSet = null;
    static ResultSet resultSet2 = null;
    static Statement stat = null;
    public String firstName;
    public String lastName;
    Bean bean=new Bean();
    Map<String,Bean>myModel=new HashMap<String,Bean>();
    static PreparedStatement preparedStatement;
    static PreparedStatement preparedStatement2;
    public static void main(String args[]) throws SQLException {
        Map<String, Bean>map=new HashMap<String,Bean>();
        DAOImpl dImpl=new DAOImpl();
        Bean bean=new Bean();
        map=dImpl.getDetails("vikash", "kumar");
        Set<Map.Entry<String, Bean>> set=map.entrySet();
        Iterator<Map.Entry<String, Bean>>itr=set.iterator();
        //Map.Entry<String, Bean>me=map.entrySet();
        while(itr.hasNext()){
            bean=itr.next().getValue();
        }
        System.out.println("First Name:"+bean.getFirstName());
        System.out.println("Last  Name:"+bean.getLasName());
    }

    public Map<String,Bean> getDetails(String userName, String pass) throws SQLException {
      
        String query = "select * from user where username='" + userName
                + "' AND pass='" + pass + "'";
        String query2="select * from user where username=?";
        String query3="update table user set lastname=singh where lastname=?";
        System.out.println(query);
      
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost/joining",
                    "root", "vikash");
            preparedStatement = con.prepareStatement(query2);
            preparedStatement.setString(1, userName);
            resultSet = preparedStatement.executeQuery();
            if (resultSet.next()) {
                bean.setFirstName(resultSet.getString(1));
                bean.setLasName(resultSet.getString(2));
                myModel.put("model", bean);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // TODO: handle exception
        }
        return myModel;
    }
}

4. Create a class Login Serlvet


package com.vikash.web;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.vikash.service.DAOImpl;

public class LoginServlet extends HttpServlet {
    /**
     *
     */
    public LoginServlet(){
        System.out.println("Login Servlet Invoked");
    }
    private static final long serialVersionUID = 1L;
    public void doPost(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException {
        PrintWriter out=response.getWriter();
        DAOImpl dImpl = new DAOImpl();
        String userName = request.getParameter("userName");
        String pass = request.getParameter("pass");
        Map<String, Bean>myMap=new HashMap<String, Bean>();
        try {
            if (dImpl.getDetails(userName, pass).size()>0) {
                HttpSession httpSession = request.getSession(true);
                myMap=dImpl.getDetails(userName, pass);
                out.print("found");
            }
            else{
                out.print("NotFound");   
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    System.out.println(userName);
   
    }
public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doPost(request, response);
    }

// This is for testing purpose
public static void main(String args[]) throws SQLException{
    DAOImpl dImpl = new DAOImpl();
    Map<String, Bean>myMap=new HashMap<String, Bean>();
    myMap=dImpl.getDetails("vikash", "kumar");
    System.out.println("gggggg:"+myMap.get("model").getFirstName());
}
}


output:

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);
}
}