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:

3 comments: