Friday, July 22, 2016

Pass parameters from one JSP to another JSP

To do this, you need to add jsp:include and its jsp:param properties .

First.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Pass Parameters from one JSP to another JSP Page</title>
</head>

<body>
      This is your First JSP page.

    <jsp:include page="Second.jsp">
        <jsp:param name="param1" value="Firstvalue"/>
        <jsp:param name="param2" value="Secondvalue"/>
    </jsp:include>
</body>
</html>

Second.jsp
<%@ page language="java" contentType="text/html;charset=UTF-8" %>
<html>
<head>
    <title>Pass Parameters Example</title>
</head>

<body>
    This is your second JSP page.
    param1: <%= request.getParameter("param1") %>
    param2: <%= request.getParameter("param2") %>
</body>
</html>

Explanation :

1.You have to include Sceond.jsp in the First.jsp page.

2. Use jsp:include property, jsp:param to pass parameter to the Second.jsp which was already included with the help of jsp:include.

3.Retrieve the passed values from First.jsp through getParameter method.

SubQuery for Beginners

Sub query  - Embedding a SQL statement within another SQL statement. It can be used with sql comparison operators like =,<.>,<=,>= etc.,

Additionally, we can write with LIKE IN, NOT IN, ANY and IN operators. Now you may have question when we have to use LIKE IN etc., and comparison operators while writing query.

Things to remember:

1. Sub query may return one row or more than one row.
2. If it will return more than one row then you should use IN operator.
3.It must be enclosed with parenthesis.
4. You can not use ORDER BY in sub query. Instead of that, you can use GROUP BY.


Sub Query Format:

SELECT "column_name1"
FROM "table_name1"
WHERE "column_name2" [Comparison Operator] or [LIKE IN, ANY etc.,]
(SELECT "column_name3"
FROM "table_name2"
WHERE "condition");

Highlighted in blue color is inner query and highlighted in red color is called outer query. Let see the example one by one, so that we able to understand more clearly.

Example I: Sub Query with IN operator

ID     NAME  AGE PLACE     SALARY  

  1     Rajesh     35    Chennai       2000.00
  2     Velava     25    Mumbai       1500.00
  3     kajol        23    Hyderabad   2000.00
  4     Mukesh   24    Madurai       10000.00

Sub Query:

SELECT * 
FROM CUSTOMERS 
WHERE ID IN (SELECT ID 
             FROM CUSTOMERS 
             WHERE SALARY > 1800) ;

Output:

 ID   NAME      AGE  PLACE      SALARY  

  1     Rajesh        35     Chennai          2000.00 
  3     kajol           23     Hyderabad      2000.00 
  4     Mukesh      24     Madurai        10000.00 


Note: Above query uses IN operator, due to inner query will return more than one rows.

Sub Query with Comparison Operator


        student                                     marks
Student Id         Name                                 Student Id                 Marks      
     1                Kalpana                                       1                               91
     2                Peter                                             2                               89
     3                Rajini                                           3                               97
     4                Ajith                                             4                               96 
     5                Vijay                                             5                               95

Ok, Now the question is , How to identify all students who get high marks than one of the student who`s id is 5. Here, you don't know marks of student id 95.

So we can split this question as two,
 1. What s the mark of student Id 95 ? (95Marks)
 2. Who are all getting high marks than studetn Id 95 marks? (>95 Marks)

For 1st question, query is below,

Select * from marks
where student_id = '5'

Output:

Student Id     Marks
       5                  95

Now second question, query is below,

Select a1.student_id,a1.name,m1.marks 
from student s1, marks m1
where s1.student_id = m1.student_id
AND m1.marks > 95

Output:

studentId     name       marks
3                   Rajini         97
4                   Ajith           96

Now combine these two query, 

SELECT a.studentid, a.name, b.marks  
FROM student a, marks b  
WHERE a.studentid = b.studentid AND b.marks >  
(SELECT marks  
FROM marks  

WHERE studentid =  '95');  

Output:

studentId     name       marks
3                   Rajini         97
4                   Ajith           96

Thursday, July 21, 2016

JAVA Generics

Java Generics is similar to C++ Templates. You can write a code with Generics for methods, classes and interfaces. Let see one by one. 

Generics Class
To create Generics class we have to use < >. The most commonly used type parameter names are:

E - Element (used extensively by the Java Collections Framework)
K - Key
N - Number
T - Type
V - Value
S,U,V etc. - 2nd, 3rd, 4th types

To know more please visit here. Ok,

Example code:

// Use < > to specify Parameter type
class JavaHit<T>
{
 // An object of type T is declared
 T obj;
 JavaHit(T obj) { this.obj = obj; } // constructor part
 public T getObject() { return this.obj; }
}

//To test above I used this class
class Main
{
 public static void main (String[] args)
 {
  // For Integer type
  JavaHit <Integer> integerObj = new JavaHit<Integer>(37);
  System.out.println(integerObj.getObject());

  // For String type
  JavaHit <String> stringObj = new JavaHit<String>("TestForString");
  System.out.println(stringObj.getObject());
 }
}

Output:
37
TestForString

From the above code , you able to understand you can pass any wrapper like Integer , Float etc.,

Multiple Type Parameters

// Use < > to specify Parameter type
class JavaHit<T, U>
{
 T obj1; // An object of type T
 U obj2; // An object of type U

 // constructor
 JavaHit(T obj1, U obj2)
 {
  this.obj1 = obj1;
  this.obj2 = obj2;
 }

 // To print objects of T and U
 public void print()
 {
  System.out.println(obj1);
  System.out.println(obj2);
 }
}

// To test above I used this class
class Main
{
 public static void main (String[] args)
 {
  JavaHit <String, Integer> obj =
   new JavaHit<String, Integer>("TestForString", 37);

  obj.print();
 }
}

Output
TestForString
37

Generics Functions:
In nutshell, you can pass here, different types of arguments. Let see code below.

// Generic functions

class Test
{
 
 static <T> void genericParameterDisplay (T typeofelement)
 {
  System.out.println(typeofelement.getClass().getName() +
      " = " + typeofelement);
 }
 
 public static void main(String[] args)
 {
  // Calling generic method for Integer
  genericParameterDisplay(37);

  // Calling generic method for String
  genericParameterDisplay("TestForString");

  // Calling generic method for double
  genericParameterDisplay(10.02);
 }
}

Output:
37
TestForString
10.02

Generics Advantages :

1. Code Reuse.
2. Type safety
3. No need Type casting

Wednesday, July 20, 2016

Ajax - Tutorial Part I - Your First program

Ajax -Introduction

Ajax (Asynchronous JavaScript and XML )is not a programming language, Its a script. It will update parts (div) of the web page, without reloading the whole page. For example, selecting drop down values.

So it will make web page as Fast and Dynamic and It supports asynchronous operation.

Synchronous: We can send single request at a time and need to wait to get the response before sending second request.

Asynchronous: It will support to send second request before receiving the response of first request. Ajax will support asynchronous. So that its good for web applications.

You must know, JavaScript, CSS and little bit knowledge of xml to work with Ajax.


How to create XMLHttpRequest Object ?

Almost all modern browsers have built-in with XmlHttpRequest object. But older version like IE5 and IE6 will not support this. So in this case you should use ActiveX object.

Let see the syntax ,


variable = new XMLHttpRequest(); // Latest Browsers


variable = new ActiveXObject("Microsoft.XMLHTTP"); // Old Browsers

Methods of XmlHttpRequest

Method Description
abort Abort was introduced in Internet Explorer 7. The abort method interrupts an asynchronous operation in progress.

getAllResponseHeaders Returns all the response headers, separated by CRLF, as a string, or null if no response has been received.

getResponseHeader Returns the string containing the text of the specified header, or null if either the response has not yet been received or the header doesn't exist in the response.

open Initializes a request. This method is to be used from JavaScript code; to initialize a request from native code, use openRequest() instead.

overrideMimeType Overrides the MIME type returned by the server.

send Sends the request. If the request is asynchronous (which is the default), this method returns as soon as the request is sent..

setRequestHeader Sets the value of an HTTP request header. You must call setRequestHeader()after open(), but before send().


Apart from these, some non standra method also there. Please refer Here .


Properties of XMLHTTPrequests


Below are the properties of XmlHttpRequest.

1. onreadystatechange - This property sets the method to be called on every state change. This is usually your event handler for the asynchronous callback.

2. ReadyState - It will defines the state of the XmlHttpRequest.Possible values include:


        0 Uninitiated
        1 Loading
        2 Loaded
        3 Interactive
        4 Complete

When sending XmlHttpRequest, check to see if the readyState is 0 or 4, and while asynchronous callback handler, will check to see if readyState is 4.

3. responseText - Returns a DOMString that contains the response to the request as text, or null if the request was unsuccessful or has not yet been sent.

4. responseXML - Returns a Document containing the response to the request, or null if the request was unsuccessful, has not yet been sent, or cannot be parsed as XML or HTML.

5. Status - Returns an unsigned short with the status of the response of the request.

6. statusText - Returns a DOMString containing the response string returned by the HTTP server. Unlike XMLHTTPRequest.status, this includes the entire text of the response message ("200 OK", for example).

Apart from these, lot of properties available , Please refer Here.

Ajax simple program

Below are simple ajax program, let see the code and explanation. Just create one html file and text file and keep the same in under same directory.

<html>
<head>
<script type="text/javascript">
function ajaxFirst()
{
var a;
 
    if (window.XMLHttpRequest)
    {// If the browser if IE7 or Firefox or Chrome or Opera or Safari (Modern Browsers)
      a=new XMLHttpRequest();
    }
   else
    {//If browser is IE6, IE5 (Old Browsers)
      a=new ActiveXObject("Microsoft.XMLHTTP");
    }
 
a.onreadystatechange=function()
{
  if (a.readyState==4 && a.status==200)
  {
    document.getElementById("myDiv").innerHTML=a.responseText;
   }
}
 
a.open("POST","sample.txt",true);
a.send();
} // ajaxFirst() close
</script>
</head>
<body>
 
<div id="myDiv" style="width: 300px; height: 30px;">Please click on below button</div>
<button type="button" onclick="ajaxFirst()">Change Content Here</button>
 
</body>
</html>
Code Explanation :

1. When the button is clicked , onClick event will call ajaxFirst() javascript method.
2. If your browser is modern like latest, then it will create XmlHttpRequest, else ActiveXObject will be created.
3. Next it will open a connection and send the request your sample text file. True parameter mentioned here, you are enabling Asynchronous operation.
4. Then send method will send the request.
5. After receiving response from server, it will execute onreadystatechange automatically.
6. Readystate 4 mentioning , it is completed and 200 status code mentioning response is success.

Tuesday, July 19, 2016

How to create Immutable class in java?

Most of the interview, we can expect this question. In Nutshell, java have lot of immutable classes like String, Integer, Float etc.,

Please remember below points to make your class as immutable.
  • Make your class as Final, So that other can not extends it, means cannot create sub class. 
  • Declare instance variable as Final with private modifier, so that it can not change once initiated.
  • Don't implement setter methods.
  • Finally, don't provide any method which will change the behavior of state of the object.

Example :

public final class JavaHit{ 
    final String name;  
  
public JavaHit(String name){  
    this.name=name;  
  }  
  
public String getName(){  
    return name;  
  }    


Benefits of Immutable class:
  • It will be helpful in synchronization environments, since its thread-safe.
  • Internal state of immutable class will be fine, even you get any exception.
  • It will be good to work with Map Keys and set elements, since typically it will not change once its created.