Simple login page using JSP

Today we will see about creating simple login page using JSP. For this tutorial we have used 
  • Eclipse
  • Apache Tomcat (Web Server)
  • Postgres Database

In this example lets start with simple JSP page which will have username and password field with login button. Also wwe have used javascript to validate text fields. In back-end we have created database connection and validating the username and password are valid or not. If its valid then we are returning true else false to the JSP page.

In JSP page if the returned value is true then we are redirecting to success.jsp else displaying error message in same page.

We have done very basic login page which will be understandable for beginners. There are lot and lot of tools and frameworks which we can use and make our web pages more powerful and rich in UI. But we have this taken simple way to start with login page.

To Be Ready with:

i. JDK 1.5 and above should be installed in the machine

ii. Download Eclipse J2EE version according to your machine and OS and install - http://www.eclipse.org/downloads/ 

iii. Download Apache Tomcat web server and install - http://tomcat.apache.org/download-60.cgi

iv. Download and install Postgres database or any other database according to your choice - http://www.postgresql.org/download/

v. Download necessary database driver jar files. In case of Postgres we need to download postgres SQL JDBC driver - http://jdbc.postgresql.org/download.html


Step - 1: Create Dynamic web project in Eclipse

File -> New -> Dynamic Web Project



Step - 2: Add database driver in project Libraries 
Right click Project -> Properties -> Java Build Path -> Libraries -> Add External JARs




Step - 3: Create simple login.jsp 


<%@page import="com.javadiscover.login.LoginValidate"%>
<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Please Login....</title>

<script type="text/javascript">
    function validate_required(field, alerttxt) {
        with (field) {
            if (value == null || value == "") {
                alert(alerttxt);
                return false;
            }
            else {
                return true;
            }
        }
    }

    function validate_Loginform(thisform) {
        with (thisform) {
            if (validate_required(username, "Please enter the username") == false)
            {
                username.focus();
                return false;
            }

            if (validate_required(password, "Please enter the password") == false)
            {
                password.focus();
                return false;
            }
            return true;
        }
    }
</script>
</head>
<body>


<%
 String msg = "";
 String uname = request.getParameter("username");
 String password = request.getParameter("password");
 if(uname != null && password != null && uname.length() > 0 && password.length() > 0){
  LoginValidate obj = new LoginValidate();
  boolean flag = obj.validateUserLogin(uname, password);
  if(flag){
   request.getRequestDispatcher("success.jsp").forward(request, response);
  }else{
   msg = "Invalid username or password";
  }
 }
%>

 <form action="login.jsp" method="post" onsubmit="return validate_Loginform(this)">
  <table width="40%" border="1" align="center">
   <tr>
    <th colspan="2" align="center" valign="top">Please enter login details</th>
   </tr>
   <tr height="50">
    <td valign="middle" align="right">User Name</td>
    <td align="left"><input name="username" size="20" value=""  type="text">
    </td>
   </tr>
   <tr>
    <td valign="middle" align="right">Password</td>
    <td align="left"><input name="password" size="20" value=""  type="password">
    </td>
   </tr>
   <tr height="40">
    <td colspan="2" align="center"><input value="Login" name="B1" type="submit"></td>
   </tr>
  </table>
  
  <br>
  <br>
  <br>
  <br>
  
  <p align="center"> <b><font color="darkred"><%=msg %></font></b></p>

 </form>
</body>
</html>



Step - 4: Create LoginValidate.java page
package com.javadiscover.login;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

/**
 * @author Java Discover
 */
public class LoginValidate {
 
 public boolean validateUserLogin(String uname, String pwd){
  boolean flag = false;
  Connection con = null;
  try{
   con = createConnection();
   if(con != null){
    Statement stat = con.createStatement();
    String qry = "SELECT * FROM tbl_login_master WHERE uname = '"+uname+"' AND password = '"+pwd+"' ";
    ResultSet rs = stat.executeQuery(qry);
    if(rs.next()){
     flag = true;
    }
   }
  }catch (Exception e) {
   e.printStackTrace();
  }finally{
   if(con != null){
    try {
     con.close();
    } catch (SQLException e) {
     e.printStackTrace();
    }
   }
  }
  return flag;
 }
 
 public Connection createConnection() {
  System.out.println("Createung postgres DataBase Connection");
  Connection connection = null;

  try {
   
   // Provide database Driver according to your database
   Class.forName("org.postgresql.Driver");
   
   // Provide URL, database and credentials according to your database 
   connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/mydatabase", "javadiscover","postgres");

  } catch (Exception e) {
   e.printStackTrace();
   return null;
  }
  if(connection != null){
   System.out.println("Connection created successfully....");
  }
  return connection;
 }
}




Step - 5: Create success.jsp 

<%@ 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>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<%
 String uname = request.getParameter("username");
%>
 <h1>Hi <%=uname%>, Successfully Logged in.....</h1>
</body>
</html>



Step - 6: Make sure database and table present in your database

As per above code Database : mydatabase
Table : tbl_login_master
Credentials:
Username: javadiscover
Password: postgres



Step - 7: Start server and test your application by login.jsp page



Project Explorer:



Login Page:



Success Login Page:




Failure Login Page:





Java Interview Questions - 2


Java Interview Questions

In our earlier tutorial we have discussed about few Java interview programming questions. In this tutorial we will discuss on more interview questions.


1. How to run program without main() method?

    By using static block as given below.


    public class MyTestClass {
   
        static{
            System.out.println("Hi, I'm in static block");
        }   
    }



2. Can we call constructor from another constructor?
   
    Yes, we can call by using "this" keyword as given below.

    public class MyTestClass {
   
    public MyTestClass() {       
        this(10);       
    }   
   
    MyTestClass(int i){
        System.out.println("Value : "+i);
    }
   
    public static void main(String[] args) {
        new MyTestClass();
    }   
}



3. What will be the size of HashMap if we place twice same Object in key?

    public static void main(String[] args) {
        MyTestClass obj = new MyTestClass();
        Map<MyTestClass, String> map = new HashMap<MyTestClass, String>();
        map.put(obj, "first");
        map.put(obj, "second");
        System.out.println("Size : "+map.size());       
    }   


   SIZE: 1


4. What will be the size of HashMap if we place 2 Objects of same class in key?
  
    public static void main(String[] args) {
        

        MyTestClass obj = new MyTestClass();
        MyTestClass obj1 = new MyTestClass();
        Map<MyTestClass, String> map = new HashMap<MyTestClass, String>();
        map.put(obj, "first");
        map.put(obj1, "second");
       

        System.out.println("Size : "+map.size());      
    }

  
    SIZE: 2


 5. How to call parametrized method using java reflection?

    Please refer to Java Reflection post for set of reflection related questions and answers.

6. Can we have try block without catch block?
  
    Yes, we can but finally block should be there. Below are the combination of valid and invalid blocks in exception handling.
  
    VALID:
  
    try{
        ....
    }catch(Exception ex){
        ....
    }
    
    try{
        ....
    }finally{
        ....
    }
    
    try{
        ....
    }catch(Exception ex){
        ....
    }finally{
        ....
    }
    
    try{
        ....

    }catch(Exception ex){
        ....
    }catch(Exception ex){
        ....
    }finally{
        ....
    }


    INVALID:
  
    try{
        ....
    }




7. What will be the output of this code?
   
    public class MyTestClass {

        public static void main(String[] args) {
            System.out.println(new MyTestClass().myMethod());
        }
        
        public int myMethod(){
            try{
                int tmp = 5/0;
                return 5;
            }catch (Exception e) {
                return 6;            
            }finally{
                return 10;
            }
        }
    }


    OUTPUT: 10

    method myMethod() will return 10 irrelevant to try or catch blocks. Finally block will be executed always and will return 10.



8. Can we able to override static or private method?

    No, we can not override static or private methods.

9. Will this piece of code work or throws exception?
   
    It will give "null" output, it won't throw any exception.

    public static void main(String[] args) {
      

        HashMap hm = new HashMap();
        hm.put(null,null);
       

        System.out.println(hm.get(null));
    }


    OUTPUT: null
 

10. What is a transient variable?

    If we say in one line, Transient variables will not be serialized.
    For example when we serialize any Object if we need to serialize only few variables and rest should not be serialized then we can use transient keyword to avoid serialization on those variables.

11. Default value assigned to Boolean variable?

    false.

12. Abstract class can be final ?

    No, Class cannot be both final and abstract.

13. Abstract class should have abstract methods?

    No, its not compulsory to have abstract methods. But if there are any abstract method then class must be abstract.

14. Abstract class can have variables?

    Yes can have.

15. Interface can have method definition?

    No, interface can have only method declaration.

16. Interface can have variables?

    Yes, by default it will be static.

17. Interface can be abstract?

    Yes, but we can't have any method definitions.
      

18. How this and super keywords are used?

    this is used to refer to the current object instance and variables.
    super is used to refer to the variables and methods of the superclass of the current object instance.


19. How to Synchronize List, Map and Set?

    By using Collections util class we can Synchronize as given below,

    List<String> list = new ArrayList<String>();
     Set<String> set = new HashSet<String>();
     Map<String, String> map = new HashMap<String, String>();
   
     list = Collections.synchronizedList(list);
     set = Collections.synchronizedSet(set);
     map = Collections.synchronizedMap(map);


20. Why java is not a 100% OOP's?

    Since we have primitive data-types (int, float, double) than complete Objects. Hence we can say it as not 100% OOP's.




 




Java Reflection

In this tutorial we will see about Java Reflection and how to use. Java Reflection is a important topic and need to use only when its necessary in our programming. It deals with class and methods at run-time and as its API we need to include necessary classes in our program.

Java reflection is used in most of application and frameworks. For example JUnit is most commonly used for unit testing by the programmers. Where we used to specify the methods with @Test annotation which will mark to the JUnit as testcase and will be executed automatically by calling corresponding class and methods using Java Reflection.

Lets see small example of Java Reflection by parameter and without parameter.


class MyClass{
 
 public void simpleMethod(){
  System.out.println("Hi, inside simple method...");
 }
 
 public void methodWithStringParam(String name){
  System.out.println("Hi, "+name);
 }
 
 public void methodWithIntParam(int value){
  System.out.println("Value passed : "+value);
 }
 
 public void methodWith2Param(String name1, int value){
  System.out.println("Hi, "+name1+" & "+value);
 }
 
 public String methodWithReturn(){
  return "Java Discover";
 }
}



import java.lang.reflect.Method;
 
public class ReflectionTesting { 
 
public static void main(String[] args)  {
  
  try {
   // Create class instance at runtime
   Class cls = Class.forName("com.test.MyClass");
   Object obj = cls.newInstance();
   
   
   // Calling method simpleMethod() without parameters 
   Class param1[] = {};
   Method method = cls.getDeclaredMethod("simpleMethod", param1);
   method.invoke(obj, null);
  
   
   // Calling method methodWithStringParam() with String parameter
   Class param2[] = new Class[1];
   param2[0] = String.class;
   method = cls.getDeclaredMethod("methodWithStringParam", param2);
   method.invoke(obj, new String("Java Discover"));
   
   
   // Calling method methodWithIntParam() with String parameter
   Class param3[] = new Class[1];
   param3[0] = Integer.TYPE;
   method = cls.getDeclaredMethod("methodWithIntParam", param3);
   method.invoke(obj, 1000);
   
   
   // Calling method methodWith2Param() with String and Integer parameters
   Class param4[] = new Class[2];
   param4[0] = String.class;
   param4[1] = Integer.TYPE;
   method = cls.getDeclaredMethod("methodWith2Param", param4);
   method.invoke(obj, new String("Java Discover"), 2006);
   
   
   // Calling method methodWithReturn() with return 
   method = cls.getDeclaredMethod("methodWithReturn", param1);
   String rValue = (String)method.invoke(obj, null);
   System.out.println("Returned value : "+rValue);
   
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
}



OUTPUT:

Hi, inside simple method...
Hi, Java Discover
Value passed : 1000
Hi, Java Discover & 2006
Returned value : Java Discover




Java Clone()



In this tutorial we will see about Java Clone and how to implement in our coding. Before jumping into coding lets discuss What is Java Clone and how its working.

What is Java Clone?
Clone is nothing but creating a copy of Object with the same state of cloning Object. For example if we clone a Object called "obj1" to "obj2" then new Object will be created with same state and value. There are Shallow copy and Deep copy which we will discuss in our next tutorial.

How its Working?
Suppose if we need to use clone for our class then we need to implement Cloneable interface in our class with clone() method, which will create a copy of super class and return's the Object. Below example will gives you how to use use clone() on user defined class and Collection Objects.



public class MyClass implements Cloneable {

 String name;
 String company;

 public MyClass(String name, String company) {
  System.out.println("Inside Constructor....");
  this.name = name;
  this.company = company;
 }

 public String getName() {
  return this.name;
 }

 public String getCompany() {
  return this.company;
 }

 public Object clone() {
  try {
   MyClass cloned = (MyClass) super.clone();
   return cloned;
  } catch (CloneNotSupportedException e) {
   e.printStackTrace();
   return null;
  }
 }
}




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

  MyClass obj1 = new MyClass("Kamal", "ABC Limited.");

  System.out.println("\nName    : " + obj1.getName());
  System.out.println("Company : " + obj1.getCompany());

  // Cloning the Object
  MyClass obj2 = (MyClass) obj1.clone();

  System.out.println("\nName    : " + obj2.getName());
  System.out.println("Company : " + obj2.getCompany());

  ArrayList<String> arr1 = new ArrayList<String>();
  arr1.add("Java");
  arr1.add("J2EE");
  System.out.println("\nFirst ArrayList  : "+arr1);
  
  ArrayList<String> arr2 = (ArrayList<String>) arr1.clone();
  System.out.println("\nSecond ArrayList : "+arr2);
 }
}



OUTPUT:


Inside Constructor....

Name    : Kamal
Company : ABC Limited.

Name    : Kamal
Company : ABC Limited.

First ArrayList  : [Java, J2EE]

Second ArrayList : [Java, J2EE]




Java Interview Questions


Java Interview Questions

In this tutorial we will see about some basic Java programming questions asked in interview. Below are the list of few questions and along with solution.

  • Reversing a String without reverse() function
  • Add numbers from the given input
  • Count no. of words in the line or paragraph
  • Find Armstrong number or not
  • Find Prime number or not

Reversing a String without reverse() function

public class StringReverse {
 
 public static void main(String[] args) {
  
  String str = "Java Discover";
  System.out.println("Input String : "+str);
  str = myReverseFunction(str);
  System.out.println("Reversed String : "+str);
 }
 
 /**
  * Need to reverse a String without reverse() function
  * @param str
  * @return
  */
 public static String myReverseFunction(String str){
  char[] chars = str.toCharArray();
  StringBuilder sb = new StringBuilder();
  for (int i=str.length()-1;i>=0;i--) {
   sb.append(chars[i]);
  }
  return sb.toString();
 }
}


OUTPUT:


Input String : Java Discover
Reversed String : revocsiD avaJ



Add numbers from the given input
 

public class AddNumerals {
 
 public static void main(String[] args) {
  int value = 1234;
  int output = addNumerals(value);
  System.out.println("INPUT : "+value);
  System.out.println("OUTPUT : "+output);
 }
 
 /**
  * Add numerals in the given param value
  * For example input=1234 then output should be 1+2+3+4=10
  * @param value
  * @return
  */
 public static int addNumerals(int value){
  int output = 0;
  while(value > 0){
   output += value%10;
   value = value/10;
  }  
  return output;
 }
}



OUTPUT:


INPUT : 1234
OUTPUT : 10




Count no. of words in the line or paragraph
 

public class CountWords {

 public static void main(String[] args) {
  String line = "The string tokenizer class allows an application to break a string into tokens";
  int noOfWords = countNoOfWordsInLine(line);
  System.out.println("Input : "+line);
  System.out.println("No Of Words : "+noOfWords);
 }
 
 /**
  * Count no. of words in a line or paragraph 
  * @param line
  * @return
  */
 public static int countNoOfWordsInLine(String line){
  int output = 0;
  StringTokenizer tok = new StringTokenizer(line);
  output = tok.countTokens();
  return output;
 }
}



OUTPUT:


Input : The string tokenizer class allows an application to break a string into tokens
No Of Words : 13




Find Armstrong number or not
 

public class ArmstrongOrNot {
 
 public static void main(String[] args) {
  long input = 54748;
  boolean flag = checkArmstringOrNot(input);
  if(flag){
   System.out.println(input+" is Armstrong number");
  }else{
   System.out.println(input+" is NOT Armstrong number");
  }  
 }
 
 /**
  * Check given number is Armstrong number or not
  * For example, 371 is an Armstrong number, since 3^3 + 7^3 + 1^3 = 371 
  * @param input
  * @return
  */
 public static boolean checkArmstringOrNot(long input){
  int output = 0;
  long tmp = input;
        int length = Long.toString(input).length();
        while(tmp != 0){
         long rem = tmp % 10;
            long tmp1 = 1;
            for(int i = 0; i < length ;i++){
             tmp1 *= rem;
            }
            output += tmp1;
            tmp = tmp/10;
        }
        if(input == output){
            return true;
        }
        return false;
 }
}



OUTPUT:


54748 is Armstrong number




Find Prime number or not
 

public class PrimeOrNot {

 public static void main(String[] args) {
  int input = 23;
  boolean flag = primeOrNot(input);
  if(flag){
   System.out.println(input+" is a Prime number");
  }else{
   System.out.println(input+" is NOT a Prime number");
  }
 }
 
 /**
  * Check whether given number is Prime or Not
  * @param input
  * @return
  */
 public static boolean primeOrNot(int input){
  for(int i=2;i<=input/2;i++){
   if(input%i == 0){
    return false;
   }
  }
  return true;
 }
}



OUTPUT:


23 is a Prime number




More questions will be added shortly. 



Volatile in Java

Volatile is a important topic in Java where we will use in Multi-Threading. Volatile keyword will be used in variables and the value will be changed simultaneously by other threads. This makes compiler to read the value from main memory instead of reading from registers. If we say simply value will not be cached in register. And also this makes each thread to get current value of the variable and each thread will not change values unexpectedly.

The main use of Volatile is stops caching the values of variables in registers. When every time value got changes, immediately flushes the value to RAM where other threads can access the updated value directly.

Here we may think of synchronized which will holds a lock for an Object. Where as here its not suitable since we are just reading and updating value when we use Volatile keyword. Volatile can be applied on Object or Primitive types.

Before Java version 1.5 Volatile is not guarantee the atomicity of a 64-bit long load. For example while thread updating some 64 bit long and other reads can get half of old values and half of new values which will reside in improper value. Later from Java 1.5 onwards atomicity of volatile longs is guaranteed on 64-bit hardware also.

Lets see small example of using Volatile keyword which will works along with Multi Threading.



public class MyVolatile {
 
 static volatile long value = 1234567890L;
 
 public static void main(String[] args) {
  new Thread(new IncrementVolatileValue()).start();
  new Thread(new CheckVolatileValue()).start();
 }
 
 static class CheckVolatileValue implements Runnable{
  @Override
  public void run() {   
   for(int i=0;i<10;i++){
    System.out.println("Value Same : "+value);
   }
  }
 }
 
 static class IncrementVolatileValue implements Runnable{
  @Override
  public void run() {
   for(int i=0;i<10;i++){
    System.out.println("Value Incremented : "+value++);
   }
  }
 } 
}



In above example we are incrementing volatile variable in single Thread and by other Thread we are reading the value and printing in loop for checking the change of value. Both the threads are having its own stack and its own copy of variables in its own memory. Volatile keyword is used to say to the JVM "Warning, this variable can be changed by other Thread" so don't cache it, rather read every time from RAM.

So one who programmer need to decide whether he needs to use Volatile or not according to his business logic's.