Great Deals

Array Declaration in java :)

 

I am gonna discuss about various possibilities in which array can be declared.

String[] empNames []; Correct
String[][][] professions; // Correct


int[5] salaries;//Wrong
Remember JVM wont allocate size until oyu create objects.

HOw to create the array of type String.
int[] items; // Declares the array of ints
items= new int[4]; // constructs an array and assigns it
// to the testScores variable

  • Create an array of size four and assign the reference to "items" variable.

Array must be given size explicitely.
int[] list=new int[];//Not allowed
_________________________
Create multidimenstional Array
_________________________________

int[][] myArray = new int[3][];
Notice that first bracket carry size.This means it is a array that will hold refernce to other arrays.

int[ ][ ] myArray = new int[3][ ];
myArray[0] = new int[2];
myArray[0][0] = 6;
myArray[0][1] = 7;
myArray[1] = new int[3];
myArray[1][0] = 9;
myArray[1][1] = 8;
myArray[1][2] = 5;


Onother example
Car [] cars = new Car[3];
cars[0]=new Car(); //Will Work
cars[4]=new Car(); //Will not Work.will give ArrayIndexOutOfBoundException.
cars[3]=3 // Runtime exception. There is no element at index

 One Line intialization
int x = 9;
int[] items = {6,x,8};//Length determined by number of values in "items".

Shortcut for Creating multidimensional array.
int[][] items = {{5,2,4,7}, {9,2}, {3,4}};

items[0] ///contains 5,2,4,7
items[0][1] output 2


Anonymous Array creation

Correct ->      

int[] items;
items = new int[] {4,15,2};

This implies first refernce is created and then it points to anonymous array with items {4,15,2}

InCorrect->    

 int[] items;
items = new int[3] {4,15,2};//Not allowed.


When creating anonymous array we never specify the item size in advance it will be calculated by number of items in the comma seperated list.

YOu can't assign 2 d array to 1 d array.

int[] screen;
int[][] multiplex = new int[3][];
screen = multiplex ;

  • Static block and init block

Static block: initializes static variable.Static block initializes only once.

Init block: inits instance variables.Init block runs evry time when instance of class is created..
class SmallInit {
static int x;
int y;
static { x = 7 ; } // static init block
{ y = 8; } // instance init block
}
>>Init blocks runs after the all constructors got executed.



RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()

Get Free Book :)
  • RequestDispatcher.forward() vs HttpServletResponse.sendRedirect()
    _______________________________________________________________
    RequestDispatcher.forward()
    _______________________________________________________________

    1.When we use forward method, request is transfer to other resource within the same server.

    2.client or browser is not involved.

    3.When forward is called on requestdispatcher object we pass request and response objects so our old request object is passed on for further processing.

    4.ON browsers url you cant see that address.

    5. forward () method is faster then send redirect.

    _______________________________________________________________
    SendRedirect
    _________________________________________________________________
  • 1.request is transfer to another resource to different server for further processing.

  • 2.Url is visible on the browser.

  • 3.In case of sendRedirect call, old request and response objects are lost because it’s treated as new request by the browser.

  • 4.In address bar, we are able to see the new redirected address.

    5.sendRedirect is slower because one extra round trip is required, because completely new request is created and old request object is lost. Two browser request required.

  •  

 



Producer Consumer Problem in java


 import java.util.Vector;
 import java.util.logging.Level;
 import java.util.logging.Logger;

public class ProducerConsumerSolution {
     public static void main(String args[]) {
         Vector sharedQueue = new Vector();
         int size = 4;
         Thread prodThread = new Thread(new Producer(sharedQueue, size), "Producer");
         Thread consThread = new Thread(new Consumer(sharedQueue, size), "Consumer");
         prodThread.start();
         consThread.start();
     }
 }

 class Producer implements Runnable {

     private final Vector sharedQueue;
     private final int SIZE;

     public Producer(Vector sharedQueue, int size) {
         this.sharedQueue = sharedQueue;
         this.SIZE = size;
     }

     @Override
     public void run() {
         for (int i = 0; i < 7; i++) {
             System.out.println("Produced: " + i);
             try {
                 produce(i);
             } catch (InterruptedException ex) {
                 Logger.getLogger(Producer.class.getName()).log(Level.SEVERE, null, ex);
             }

         }
     }

     private void produce(int i) throws InterruptedException {

         //wait if queue is full
         while (sharedQueue.size() == SIZE) {
             synchronized (sharedQueue) {
                 System.out.println("Queue is full " + Thread.currentThread().getName()
                                     + " is waiting , size: " + sharedQueue.size());

                 sharedQueue.wait();
             }
         }

         //producing element and notify consumers
         synchronized (sharedQueue) {
             sharedQueue.add(i);
             sharedQueue.notifyAll();
         }
     }
 }

 class Consumer implements Runnable {

     private final Vector sharedQueue;
     private final int SIZE;

     public Consumer(Vector sharedQueue, int size) {
         this.sharedQueue = sharedQueue;
         this.SIZE = size;
     }

     @Override
     public void run() {
         while (true) {
             try {
                 System.out.println("Consumed: " + consume());
                 Thread.sleep(50);
             } catch (InterruptedException ex) {
                 Logger.getLogger(Consumer.class.getName()).log(Level.SEVERE, null, ex);
             }

         }
     }

     private int consume() throws InterruptedException {
         //wait if queue is empty
         while (sharedQueue.isEmpty()) {
             synchronized (sharedQueue) {
                 System.out.println("Queue is empty " + Thread.currentThread().getName()
                                     + " is waiting , size: " + sharedQueue.size());

                 sharedQueue.wait();
             }
         }

         //Otherwise consume element and notify waiting producer
         synchronized (sharedQueue) {
             sharedQueue.notifyAll();
             return (Integer) sharedQueue.remove(0);
         }
     }
 }






Oveririding rules


Rules for overriding
  • The access level can't be more restrictive than the overridden method's.
  • class Car {
        String message = "Car";
        <T> void horn() throws Exception {
            System.out.println(message);
        }
    }

    class Mercedez extends Car {
        String message = "child";
         void horn() throws IOException {
            System.out.println(message);
        }
    }
  • Compiles  fine
  • class Car {
        String message = "Car";
        public void horn() throws Exception {
            System.out.println(message);
        }
    }

    class Mercedez extends Car {
        String message = "child";
         private void horn() throws IOException {
            System.out.println(message);
        }
    }
  • Not Allowed
  • class Car {
        String message = "Car";
         void horn(){
            System.out.println(message);
        }
    }

    class Mercedez extends Car {
        String message = "child";
        <T> void horn(){
            System.out.println(message);
        }
    }
  • Not Allowed 
  • class Car {
        String message = "Car";
        Number horn(){
            return 1;
        }
    }

    class Mercedez extends Car {
        String message = "child";
        Integer horn(){
            return 2;
        }
    }


    public class OverridingWithException {    
        public static void main(String[] args) {
         Car c=new Mercedez();
         System.out.println(c.horn());
        }
    }
  • Output: :2
  • The access level CAN be less restrictive than that of the overridden method.
  • private, static and final methods can't be overridden
  • Return type of method is never part of method signature, so only changing the return type of method does not mean overloading
  • Overriding method can not throw checked Exception higher in hierarchy than thrown by overridden method.  
  • class Car {
        String message = "Car";
  • //Overriden method

        void horn() throws NoHornException {
            System.out.println(message);
        }
    }

    class Mercedez extends Car {
        String message = "child";
  • //Overriding method

         void horn() throws NoBreakException {
            System.out.println(message);
        }
    }
    class NoHornException extends Exception {
    }

    class NoBreakException extends NoHornException {
    }

    public class OverridingWithException {    
        public static void main(String[] args) {
          try {
            new Mercedez().horn();
        } catch (NoBreakException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        }
    }
  • which overridden method to call based on object type  
  • import java.io.FileNotFoundException;
    import java.io.IOException;
    class Parent {
        String message = "parent";
        void say() {
            System.out.println(message);
        }
    }

    class Child extends Parent {
        String message = "child";
        void say() {
            System.out.println(message);
        }
    }

    public class OverridingWithException {
        public static void main(String[] args) {
            Parent p=new Child();
           
            p.say();
        }
    }
    Output is CHILD 
      
  • class Car {
        String message = "Car";
        void horn() throws Exception{
            System.out.println(message);
        }
    }

    class Mercedez extends Car {
        String message = "child";
         void horn() throws IOException,FileNotFoundException{
            System.out.println(message);
        }
    }
    Compiles fine

  • Imagine Base class car references Object of derived class 
    and invokes the method in base class then the call is made 
    and base class method invoked.
    class Car {
        String message = "Car";
        void horn() {
            System.out.println(message);
        }
    }
    
    class Mercedez extends Car {
        String message = "Mercedez ";
        /*void horn() {
            System.out.println(message);
        }*/
    }
    
    
    public class OverridingWithException {  
        public static void main(String[] args) {
            Car yo = new Mercedez();
            yo.horn();
        }
    }
    Output:Car
    But if i uncomment methodin Mercedez then
    Output:Mercedez

_________________________________________________________________________
 
class Car {
    String message = "Car";
    static void horn() {//NOT ALLOWED
        System.out.println(message);
    }
} 
class Mercedez extends Car {
    String message = "Mercedez ";
    /*void horn() {
        System.out.println(message);
    }*/
}


public class OverridingWithException {  
    public static void main(String[] args) {
        Car yo = new Mercedez();
        yo.horn();
    }
}
 ___________________________
class Animal {
   public void eat() {
    System.out.println("Generic Animal Eating Generically");
 }
}
class Horse extends Animal {
    public void eat() {
       System.out.println("Horse eating hay, oats, "
                                + "and horse treats");
    }
    public void fight() { }
   }
}

In the preceding code, the test class uses an Animal reference to invoke a method on a Horse object. Remember, the compiler will allow only methods in class Animal to be invoked when using a reference to an Animal. The following will not be alllowed:
Animal c = new Horse(); c.fight(); // Can't invoke fight(); // Animal class doesn't have that method ****The overriding method can throw any unchecked excpetion regardless of what exception overridden method is throwing.
Overriding Puzzle
class Animal {
public void eat() {
System.out.println("Generic Animal Eating Generically");
}
}
class Horse extends Animal {
public void eat() {
System.out.println("Horse eating hay, oats, "
+ "and horse treats");
}
public void fight(String weapon) { 

}
}

public class TestA {
public static void main(String[] args) {
Animal a=new Animal();
a.eat();
Animal aObj=new Horse();
aObj.fight("Nails");//Compiler Error it looks for the reference Animal for definition of fight() and it wont get So Error

Horse h=new Horse();
h.fight("Nails");//Allowed
}
}
Overriding method can not throw checked Exception higher in hierarchy than thrown by overridden method.  
Lets take one example
class Car
{
 public void accelarate() throws Exception
 {
  //Throw exception
  
 }
}
class Mercedez extends Car
{
 public void accelarate(){  //No exceptions
  
 }
 
}
public class OverridingWithException extends Animal{

 public static void main(String[] args) {
Car c=new Mercedez();
Mercedez carObj=new Mercedez();
carObj.accelarate();//THis is fine
c.accelarate();//Will throw exception. 
//since the derived class Mercedez does not thorws exception it is not valid
 }

}
If class Mercedez defines a method throws 
checked Exception not defined by class Car
Then it is not allowed. 
  
 
import java.io.FileNotFoundException;
import java.io.IOException;

class Car
{//Overriden method
 public void accelarate() throws FileNotFoundException
 {
  //Throw exception
  
 }
}
class Mercedez extends Car
{
 //Overriding method
 public void accelarate() throws IOException{  //No exceptions
  
 }
 
} 

Puzzles about cobstructor


Hi here I come again with puzzle about constructor.
As we know if we don't create constructor it is by default created .
But imagine a situation where you have created parameterized constructor??????
Let's take a look at following code snippet
Class A
{ A(int a){ }
}
Class B extends A
{
   }
class c extends B
{
  //Now imagine a situation where you need to call a parameterized constructor of A.
Probably you will choose
A a=new A(5);
}
Wait!!!!!!!!!!!!!!
I would like to take a stand and say no!!!.
Because if there is any parameterized constructor then you need to put default constructor manually.
So the redefination of class A goes like this
Class A
{ A(){
        }
   A(int a){
    }
}

Implement your own logging framework


How to implement your own logging operation
import java.lang.ref.WeakReference;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.ReflectPermission;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.ResourceBundle;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.function.Supplier;
import java.util.logging.Handler;
import java.util.logging.Level;
import java.util.logging.LogManager;

import javax.swing.JApplet;
//import sun.reflect.CallerSensitive;
//import sun.reflect.Reflection;


class Driver
{
 
String name;

public String getName() {
 return name;
}

public void setName(String name) {
 this.name = name;
}

}
class Car
{
 
String name;

public String getName() {
 return name;
}

public void setName(String name) {
 this.name = name;
}

}
public class MyLogger {//extends java.util.logging.Logger {
/*
 protected MyLogger(String name, String resourceBundleName) {
  super(name, resourceBundleName);
  // TODO Auto-generated constructor stub
 }
 
  /*******Function print array basically gets the name of methods present in the class using 
Element.getClass().getMethods().
After getting name of it uses method.invoke function to invoke the getter methods.
In this way we access getter methods.
    
 
  // generic method printArray                         
 public  < E > void printArray( List inputArray )
 {
  // Display array elements   

  for ( E element : inputArray ){    
    Method[] methods= element.getClass().getMethods();
    for(Method method:methods)
    {String name=method.getName();
     if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
       try {

     try {
      
      System.out.println("%%"+method.invoke(element,null) );
     } catch (IllegalAccessException | InvocationTargetException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }
        } catch (IllegalArgumentException e) {
     // TODO Auto-generated catch block
         e.printStackTrace();
        }/* catch (IllegalAccessException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
     }*/
     }
    }
  }

   // System.out.println();
   }
    public static void main(String[] args) {
     MyLogger myObj=new MyLogger();
     String s[]=new String[]{"Suresh","Chaudhari"};
     List driverList=new ArrayList();
     Driver drr=new Driver();
     drr.setName("YUI");
     Driver dr2=new Driver();
     dr2.setName("raman");
     driverList.add(drr);
     driverList.add(dr2);
     
     List carList=new ArrayList();
     Car cr1=new Car();
     cr1.setName("D");
     Car cr2=new Car();
     cr2.setName("R");
     carList.add(cr1);
     carList.add(cr2);
     
     //myObj.printArray(s);
     myObj.printArray(driverList);
     myObj.printArray(carList);
 }

}


Post about using reflection to get values of private members


import java.io.IOException;

import java.lang.annotation.Retention;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.SQLException;
import java.util.Arrays;
import java.util.Comparator;
import java.lang.annotation.RetentionPolicy;

/**Using reflection how to get values of member of class please go throught the code
**/
public class Student {

private String grade;

private String name;

private String id;

private String gender;

private Method[] methods;

@Retention(RetentionPolicy.RUNTIME)
public @interface Order {
    int value();
}

/**
 * Sort methods as per Order Annotations
 * 
 * @return
 */
private void sortMethods() {

 methods = Student.class.getMethods();

    Arrays.sort(methods, new Comparator() {
        public int compare(Method o1, Method o2) {
            Order or1 = o1.getAnnotation(Order.class);
            Order or2 = o2.getAnnotation(Order.class);
            if (or1 != null && or2 != null) {
                return or1.value() - or2.value();
            }
            else if (or1 != null && or2 == null) {
                return -1;
            }
            else if (or1 == null && or2 != null) {
                return 1;
            }
            return o1.getName().compareTo(o2.getName());
        }
    });
}

/**
 * Read Elements by Using method.invoke functionality
 * 
 * @return
 */
public void readElements() {
    int pos = 0;
    /**
     * Sort Methods
     */
    if (methods == null) {
        sortMethods();
    }
    for (Method method : methods) {
        String name = method.getName();
        if (name.startsWith("get") && !name.equalsIgnoreCase("getClass")) {
            pos++;
            String value = "";
            try {
                value = (String) method.invoke(this);
            }
            catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
                e.printStackTrace();
            }
            System.out.println(name + " Pos: " + pos + " Value: " + value);
        }
    }
}
// /////////////////////// Getter and Setter Methods

/**
 * @param grade
 * @param name
 * @param id
 * @param gender
 */
public Student(String grade, String name, String id, String gender) {
    super();
    this.grade = grade;
    this.name = name;
    this.id = id;
    this.gender = gender;
}

/**
 * @return the grade
 */
@Order(value = 4)
public String getGrade() {
    return grade;
}

/**
 * @param grade the grade to set
 */
public void setGrade(String grade) {
    this.grade = grade;
}

/**
 * @return the name
 */
@Order(value = 2)
public String getName() {
    return name;
}

/**
 * @param name the name to set
 */
public void setName(String name) {
    this.name = name;
}

/**
 * @return the id
 */
@Order(value = 1)
public String getId() {
    return id;
}

/**
 * @param id the id to set
 */
public void setId(String id) {
    this.id = id;
}

/**
 * @return the gender
 */
@Order(value = 3)
public String getGender() {
    return gender;
}

/**
 * @param gender the gender to set
 */
public void setGender(String gender) {
    this.gender = gender;
}

/**
 * Main
 * 
 * @param args
 * @throws IOException
 * @throws SQLException
 * @throws InvocationTargetException
 * @throws IllegalArgumentException
 * @throws IllegalAccessException
 */
public static void main(String args[]) throws IOException, SQLException, IllegalAccessException,
        IllegalArgumentException, InvocationTargetException {
    Student student = new Student("A", "Anand", "001", "Male");
    student.readElements();
}
}


Serialization

1.If class B is implementing serializable and it holds reference of class A which is not serialized then NonSerializable exception will be thrown at runtime.
>
Class A{}
 Class A implements Serializable
 {
  B b;
 }
2.When Object is deserialized it does not invoke the constructor. Reson is when we deserialize the Object we need to know it actual state but if constructor is called it will be changed to the default state objects. suppose
 class A
 {
 int a;
  A(int a)
  {
   this.a=a=3;//if constructor called in deserialization then value will be 3 which is inappropriate
  }
  changeA()
  {
  this.a=5;//here value is changed to 5
  }
}
4.Static variable will neve be part of serialization. 5.How to serialize the singleton variables
@Configurable
public class NotSingleton implements Serializable {
    @Autowired
    private transient SingletonClass singleton;
    
}
5. When the serializable class extends non serializable class then the instance variable of the parent class can get the state which is the state which is initialized by serialized child class.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;

class NonSerial
{
int a=8;
NonSerial()
{
 System.out.println("called"+this.a);
}
}
class B extends NonSerial implements Serializable
{

 /**
  * 
  */
 
 
 private static final long serialVersionUID = 1L;
 B()
 {
  
 
 System.out.println("B  "+this.a);
  
 }
 public void getB()
 {
  this.a=12;
  
 }
}
public class SerializeDemo {

 public static void main(String[] args) {
  B bObj=new B();
  bObj.getB();
  try {
   ObjectOutputStream os=new ObjectOutputStream(new FileOutputStream(new File("a.txt")));
   os.writeObject(bObj);
   os.close();
  } catch (FileNotFoundException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  } catch (IOException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
 ObjectInputStream io = null;
 try {
  io = new ObjectInputStream(new FileInputStream(new File("a.txt")));
 } catch (FileNotFoundException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 } catch (IOException e1) {
  // TODO Auto-generated catch block
  e1.printStackTrace();
 }
 try {
  B b=(B) io.readObject();
  io.close();
  System.out.println("Later On "+b.a);
 } catch (ClassNotFoundException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 } catch (IOException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
 }
 }
}


Convert Java Object List to Json Array


Code for demonstrating the Conversion of Java Object to Json Array

Jars Required:

  • http://central.maven.org/maven2/com/google/code/gson/gson/2.3.1/gson-2.3.1.jar<br/>
  • http://repo.grails.org/grails/repo/org/immutables/gson/2.1.0.alpha/gson-2.1.0.alpha.jar


import java.io.IOException;
import java.io.PrintWriter;
import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.gson.Gson;
import com.model.Product;
import com.google.gson.reflect.TypeToken;
/**
 * Servlet implementation class UserController
 */
@WebServlet("/users")
public class UserController extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UserController() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products=new ArrayList<Product>();
products.add(new Product(1, "Pen", "Smooth Pencil", 23));
com.google.gson.Gson gsonObj=new Gson();
Type listTypes=new TypeToken<List<Product>>(){}.getType();
//;
PrintWriter pw=response.getWriter();
pw.write(gsonObj.toJson(products,listTypes));
pw.close();
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}

Session Demo View Cart Using Jsp and Servlet

Add Item Then Show LIst
package com.webapp.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.webapp.model.Product;

/**
 * Servlet implementation class ListController
 */
@WebServlet("/ListController")
public class ListController extends HttpServlet {
private static final long serialVersionUID = 1L;
     
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ListController() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Product> products=new ArrayList<Product>();
Product product1=new Product("Colgate",25, 2, "ToothPaste");
Product product2=new Product("Miswaak",50, 2, "Shiny teeth fights with germs");
products.add(product1);
products.add(product2);
request.setAttribute("deepti", products);
RequestDispatcher rd=request.getRequestDispatcher("/list.jsp");

rd.forward(request, response);
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}

}
Then Add to cart


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://java.sun.com/jstl/core" prefix="c" %>

<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt"%>
<!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>
<!-- <link href="/js/bootstrap.min.css" rel="stylesheet"> -->

   <!-- <script src="/js/bootstrap.min.js"></script> -->
</head>
<body>


<c:out value="${product.price}"/>



<c:forEach  items="${deepti}" var="product"  >   
   <div class = "col-sm-6 col-md-3">
      <div class = "thumbnail">
         <img src = "/bootstrap/images/kittens.jpg" alt = "Generic placeholder thumbnail">
      </div>
      
      <div class = "caption">
         <h3><c:out value="${product.price}"/></h3>
         <p><c:out value="${product.productDesc}"/></p>
         <p><c:out value="${product.productName}"/></p>
         <p><a href="/WebProject/Cart?add=<c:out value='${product.productName}'/>">Add to Cart</a>
          <p><a href="/WebProject/Cart?viewCart=1">View Cart</a>
            <a href = "#" class = "btn btn-primary" role = "button">
               Button
            </a> 
            
            <a href = "#" class = "btn btn-default" role = "button">
               Button
            </a>
         </p>
         
      </div>
   </div>
   </c:forEach>
   
 <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.2/jquery.min.js"/>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"/>
</body>
</html>
Then add to Session
package com.webapp.controller;

import java.io.IOException;

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;

/**
 * Servlet implementation class CartController
 */
public class CartController extends HttpServlet {
private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CartController() {
        super();
        // TODO Auto-generated constructor stub
    }

/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
    /**
     * Will add the add to cart item using session
     */
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if(request.getParameter("add")!=null)
{
HttpSession sessionObj=request.getSession();
sessionObj.setAttribute("cartItems",request.getParameter("add"));
}
if(request.getParameter("viewCart")!=null)
{
HttpSession sessionObj=request.getSession();
String cartItem=(String)sessionObj.getAttribute("cartItems");
request.setAttribute("cartItems",cartItem);
RequestDispatcher rd=request.getRequestDispatcher("/showCart.jsp");
rd.forward(request, response);
}
}

/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}

}
THen show your item added to cart

ShowCart.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 cartItem=(String)session.getAttribute("cartItems");

%>
</body>
<div id=""><%=cartItem %></div>
</html>

Advertising