J2EE Ashok PDF
J2EE Ashok PDF
J2EE Ashok PDF
Ashok
JAVA / J2EE
By
Mr. Ashok
JAVA / J2EE Mr. Ashok
Program: A program is a set of instructions, which are executed by a machine to reduce the burden of a user or
a human being by performing the operations faster without any mistakes.
What is Java?
Java is a high level programming language and also known as platform because of its JRE (java runtime environment).
As per the sun micro system standard the JAVA language is divided into three Editions.
1. J2SE/JSE
2. J2EE/JEE
3. J2ME/JME
J2SE
- > J2SE stands for java 2 standard edition
- > By using J2SE we can develop standalone/Desktop applications.
Standalone applications: - Any application which runs in single computer is called standalone application.
i. Standalone applications are the java applications which don’t need the client server architecture.
ii. The standalone applications applicable for the only one desktop hence it is called desktop applications or
window based applications.
iii. For the standalone applications doesn’t need internet connections.
iv. It is a local application it doesn’t need any other external application support.
v. This type of the applications we can launch by using the command line or by using the executable jar.
Client Database
J2EE
-> J2EE stands for java 2 enterprise edition
-> By using J2EE we can develop web based applications.
Ex: Facebook, IRCTC, Flipkart etc.…
Web-applications:- Any application which can be accessible through the browser is called Web application
i. Web applications are the java applications which needs client and server concept.
ii. Web applications must need the internet connections to access the application.
iii. The application which is present in the internet is called the web application.
JAVA / J2EE Mr. Ashok
request
Html
(java)
Css Hibernate
Jsp (.net) Used to
(php)
response Jdbc
store the
data.
Client: The Person who is sending the request is called client. All browsers comes under Clients.
Ex: Google chrome, Mozilla Firefox, Internet Explorer etc.…
Server: In information technology, a server is a computer program that provides services to other computer programs
(and their clients) in the same or other computers.
Ex: Apache Tomcat, Oracle WebLogic, IBM WebSphere’s (WAS) etc.….
Database: Database is used to store the details like client details, application details, registration details……etc.
Ex: Oracle, DB2, MySQL etc.….
J2ME
- > J2ME stands for java 2 mobile edition
- > J2ME is used to develop mobile/micro based applications.
any machine, plus this bytecode format also provide security. Any machine with Java Runtime Environment can run
Java Programs.
3. Object-Oriented:
In java everything is Object which has some data and behaviour. Java can be easily extended as it is based on
Object Model.
4. Robust:
Any technology if it is good at two main areas it is said to be ROBUST
i. Exception Handling
ii. Memory Allocation
JAVA is having very good predefined Exception Handling mechanism whenever we are getting exception we are
having meaning full information.
JAVA is having very good memory management system that is Dynamic Memory (at runtime the memory is
allocated) Allocation which allocates and deallocates memory for objects at runtime.
5. Secure:
When it comes to security, Java is always the first choice. With java secure features it enable us to develop virus
free, temper free system. Java program always runs in Java runtime environment with almost null interaction with
system OS, hence it is more secure.
6. Distributed:
Java provides the network facility. I.e. programs can be access remotely from any machine on the network rather
than writing program on the local machine. HTTP and FTP protocols are developed in java.
7. Portable:
Means able to be easily carried or moved. Write once, run anywhere (WORA) feature makes it portable.
8. Architecture-Neutral:
Java code is translated into byte code after compilation which is independent of any computer architecture, it needs
only JVM (Java Virtual Machine) to execute.
9. High performance:
JVM can execute byte codes (highly optimized) very fast with the help of Just in time (JIT) compilation technique.
JAVA / J2EE Mr. Ashok
10. Multithreading:
Java provides multitasking facility with the help of lightweight processes called threads.
11. Dynamic:
Java have the capability of linking dynamic new classes, methods and objects.
What is JVM?
Java virtual Machine (JVM) is a virtual Machine that provides runtime environment to execute java byte code. The
JVM doesn't understand Java typo, that's why you compile your *.java files to obtain *.class files that contain the
bytecodes understandable by the JVM.
JVM control execution of every Java program. It enables features such as automated exception handling, Garbage-
collected heap.
JVM details:
1. Class loader subsystem:
It is a part of JVM that care of finding and loading of class files.
2. Class/method area:
It is a part of JVM that contains the information of types/classes loaded by class loader. It also contain the static
variable, method body etc.
3. Heap:
It is a part of JVM that contains object. When a new object is created, memory is allocated to the object from the
heap and object is no longer referenced memory is reclaimed by garbage collector.
4. Java Stack:
It is a part of JVM that contains local variable, operands and frames. To perform an operation, Byte code
instructions takes operands from the stack, operate and then return the result in to the java stack.
5. Program Counter:
For each thread JVM instance provide a separate program counter (PC) or pc register which contains the address
of currently executed instruction.
7. Execution Engine:
It is a part JVM that uses Virtual processor (for execution), interpreter (for reading instructions) and JIT (Just in
time) compiler (for performance improvement) to execute the instructions.
Lifetime of JVM: When an application starts, a runtime instance is created. When application ends, runtime
environment destroyed. If n no. of applications starts on one machine then n no. of runtime instances are created
and every application run on its own JVM instance.
After installing the software the java folder is available in the fallowing location
To check whether the java is installed in your system or not go to the command prompt. To open the
command prompt
‘javac’ is not recognized is an internal or external command, operable program or batch file.
Whenever we are getting above information at that moment the java is installed but the java is not working properly.
1. Operating system will pick up javac command search it in the internal operating system calls. The javac not
available in the internal command list.
2. Then operating system goes to environmental variables and check is there any path is sets or not. Up to
now we are not setting any path. So operating system don’t know anything about javac command Because
of this reason we are getting error message.
JAVA / J2EE Mr. Ashok
Hence we have to set environmental variables. The main aim of the setting environmental variable is to make available
the following commands javac,java,javap (softwares) to the operating system.
Now the java is working fine in your system. Open the command prompt to check once C:>javac---------
now list of commands will be displayed
What is Variable?
A variable can be thought of as a container which holds value for you during the life of your program. Every variable
is assigned a data type which designates the type and quantity of a value it can hold.
1. Variable Declaration
2. Variable Initialization
JAVA / J2EE Mr. Ashok
1) Variable Declaration:
To declare a variable, you must specify the data type & give the variable a unique name.
2) Variable Initialization:
To initialize a variable you must assign it a valid value.
Variables in Java
Java Programming language defines mainly three kind of variables, they are
Instance variables
Static Variables
Local Variables
Instance variables
Instance variables are variables that are declare inside a class but outside any method, constructor or block. Instance
variable are also variable of object commonly known as field or property.
class Student
{
String name;
int age;
}
Here name and age are instance variable of Student class.
Static variables
Static are class variables declared with static keyword. Static variables are initialized only once. Static variables are
also used in declaring constant along with final keyword.
class Student
{
String name;
int age;
static int instituteCode=1101;
}
Here instituteCode is a static variable. Each object of Student class will share instituteCode property.
What is Static?
Static is a Non Access Modifier.
Applicable to
Method
Variable
Class nested within another Class
Initialization Block
Not Applicable to
How to Invoke
Static variable and Methods can be used without having any instance of the Class. Only the Class is required to
invoke a static Method or static variable.
Local variables
Local variables are declared in method constructor or blocks. Local variables are initialized when method or
constructor block start and will be destroyed once its end. Local variable reside in stack. Access modifiers are not
used for local variable.
float getDiscount(int price)
{
float discount;
discount=price*(20/100);
return discount;
}
Here discount is a local variable.
Local variables cannot use any of the access level since its scope is only inside the method.
Final is the Only Non-Access Modifier that can be applied to a local variable.
Local variables are not assigned a default value, hence they need to be initialized.
It can be used to get property value based on the property key. The Properties class provides methods to get data
from properties file and store data into properties file. Moreover, it can be used to get properties of system.
JAVA / J2EE Mr. Ashok
Dynamic loading of Java classes at runtime provides tremendous flexibility in the development of enterprise
systems. It provides for the basis of “application servers”, and allows even simpler, lighter-weight systems to
accomplish some of the same ends. Within Java, dynamic loading is typically achieved by calling the forName
method on the class
java.lang.Class;
A call to Class.forName ("X") causes the class named X to be dynamically loaded (at runtime). A call to forName ("X")
causes the class named X to be initialized (i.e., JVM executes all its static block after class loading). Class.forName
JAVA / J2EE Mr. Ashok
("X") returns the Class object associated with the "X" class. The returned Class object is not an instance of the "x"
class itself.
Class.forName ("X") loads the class if it not already loaded. The JVM keeps track of all the classes that have been
previously loaded. This method uses the classloader of the class that invokes it. The "X" is the fully qualified name
of the desired class.
In general Class.forName is used to load the class dynamically where we doesn’t know the class name beforehand.
Once the class is loaded we will use newInstance () method to create the object dynamically. Let’s consider that we
have a class “Test”, and we make a call like Class.forName(“com.ashok.apps.Test”), then Test class will be initialized
(JVM will run the static block which is inside the Test Class).Class.forName(“com.ashok.apps.Test”) will returns a
Class object associated with class Test.
Let’s see the below example, Our Test class will have a static block and a public constructor.
=======================================Test.java===============================================
package com.ashok.apps;
import java.util.Scanner;
{
e.printStackTrace();
}
}
}
=============================================0=============================================
We may be in situations where in which you may know the class name beforehand, then we can use the above way
to create object at runtime. Let’s see the explanation of the above code
Through Scanner we will get the class name with full package structure entered in the console.
How many ways are there to create Object for a class in java?
While being a Java developer we usually create lots of objects daily, but we always use the new or dependency
management systems e.g. Spring to create these objects. However, there are more ways to create objects.
There are total 5 core ways to create objects in Java which are explained below
Or
Both newInstance() methods are known as reflective ways to create objects. In fact newInstance() method of Class
class internally uses newInstance() method of Constructor class. That's why the later one is preferred and also used
by different frameworks like Spring, Hibernate, Struts etc.
Whenever we call clone () on any object, JVM actually creates a new object for us and copy all content of the previous
object into it. Creating an object using clone method does not invoke any constructor.
Note : To use clone () method on an object we need to implements Cloneable and define clone() method in it.
Java cloning is the most debatable topic in Java community and it surely does have its drawbacks but it is still the
most popular and easy way of creating a copy of any object until that object is full filling mandatory conditions of
Java cloning.
Note: To Serialize & deserialize an object we need to implement the Serializable interface in our class.
Let’s consider an Employee class for which we are going to create the objects
===================================Employee.java=============================================
package com.ashok;
import java.io.Serializable;
@Override
JAVA / J2EE Mr. Ashok
public Object clone() {
====================================Test.java=================================================
package com.ashok;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.Constructor;
// using Class.forName(.)
Class c = Class.forName("com.ashok.Employee");
Employee emp2 = (Employee) c.newInstance();
System.out.print("Emp 2 - Hash Code : ");
System.out.println(emp2.hashCode());
// using newInstance()
Constructor<Employee> con = Employee.class.getConstructor();
Employee emp3 = con.newInstance();
System.out.print("Emp 3 - Hash Code : ");
System.out.println(emp3.hashCode());
// using Cloning
Employee emp4 = (Employee) emp3.clone();
System.out.print("Emp 4 - Hash Code : ");
System.out.println(emp4.hashCode());
// Using De-Serialization
FileOutputStream fos = new FileOutputStream("emp.ser");
ObjectOutputStream oos = new ObjectOutputStream(fos);
oos.writeObject(emp4);
Reflection in Java
In Java, the process of analyzing and modifying all the capabilities of a class at runtime is called Reflection.
Reflection API in Java is used to manipulate class and its members which include fields, methods, constructor, etc.
at runtime.
Reflection in Java is a very powerful concept and it’s of little use in normal programming but it’s the backbone for
most of the Java, J2EE frameworks. Some of the frameworks that use java reflection are:
• JUnit – uses reflection to parse @Test annotation to get the test methods and then invoke it.
• Spring – dependency injection, read more at Spring Dependency Injection
• Tomcat web container to forward the request to correct module by parsing their web.xml files
and request URI.
• Eclipse auto completion of method names
• Struts
• Hibernate etc..
The list is endless and they all use java reflection because all these frameworks have no knowledge and access of
user defined classes, interfaces, their methods etc.
java.lang.Class is the entry point for all the reflection operations. For every type of object, JVM instantiates an
immutable instance of java.lang.Class that provides methods to examine the runtime properties of the object and
create new objects, invoke its method and get/set object fields.
The java.lang.reflect package provides many classes to use reflection, Following is a list of various Java classes in
java.lang.package to implement reflection-
Field: This class is used to gather declarative information such as datatype, access modifier, name and value of a variable.
Method: This class is used to gather declarative information such as access modifier, return type, name, parameter types
and exception type of a method.
JAVA / J2EE Mr. Ashok
Constructor: This class is used to gather declarative information such as access modifier, name and parameter types of a
constructor.
Modifier: This class is used to gather information about a particular access modifier.
Public String getName (): Returns the name of the class.
public Class getSuperclass(): Returns the super class reference
Public Class[] getInterfaces() : Returns an array of interfaces implemented by the specified class
Public in getModifiers (): Returns an integer value representing the modifiers of the specified class which needs to be
passed as parameter to "public static String toString (int i )" method which returns the access specifier for the given class.
import java.lang.reflect.Constructor;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
class Demo {
public static void main(String args[]) throws Exception {
// loading class into JVM
Class cls = Class.forName("com.ashoksoft.Test");
Reflection programming in java helps in retrieving and modifying information about Classes and
Class members such variable, methods, constructors.
Reflection API in Java can be implemented using classes in java.lang.reflect package and
methods of java.lang.Class class.
Some commonly used methods of java.lang.Class class are getName (), getSuperclass (),
getInterfaces (), getModifiers () etc.
Some commonly used classes in java.lang.reflect package are Field, Method, Constructor,
Modifier, etc.
Reflection API can access private methods and variables of a class which could be a security
threat.
Reflection API is a powerful capability provided by Java, but it comes with some overheads such
as slower performance, security vulnerability, and permission issue. Hence, reflection API
should be treated as the last resort to perform an operation.
Recursion in Java
Recursion in java is a process in which a method calls itself continuously. A method in java that calls itself is
called recursive method.
Recursion is a basic programming technique we can use in Java. One of the classic problems for introducing
recursion is calculating the factorial of an integer. The factorial of any given integer — call it n so that you
sound mathematical — is the product of all the integers from 1 to n. Thus, the factorial of 5 is 120: 5 x 4 x 3
x 2 x 1.
The recursive way to look at the factorial problem is to realize that the factorial for any given number n is equal to
n times the factorial of n–1, provided that n is greater than 1. If n is 1, the factorial of n is 1.
This definition of factorial is recursive because the definition includes the factorial method itself. It also includes
the most important part of any recursive method: an end condition. The end condition indicates when the recursive
method should stop calling itself. In this case, when n is 1, it just returns 1. Without an end condition, the recursive
method keeps calling itself forever.
int a = scanner.nextInt();
int result = fact(a);
System.out.println("Factorial of " +a+ " is :"+result);
}
JAVA / J2EE Mr. Ashok
Serialization comes into picture when we need to send an object(not text) over network or store in a file so that
the object can be rebuild again when needed. But the network infrastructure and hard disks does not understand
java, what they understand are bytes only, and this is what serialization does. It converts java object to bytes and
bytes to java object again.
A class must implement Serializable interface in order to be serialized, this is a marker interface that does not
contain any method in it.
1. package com.ashoksoft;
2.
3. import java.io.Serializable;
4.
5. /**
6. * @author Ashok Bollepalli
7. *
8. */
9. @SuppressWarnings("serial")
10. public class Student implements Serializable {
11.
12. private static final long serialVersionUID = 1L;
13.
14. private int id;
15. private String name;
16.
17. public int getId() {
18. return id;
19. }
20.
21. public void setId(int id) {
22. this.id = id;
23. }
24.
25. public String getName() {
26. return name;
27. }
28.
29. public void setName(String name) {
30. this.name = name;
31. }
32.
33. }
Here is code for serialization of java objects, we just need to get an FileOutputStream object from the five we want
to persist the object and pass this to ObjectOutputStream's object's constructor. Method writeObject() is used to
get bytes from java object and pass them to output stream.
1. package com.ashoksoft;
2.
3. import java.io.FileNotFoundException;
4. import java.io.FileOutputStream;
5. import java.io.IOException;
6. import java.io.ObjectOutputStream;
JAVA / J2EE Mr. Ashok
7.
8. /**
9. * @author Ashok Bollepalli
10. *
11. */
12. public class SimpleSerImpl {
13. public static void main(String args[]) {
14.
15. /*
16. * Assigning values to Student classes
17. */
18. Student student = new Student();
19. student.setId(1);
20. student.setName("Ashok Bollepalli");
21.
22. /*
23. * Serializing Student class
24. */
25. try {
26. FileOutputStream fileOutputStream = new FileOutputStream(
27. "serialobject.ser");
28. ObjectOutputStream objectOutputStream = new ObjectOutputStream(
29. fileOutputStream);
30. objectOutputStream.writeObject(student);
31.
32. } catch (FileNotFoundException e) {
33. // TODO Auto-generated catch block
34. e.printStackTrace();
35. } catch (IOException ioe) {
36. // TODO Auto-generated catch block
37. ioe.printStackTrace();
38. }
39.
40. }
41. }
All steps are included in the image showing below, let’s implement all those steps of deserialization one by one to
get java object back from the file.
JAVA / J2EE Mr. Ashok
Here is code for deserialization of java objects, we just need to get an FileInputStream object from the file that
contains object's bytes and pass this to ObjectInputStream's object's constructor. Method readObject() returns an
object whose bytes are being read from the file.
1. package com.ashoksoft;
2.
3. import java.io.FileInputStream;
4. import java.io.FileNotFoundException;
5. import java.io.IOException;
6. import java.io.ObjectInputStream;
7.
8. /**
9. * @author Ashok Bollepalli
10. *
11. */
12. public class SimpleSerImpl {
13. public static void main(String args[]) {
14.
15. /*
16. * Deerializing Student class
17. */
18. Student studentOut = null;
19.
20. try {
21. FileInputStream fileInputStream = new FileInputStream(
22. "serialobject.ser");
23. ObjectInputStream inputStream = new ObjectInputStream(
24. fileInputStream);
25. studentOut = (Student) inputStream.readObject();
JAVA / J2EE Mr. Ashok
Here we are done with Serialization and Deserialization of a simple object in java, but in real world applications
many other situation may occur. Let’s look a little deep in serialization in different scenarios.
In case the object we are going to serialize has some reference to other object, then what would happen? In this
case three possible conditions can arise.
1. package com.ashoksoft;
2.
3. import java.io.Serializable;
4. /**
5. * @author Ashok Bollepalli
6. *
7. */
8. public class Employee implements Serializable {
9. private int empId;
10. private String empName;
11. private EmployeeAddress employeeAddress;
12.
13. public int getEmpId() {
14. return empId;
JAVA / J2EE Mr. Ashok
15. }
16.
17. public void setEmpId(int empId) {
18. this.empId = empId;
19. }
20.
21. public String getEmpName() {
22. return empName;
23. }
24.
25. public void setEmpName(String empName) {
26. this.empName = empName;
27. }
28.
29. public EmployeeAddress getEmployeeAddress() {
30. return employeeAddress;
31. }
32.
33. public void setEmployeeAddress(EmployeeAddress employeeAddress) {
34. this.employeeAddress = employeeAddress;
35. }
36.
37. }
Here is a simple referenced class 'EmployeeAddress ' this class is being referenced by 'Employee' and implements
serializable interface. This class w'll be serialized along with Employee.
1. package com.ashoksoft;
2.
3. import java.io.Serializable;
4. /**
5. * @author Ashok Bollepalli
6. *
7. */
8. public class EmployeeAddress implements Serializable {
9.
10. private String street;
11. private String city;
12. private String state;
13. private String country;
14.
15. public String getStreet() {
16. return street;
17. }
18. public void setStreet(String street) {
19. this.street = street;
20. }
21. public String getCity() {
22. return city;
23. }
24. public void setCity(String city) {
JAVA / J2EE Mr. Ashok
Here is code for serialization and deserialization of java object with a reference to another serializable object. See
the implementation below:
1. package com.ashoksoft;
2.
3. import java.io.FileInputStream;
4. import java.io.FileNotFoundException;
5. import java.io.FileOutputStream;
6. import java.io.IOException;
7. import java.io.ObjectInputStream;
8. import java.io.ObjectOutputStream;
9. /**
10. * @author Ashok
11. *
12. */
13. public class ReferenceSerImpl {
14. public static void main(String args[]) {
15.
16. /*
17. * Assigning values to Employee and EmployeeAdress classes
18. */
19. Employee emp = new Employee();
20. emp.setEmpId(1);
21. emp.setEmpName("Ashok Bollepalli");
22.
23. EmployeeAddress employeeAddress = new EmployeeAddress();
24. employeeAddress.setStreet("Sec-44");
25. employeeAddress.setCity("Delhi");
26. employeeAddress.setState("Delhi");
27. employeeAddress.setCountry("India");
28.
29. emp.setEmployeeAddress(employeeAddress);
30.
31. /*
JAVA / J2EE Mr. Ashok
In case the reference class does not implement Serializable its variable must be declared transient.
CASE 2: If the referenced class does not implements Serializable but its reference variable is transient.
In case the referenced class EmployeeAddress does not implement Serializable interface, than there will be runtime
error in serializing Employee class. To avoid the error just make EmployeeAddress’s reference variable transient.
Transient EmployeeAddress employeeAddress; In this case when we will deserialize Employee class, there will be a
null value for EmployeeAddress reference.
CASE 3: If the referenced class can not implement Serializable interface and we still want to persist its states.
In the above two cases we saw, if a reference variable is there either the referenced class must be serializable or
the reference variable must be declared transient. Now the question arises, is it possible to persist states of a
referenced class even if the class is not serializable and its reference variable is declared transient. Yes, This is
possible !
In that case, Java serialization provides a mechnism such that if you have private methods with particular
signature then they will get called during serialization and deserialization so we will override writeObject and
readObject method of Employee class and they will be called during serialization and deserialization of Employee
object.
1. package com.ashoksoft;
2.
3. import java.io.IOException;
4. import java.io.ObjectInputStream;
5. import java.io.ObjectOutputStream;
6. import java.io.Serializable;
7. /**
8. * @author Ashok
9. *
10. */
11. public class Employee implements Serializable {
12. private static final long serialVersionUID = 1L;
13. private int empId;
14. private String empName;
15. transient private EmployeeAddress employeeAddress;
16.
17. public int getEmpId() {
18. return empId;
JAVA / J2EE Mr. Ashok
19. }
20.
21. public void setEmpId(int empId) {
22. this.empId = empId;
23. }
24.
25. public String getEmpName() {
26. return empName;
27. }
28.
29. public void setEmpName(String empName) {
30. this.empName = empName;
31. }
32.
33. public EmployeeAddress getEmployeeAddress() {
34. return employeeAddress;
35. }
36.
37. public void setEmployeeAddress(EmployeeAddress employeeAddress) {
38. this.employeeAddress = employeeAddress;
39. }
40.
41. private void writeObject(ObjectOutputStream ous) throws IOException,
42. ClassNotFoundException {
43. try {
44. ous.defaultWriteObject();
45. ous.writeObject(employeeAddress.getStreet());
46. ous.writeObject(employeeAddress.getCity());
47. ous.writeObject(employeeAddress.getState());
48. ous.writeObject(employeeAddress.getCountry());
49.
50. } catch (Exception e) {
51. // TODO Auto-generated catch block
52. e.printStackTrace();
53. }
54. }
55.
56. private void readObject(ObjectInputStream ois) throws IOException,
57. ClassNotFoundException {
58. try {
59. ois.defaultReadObject();
60. employeeAddress = new EmployeeAddress((String) ois.readObject(),
61. (String) ois.readObject(), (String) ois.readObject(),
62. (String) ois.readObject());
63. } catch (ClassNotFoundException e) {
64. // TODO Auto-generated catch block
65. e.printStackTrace();
66. } catch (Exception e) {
67. // TODO Auto-generated catch block
68. e.printStackTrace();
69. }
70.
JAVA / J2EE Mr. Ashok
71. }
72.
73. }
Here is a simple referenced class 'EmployeeAddress ' this class is being referenced by 'Employee' and does not
implements serializable interface.
1. package com.ashoksoft;
2.
3. /**
4. * @author Ashok Bollepalli
5. *
6. */
7. public class EmployeeAddress{
8.
9. private String street;
10. private String city;
11. private String state;
12. private String country;
13.
14. EmployeeAddress(String street, String city, String state, String country){
15. super();
16. this.street = street;
17. this.city = city;
18. this.state = state;
19. this.country = country;
20. }
21.
22. public String getStreet() {
23. return street;
24. }
25. public void setStreet(String street) {
26. this.street = street;
27. }
28. public String getCity() {
29. return city;
30. }
31. public void setCity(String city) {
32. this.city = city;
33. }
34. public String getState() {
35. return state;
36. }
37. public void setState(String state) {
38. this.state = state;
39. }
40. public String getCountry() {
41. return country;
42. }
43. public void setCountry(String country) {
44. this.country = country;
JAVA / J2EE Mr. Ashok
45. }
46.
47. }
1. package com.ashoksoft;
2.
3. import java.io.FileInputStream;
4. import java.io.FileNotFoundException;
5. import java.io.FileOutputStream;
6. import java.io.IOException;
7. import java.io.ObjectInputStream;
8. import java.io.ObjectOutputStream;
9. /**
10. * @author Ashok Bollepalli
11. *
12. */
13. public class ReferenceSerImpl {
14. public static void main(String args[]) {
15.
16. /*
17. * Assigning values to Employee and EmployeeAdress classes
18. */
19. Employee emp = new Employee();
20. emp.setEmpId(1);
21. emp.setEmpName("Nagesh Chauhan");
22.
23. EmployeeAddress employeeAddress = new EmployeeAddress("Sec-44","Delhi","Delhi","India");
24. // employeeAddress.setStreet("Sec-44");
25. // employeeAddress.setCity("Delhi");
26. // employeeAddress.setState("Delhi");
27. // employeeAddress.setCountry("India");
28. //
29. emp.setEmployeeAddress(employeeAddress);
30.
31. /*
32. * Serializing Employee class, referenced class EmployeeAdress will be
33. * serialized bydefault, unless the referenced class variable is not
34. * declared transient
35. */
36. try {
37. FileOutputStream fileOutputStream = new FileOutputStream(
38. "serialObject.ser");
39. ObjectOutputStream objectOutputStream = new ObjectOutputStream(
40. fileOutputStream);
41. objectOutputStream.writeObject(emp);
42.
43. } catch (FileNotFoundException e) {
44. // TODO Auto-generated catch block
JAVA / J2EE Mr. Ashok
45. e.printStackTrace();
46. } catch (IOException ioe) {
47. // TODO Auto-generated catch block
48. ioe.printStackTrace();
49. }
50.
51. /*
52. * Deserializing Employee class, referenced class EmployeeAdress will be
53. * deserialized bydefault, unless the referenced class variable is not
54. * declared transient
55. */
56. Employee empout = null;
57.
58. try {
59. FileInputStream fileInputStream = new FileInputStream(
60. "serialobject.ser");
61. ObjectInputStream inputStream = new ObjectInputStream(
62. fileInputStream);
63. empout = (Employee) inputStream.readObject();
64.
65. } catch (FileNotFoundException e) {
66. // TODO Auto-generated catch block
67. e.printStackTrace();
68. } catch (IOException ioe) {
69. // TODO Auto-generated catch block
70. ioe.printStackTrace();
71. } catch (ClassNotFoundException cnf) {
72. // TODO Auto-generated catch block
73. cnf.printStackTrace();
74. }
75.
76. /*
77. * Printing values from deserialized object
78. */
79. System.out.println("Deserailization of Employee and Address :");
80. System.out.println("Emp ID: " + empout.getEmpId());
81. System.out.println("Emp Name: " + empout.getEmpName());
82. System.out.println("Emp Address Street: "
83. + empout.getEmployeeAddress().getStreet());
84. System.out.println("Emp Address City: "
85. + empout.getEmployeeAddress().getCity());
86. System.out.println("Emp Address State: "
87. + empout.getEmployeeAddress().getState());
88. System.out.println("Emp Address Country: "
89. + empout.getEmployeeAddress().getCountry());
90.
91. }
92. }
JAVA / J2EE Mr. Ashok
In our previous discussions we came across, Serialization, serialVersionUID and transient variable. In this particular
blog we will see ‘Inheritance in Serialization’.
In case of inheritance, when we want to serialize an object there may be three possible scenarios.
In case super class is Serializable than all its subclasses will be serializable by default. No need to implement
serializable interface in subclass explicitly. See the implementation below.
1. package com.ashoksoft;
2.
3. import java.io.Serializable;
4.
5. /**
6. * @author Ashok Bollepalli
7. */
8. public class Human implements Serializable {
9.
10. private static final long serialVersionUID = 1L;
11.
12. String gender;
13. String color;
14.
15. Human(String gender, String color) {
16. this.gender = gender;
17. this.color = color;
18. }
19.
20. public String getGender() {
21. return gender;
22. }
23.
24. public void setGender(String gender) {
25. this.gender = gender;
26. }
27.
28. public String getColor() {
JAVA / J2EE Mr. Ashok
1. package com.ashoksoft;
2.
3. /**
4. * @author Ashok Bollepalli
5. */
6. public class Man extends Human {
7.
8. private String name;
9. private String address;
10.
11. Man(String gender, String color, String name, String address) {
12. super(gender, color);
13. this.name = name;
14. this.address = address;
15. }
16.
17. public String getName() {
18. return name;
19. }
20.
21. public void setName(String name) {
22. this.name = name;
23. }
24.
25. public String getAddress() {
26. return address;
27. }
28.
29. public void setAddress(String address) {
30. this.address = address;
31. }
32.
33. }
1. package com.ashoksoft;
2.
3. import java.io.FileInputStream;
4. import java.io.FileNotFoundException;
5. import java.io.FileOutputStream;
6. import java.io.IOException;
7. import java.io.ObjectInputStream;
8. import java.io.ObjectOutputStream;
JAVA / J2EE Mr. Ashok
9.
10. /**
11. * @author Ashok Bollepalli
12. */
13. public class Implementation {
14. public static void main(String args[]) {
15.
16. /*
17. * Assigning values to Man class's instance
18. */
19. Man man = new Man("Male", "Black", "Anderw", "Delhi");
20.
21. /*
22. * Serializing Man's instance
23. */
24. try {
25. FileOutputStream fileOutputStream = new FileOutputStream(
26. "serialObject.ser");
27. ObjectOutputStream objectOutputStream = new ObjectOutputStream(
28. fileOutputStream);
29. objectOutputStream.writeObject(man);
30.
31. } catch (FileNotFoundException e) {
32. // TODO Auto-generated catch block
33. e.printStackTrace();
34. } catch (IOException ioe) {
35. // TODO Auto-generated catch block
36. ioe.printStackTrace();
37. }
38.
39. /*
40. * Deserializing Man's instance
41. */
42. Man manout = null;
43.
44. try {
45. FileInputStream fileInputStream = new FileInputStream(
46. "serialobject.ser");
47. ObjectInputStream inputStream = new ObjectInputStream(
48. fileInputStream);
49. manout = (Man) inputStream.readObject();
50.
51. } catch (FileNotFoundException e) {
52. // TODO Auto-generated catch block
53. e.printStackTrace();
54. } catch (IOException ioe) {
55. // TODO Auto-generated catch block
56. ioe.printStackTrace();
57. } catch (ClassNotFoundException cnf) {
58. // TODO Auto-generated catch block
59. cnf.printStackTrace();
60. }
JAVA / J2EE Mr. Ashok
61.
62. /*
63. * Printing values from deserialized Man's object
64. */
65. System.out.println("Printing value of Deserailized Man's instance :");
66. System.out.println("Gender: " + manout.getGender());
67. System.out.println("Color: " + manout.getColor());
68. System.out.println("Name: " + manout.getName());
69. System.out.println("Address: " + manout.getAddress());
70.
71. }
72.
73. }
In case super class is not Serializable than to serialize the subclass’s object we must implement serializable
interface in subclass explicitly. In this case the superclass must have a no-argument constructor in it. See the
implementation below.
1. package com.ashoksoft;
2.
3. /**
4. * @author Ashok Bollepalli
5. */
6. public class Human {
7. String gender;
8. String color;
9.
10. Human() {
11. }
12.
13. Human(String gender, String color) {
14. this.gender = gender;
15. this.color = color;
16. }
17.
18. public String getGender() {
19. return gender;
20. }
21.
22. public void setGender(String gender) {
23. this.gender = gender;
24. }
25.
JAVA / J2EE Mr. Ashok
1. package com.ashoksoft;
2.
3. import java.io.Serializable;
4.
5. /**
6. * @author Ashok Bollepalli
7. */
8. public class Man extends Human implements Serializable {
9.
10. private static final long serialVersionUID = 1L;
11. private String name;
12. private String address;
13.
14. Man(String gender, String color, String name, String address) {
15. super(gender, color);
16. this.name = name;
17. this.address = address;
18. }
19.
20. public String getName() {
21. return name;
22. }
23.
24. public void setName(String name) {
25. this.name = name;
26. }
27.
28. public String getAddress() {
29. return address;
30. }
31.
32. public void setAddress(String address) {
33. this.address = address;
34. }
35.
36. }
1. package com.ashoksoft;
2.
3. import java.io.FileInputStream;
4. import java.io.FileNotFoundException;
5. import java.io.FileOutputStream;
JAVA / J2EE Mr. Ashok
6. import java.io.IOException;
7. import java.io.ObjectInputStream;
8. import java.io.ObjectOutputStream;
9.
10. /**
11. * @author Ashok
12. */
13. public class Implementation {
14. public static void main(String args[]) {
15.
16. /*
17. * Assigning values to Man class's instance
18. */
19. Man man = new Man("Male", "Black", "Anderw", "Delhi");
20.
21. /*
22. * Serializing Man's instance
23. */
24. try {
25. FileOutputStream fileOutputStream = new FileOutputStream(
26. "serialObject.ser");
27. ObjectOutputStream objectOutputStream = new ObjectOutputStream(
28. fileOutputStream);
29. objectOutputStream.writeObject(man);
30.
31. } catch (FileNotFoundException e) {
32. // TODO Auto-generated catch block
33. e.printStackTrace();
34. } catch (IOException ioe) {
35. // TODO Auto-generated catch block
36. ioe.printStackTrace();
37. }
38.
39. /*
40. * Deserializing Man's instance
41. */
42. Man manout = null;
43.
44. try {
45. FileInputStream fileInputStream = new FileInputStream(
46. "serialobject.ser");
47. ObjectInputStream inputStream = new ObjectInputStream(
48. fileInputStream);
49. manout = (Man) inputStream.readObject();
50.
51. } catch (FileNotFoundException e) {
52. // TODO Auto-generated catch block
53. e.printStackTrace();
54. } catch (IOException ioe) {
55. // TODO Auto-generated catch block
56. ioe.printStackTrace();
57. } catch (ClassNotFoundException cnf) {
JAVA / J2EE Mr. Ashok
If superclass is not Serializable then all values of the instance variables inherited from super class will be initialized
by calling constructor of Non-Serializable Super class during deserialization process. As we can see in the output
figure above ‘Gender’ gets a default value and ‘Color’ is getting null because of no default value set.
(3) If the superclass is serializable but we don’t want the subclass to be serialized.
To prevent subclass from being serialized we must implement writeObject() and readObject() method and need to
throw NotSerializableException from these methods.
Here, the serialVersionUID represents your class version, and you should increment it if the current version of your
class is modified such that it is no longer backwards compatible with its previous version.
JAVA / J2EE Mr. Ashok
Bullet Points
JDBC
What is JDBC?
JDBC is a Java API that allows Java programs to access database management systems (Relational database). The
JDBC API consists of a set of interfaces and classes which enables java programs to execute SQL statements.
After storing the data into Persistence stores, we can perform some operations on Persistent data, these
operations are called as Persistence operations. Below are the persistence operations
CURD or CRUD or SCUD
C- Create /Insert
U – Update
R – Retrieve
D – Delete
To perform these persistence operations on persistence data we need Persistence Technologies.
JDBC is one of the Persistence Technology. It is released by Sun micro system as part of JDK 1.1v.
Java programs cannot communicate with the Databases directly. JDBC acts as a mediator between Java and
Database.
JAVA / J2EE Mr. Ashok
1. JDBC Driver:
JDBC driver is a collection of classes which implements interfaces defined in the JDBC API for opening database
connections, interacting with database and closing database connections.
2. Connections:
Before performing any database operation via JDBC, we have to open a database connection. To open a
database connection we can call getConnection () method of DriverManager class.
3. Statements:
The JDBC statements are used to execute the SQL or PL/SQL queries against the database. We need a
statement for every single query.
4. ResultSets:
A query returns the data in the form of ResultSet. To read the query result data, ResultSet provides a cursor
that points to the current row in the result set.
2. Get the connection by using Database details (url, username and password).
Syntax : Class.forName("DriverClassName");
Ex : To load Oracle Driver Class we will use below statement
JAVA / J2EE Mr. Ashok
Class.forName(“oracle.jdbc.driver.OracleDriver”);
2. Create connection:
Second step is to open a database connection. DriverManager class provides the facility to create a connection
between a database and the appropriate driver.To open a database connection we can call getConnection()
method of DriverManager class.
username and password: username and password are used for authentication purpose.
3. Create statement:
The statement object is used to send SQL queries to the database .To create a statement object we have to call
createStatement() method of Connection interface.
Syntax :
4. Execute statement:
Statement interface provides the methods to execute a statement.
JAVA / J2EE Mr. Ashok
Call any one of the following three methods of Statement interface is used to execute queries to the database and
Syntax:
DriverManager class
Note : Whenever we open a database connection, its mandatory that we have to close the connection,
because every database will have limited no.of connections.
Requirement #1:
package info.ashok;
import java.sql.Connection;
import java.sql.DriverManager;
JAVA / J2EE Mr. Ashok
import java.sql.Statement;
/**
* @abstract This class is used to Create a table in DB
*
*/
public class DBOperations {
public static void main(String args[]) {
Connection conn = null;
Statement statement = null;
String query = "create table EMPLOYEE("
+ "EMPLOYEE_ID NUMBER(5) NOT NULL, "
+ "NAME VARCHAR(20) NOT NULL, "
+ "SALARY NUMBER(10) NOT NULL, "
+ "PRIMARY KEY (EMPLOYEE_ID) )";
String url = "jdbc:oracle:thin:@localhost:1521/XE";
String uname = "ashok";
String pwd = "ashok";
try {
// Load the driver (Using Oracle Driver)
Class.forName("oracle.jdbc.driver.OracleDriver");
// get connection
conn = DriverManager.getConnection(url, uname, pwd);
// create statement
statement = conn.createStatement();
// execute query
statement.execute(query);
// close connection
statement.close();
conn.close();
System.out.println("Table created successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note : set the CLASSPATH for ojdbc14.jar file and Execute the program like below
JDBC driver
Jdbc API contains a set of classes and Interfaces where classes definition is provided by Sun Micro System and
Interfaces Implementation are not provided. For interface Implementation classes will be provided by vendors,
these set of classes are called Jdbc Driver Software.
JAVA / J2EE Mr. Ashok
A Driver software contains set of classes among these classes one class is driver class.
Java Application use Jdbc API and this API connect to driver class, then driver class connect to database.
Database queries are classified into two types they are
1. Select queries 2. Non-select queries
Requirement #2:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
/**
* @abstract This class is used to Insert a record into Employee table in DB
* @author Ashok Bollepalli
*
*/
public class DBOperations {
public static void main(String args[]) {
Connection conn = null;
Statement statement = null;
String query = "insert into EMPLOYEE "
+ "(EMPLOYEE_ID, NAME, SALARY) "
+ "values (1, 'Raju', 50000)";
Requirement #3:
Execute the above program (Requirement: #2) by replacing the query as given below;
String query = "delete EMPLOYEE " + "where EMPLOYEE_ID = 1 ";
Requirement #5:
Develop the java application to retrieve the records from EMPLOYEE table and display to the client.
- > To retrieve the records from table we have to use select queries.
- > To execute the select queries we have to use executeQuery(String sql) method.
- > JDBC Driver will send the SQL query to database, in Database Database Engine will execute
- > After receiving the results from Database, it is the responsibility of JDBC Driver to convert the results
into Object format. That Object is called as ResultSet object and this ResultSet object will return to java
application.
Whenever we got the result set object(rs). It is associated with a ResultSet pointer.
- > To get the fist row data we need to move ResultSet pointer to the row position.
If rs.next() method return type is true, that means record (row) is available.
To get the data from columns ResultSet is providing some getterMethods(getXXX()) based on column data type.
Note : One Row may contains multiple columns, so retrieve particular column data we have to pass column
index or column name as a parameter for getter methods.
Syntax :
The following diagram shows how to read the values of a specific data type.
JAVA / J2EE Mr. Ashok
Advantages of PreparedStatement
1. Parameterized query: Provides the facility of parameterized query.
Note: PreparedStatement improves the performance of java application when compared with statement
object.
Requirement #6:
Develop a java application to insert a record into EMPLOYEE table by using prepared statement
package info.ashok;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
/**
* @abstract This class is used to Insert a record in Table
*/
public class DBOperations {
public static void main(String args[]) {
Connection conn = null;
PreparedStatement pstmt = null;
try {
// get connection
conn = DriverManager.getConnection(url, uname, pwd);
JAVA / J2EE Mr. Ashok
// Creating Query
String query = "insert into EMPLOYEE (EMPLOYEE_ID, NAME, SALARY) values (?,?,?)";
// create preparedStatement
pstmt = conn.prepareStatement(query);
// set values
pstmt.setInt(1, 1);
pstmt.setString(2, "Bharat");
pstmt.setInt(3, 62000);
// execute query
pstmt.executeUpdate();
// close connection
pstmt.close();
conn.close();
System.out.println("Record inserted successfully.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Requriement #7:
Note: Set the values for positional parameters and execute the program.
Requriement #8:
Note : Set the values for positional parameter and execute the program
Requirement #9:
Develop a java program to retrieve records from EMPLOYEE table.
package info.ashok;
JAVA / J2EE Mr. Ashok
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
/**
* @abstract This class is used to Retrieve Records from TABLE.
*
*
*/
public class DBOperations {
try {
// Creating Query
String query = "select EMPLOYEE_ID, NAME from EMPLOYEE";
// create preparedStatement
pstmt = conn.prepareStatement(query);
} catch (Exception e) {
e.printStackTrace();
}
JAVA / J2EE Mr. Ashok
}
}
JDBC CallableStatement
The JDBC CallableStatement is used to execute the store procedure and functions. CallableStatement interface
provides the methods to execute the store procedure and functions. We can get a statement object by invoking
the prepareCall() method of Connection interface.
Syntax:
Note: A store procedure is used to perform business logic and may return zero or more values. A function used
to perform calculation and it can return only one value.
Use Case :
Calculate the bill amount to all the customers which are available in customer table.
package info.ashok;
import java.sql.*;
The disadvantage above approach we are interact with database server from multiple times through networks.
Because of this we get the performance issue we can resolve this by using procedures.
We can write the procedures with business logic. Procedures in database server procedures run’s inside
database server.
Whenever anybody call processor, database server run’s it procedures improves performance of project.
Procedures:
A stored procedure is nothing more than prepared SQL code that you save so you can reuse the code over and
over again. So if you think about a query that you write over and over again, instead of having to write that
query each time you would save it as a stored procedure and then just call the stored procedure to execute the
SQL code that you saved as part of the stored procedure.
In addition to running the same SQL code over and over again you also have the ability to pass parameters to
the stored procedure, so depending on what the need is the stored procedure can act accordingly based on the
parameter values that were passed.
as begin
end MyProc;
as
begin
end MyProc;
Execution :
create or replace procedure addition(no1 in number, no2 in number, result out number)
as begin
end addition;
Step 1: Before we call the procedure we must register / create variable. (/ slash)
Step 3: After procedure is executed we can get the value from out variable and display.
Requirement #10:
Develop a java application to call a procedure which doesn’t take any parameter.
package info.ashok;
JAVA / J2EE Mr. Ashok
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* @abstract This class is used to call Procedure from DB
* @author
*
*/
public class DBOperations {
// close connection
cstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Requirement #11:
Develop a java application to call the procedure which takes Input parameters.
package info.ashok;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
/**
JAVA / J2EE Mr. Ashok
* @abstract This class is used to call Procedure from DB
*
*/
public class DBOperations {
// close connection
cstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Requirement #12 :
Develop a java application to call a procedure which takes input parameter and output parameter
package info.ashok;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Types;
/**
* @abstract This class is used to call Procedure from DB
JAVA / J2EE Mr. Ashok
*
*/
public class DBOperations {
// close connection
cstmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Note : When we register out parameter it is responsibility of JDBC driver to declare a variable. Once the
procedure is executed the value will be stored in the variable
Functions
In oracle we can use functions. They are two types of function are available in oracle.
i. count()
ii. min()
JAVA / J2EE Mr. Ashok
iii. max()
iv. sum()
v. avg() and etc.
Requirement #13 :
Develop a java application to find the number of records available in EMPLOYEE table
package info.ashok;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* @abstract This class is used to call function from DB
* @author Ashok
*
*/
public class DBOperations {
// create statement
stmt = conn.createStatement();
// close connection
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Types of ResultSets:
They are two types of ResultSets in java. They are
Bi-Directional ResultSet can be achieved in both statement and prepared statement object. To get the Bi-
Directional ResultSet we have to sulpply parameters to statement object (or) prepared statement object.
For ResultSet TYPE we can supply any of the following three values.
For ResultSet Concurrency we can supply any of the following two values.
When we use CONCUR_UPDATABLE when even we modify the data in ResultSet object it get reflected in
database server.
Requirement 14:
Develop a java program to retrieve records from Table (using Bi-Directional Result Set)
package info.ashok;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* @abstract This class is used to Create a table DB
*
*/
public class DBOperations {
// create statement
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_READ_ONLY);
} catch (Exception e) {
e.printStackTrace();
}
}
}
When we call the previous() method the ResultSet pointer is placed to old recored.
Absoulte(): This method is used to move the ResultSet pointer to a specific Record/Row. Ex: rs.absolute(5);
When the above line is executed to ResultSet pointer is placed at 5th Row.
Requirement #15:
Develop a java program to retrieve records from Table (using Bi-Directional Result Set)
To develop a sensitive ResultSet program we must follow the follow three steps.
package info.ashok;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
/**
* @abstract This class is used to Create a table DB
*
*
*/
public class DBOperations {
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
ResultSet rs = stmt.executeQuery("select eno, ename, sal from emp");
while(rs.next()){
//System.out.println("press any key to get the next result");
//System.in.read();
//System.in.read();
rs.refreshRow();
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}
// close connection
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Whenever java program has encounter a refreshRow() it will check the data in database server and the data in
ResultSet object same or not. If they are not same refreshRow() will update the data in ResultSet object.
In the SQL query instead of * we are specified column names. This is because whenever we change the specific
column , the JDBC Driver update the specific column only.
Batch Updates
The JDBC batch processing provides the facility to execute a group of related queries. A group of related
queries is known as a batch. It reduces the amount of communication overhead and hence improves the
performance.
Instead of sending individual queries to Database, We can add multiple queries to Batch object and send Batch
object to database server only once. So that we can reduce no.of iterations b/w Java program and DB Server.
Because of these we can improve the performance.
JAVA / J2EE Mr. Ashok
When ever we create the statement object, immediately a Batch object will be created. This Batch object is
associated with statement object.
Ex: Statement stmt1 = on.createStatement();
Statement stmt2 = con.createStatement();
Requirement : #16
Develop a java application to insert three records into EMPLOYEE table by using Batch updates
package info.ashok;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
/**
* @abstract This class is used to Execute Batch Object
*
*/
public class DBOperations {
// create statement
stmt = conn.createStatement();
// executing batch
stmt.executeBatch();
// close connection
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
By using object we can add insert, update and delete queries. By using Batch updates we can not perform
select and create operations.
The size of integer array is dependent on the size of the Batch object. The integer array contains the values
which are got effected by each and every query. We can print these values by using a loop.
Ex:
for(int i = 0; i<a.length;i++){
System.out.println(a[i]);
While working with Batch updates if any query in the batch object is failed. JDBC driver throws java.
Sql.BatchUpadeException.
Once if we sent the Batch object to database server we can clear the Batch by using cleared Batch method.
JAVA / J2EE Mr. Ashok
Transactions:
Transaction represents a single unit of work.
The ACID properties describes the transaction management well. ACID stands for Atomicity, Consistency,
isolation and durability.
If all the steps in the transaction are executed successfully then we say transaction is success. If any one step is
failed we can say transaction is failed.
After establish the connection with database server. When the user perform any operation. The data will store
permanently when we end the transaction.
When the JDBC driver starts the transaction. When ever we establish connection with database server
immediately JDBC driver starts the transaction.
con.setAutoCommit(false);
and con.rollBack();”.
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
con.commit();
JAVA / J2EE Mr. Ashok
}
The above application is used to capture employee details and store it in a DB. Our application should be able
to support dealing with multiple address.
To achieve the above requirement we have two designs. Design1: In this design we create only table.
The disadvantage of this approach is we find the duplicate data in the table. It is not recommend using design1.
Design2: In this design we will try to have two tables. They are emp and Address tables.
MetaData:
Data about data is called as MetaData.
The following is example of using ResultSetMetaData object to find number of columns name of the columns
and data types.
Ex: rs = stmt.executeQuery(“select * from emp”);
ResultSetMetaData rsmd = rs.getMetaData();
System.out.println(rsmd.getColumnCount());
System.out.println(rsmd.getColumnName(2)); System.out.println(rsmd.getColumnTypeName(2));
System.out.println(rsmd.isSearchable(2));
System.out.println(rsmd.getColumnType(1));
DatabaseMetadata
DatabaseMetadata is an object which gives more information about underline Database server. That is it can
find the database server, version information and JDBC Driver information.
ParameterMetaData:
ParameterMetaData is an object which gives more information about
ParameterMetaData’s of PreparedStatement (possional parameter information is object). To get
ResultSetMetaData object we take the help of ResultSet object. We use a method get MetaData to get
ResultSetMetaData object.
Requirement #17:
SQL> create table empimg (eno number(5), name varchar2(20), image blob);
package info.ashok;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @abstract This class is used to Insert image into table
*
*
*/
public class DBOperations {
public static void main(String[] args) throws SQLException,FileNotFoundException {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "ashok", "ashok");
Requirement #18:
Develop a java program to retrieve Image from Database
package info.ashok;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* @abstract This class is used to retrieve Image from DB
*
*/
public class DBOperations {
public static void main(String[] args) throws
SQLException,FileNotFoundException,IOException {
DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());
Connection con =
DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe", "ashok", "ashok");
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("select * from empimg");
rs.next();
System.out.println(rs.getInt(1));
System.out.println(rs.getString(2));
byte imgarr[] = rs.getBytes(3);
FileOutputStream fos = new FileOutputStream("one.jpg"); // target folder to place
img
fos.write(imgarr);
fos.close();
con.close();
}
}
JAVA / J2EE Mr. Ashok
Connection pool
When we develop a java application to get the connection from Database server. By using
DriverManager.getConnection we always get physical connections.
If we got a physical connection and we are not closing the connection after completion of work, the other
application can not use the same connections.
Connection pool is java program which manages the connections of Database server. Connection pool
contains set of connections.
There are so many connection pool programs are available some of them are.
i. DBCP (Database connection pool)
ii. C3p0 connection pool
iii. Weblogic connection pool
iv. JBOSS connection pool
v. Tomcat connection pool ……. Etc.
Generally connections pool program is released in the form of jar files. The jar file contains set of class.The
meaning of using connection pool program is creating the object class and supply Driver class, url, username,
password and initial capacity.
Requirement #19:
Develop a java program to establish Connection pool (Using DBCP connection pool)
package info.ashok;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import org.apache.commons.dbcp.BasicDataSource;
1.tomcat-dbcp.jar, ojdbc14.jar
Requirement #20 :
Develop a java program to establish Connection pool (Using C3PO connection pool)
package info.ashok;
import java.beans.PropertyVetoException;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import com.mchange.v2.c3p0.ComboPooledDataSource;
}
}
Note : Set the CLASSPATH for below jar fies and execute the program
2.13 RowSet Interfcae
ResultSet Disdavantages
ResultSet Object is not serilaizable , because it is always maintains a connection with DB
We can’t pass theResultset object from one class to other class across the network.
Rowset
RowSet extends the ResultSet interface so it has all the methods of ResultSet
RowSet can be serialized because it doesn’t have a connection to any database
RowSet Object can be sent from one class to another across the network.
rowSet.setPassword("oracle");
rowSet.setCommand("select * from emp400");
Requirement #21:
Develop a java program to read data from DB table and write it to Excel file
Many a time, a software application is required to generate reports in Microsoft Excel file format. Sometimes,
an application is even expected to receive Excel files as input data. For example, an application developed for
the Finance department of a company will be required to generate all their outputs in Excel.
Any Java programmer who wants to produce MS Office files as output must use a predefined and read-only
API to do so.
What is Apache POI?
Apache POI is a popular API that allows programmers to create, modify, and display MS Office files using Java
programs. It is an open source library developed and distributed by Apache Software Foundation to design or
modify Microsoft Office files using Java program. It contains classes and methods to decode the user input
data or a file into MS Office documents.
Components of Apache POI
Apache POI contains classes and methods to work on all OLE2 Compound documents of MS Office. The list of
components of this API is given below.
i. POIFS (Poor Obfuscation Implementation File System) : This component is the basic factor of all other
POI elements. It is used to read different files explicitly.
ii. HSSF (Horrible Spreadsheet Format) : It is used to read and write xls format of MS-Excel files.
iii. XSSF (XML Spreadsheet Format) : It is used for xlsx file format of MS-Excel.
iv. HPSF (Horrible Property Set Format) : It is used to extract property sets of the MS-Office files.
v. HWPF (Horrible Word Processor Format) : It is used to read and write doc extension files of MS-Word.
vi. XWPF (XML Word Processor Format) : It is used to read and write docx extension files of MS-Word.
vii. HSLF (Horrible Slide Layout Format) : It is used for read, create, and edit PowerPoint presentations.
JAVA / J2EE Mr. Ashok
viii. HDGF (Horrible DiaGram Format) : It contains classes and methods for MS-Visio binary files.
ix. HPBF (Horrible PuBlisher Format) : It is used to read and write MS-Publisher files.
x. This tutorial guides you through the process of working on Excel files using Java. Therefore the discussion
is confined to HSSF and XSSF components.
Note: Older versions of POI support binary file formats such as doc, xls, ppt, etc. Version 3.5 onwards, POI
supports OOXML file formats of MS-Office such as docx, xlsx, pptx, etc.
Like Apache POI, there are other libraries provided by various vendors for Excel file generation. These include
Aspose cells for Java by Aspose, JXL by Commons Libraries, and JExcel by Team Dev.
Let us assume the following employee data table called emp_tbl is to be retrieved from the ORACLE
database.
Use the following code to retrieve data from a database and insert the same into a spreadsheet.
import java.io.File;
import java.io.FileOutputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelDatabase
{
public static void main(String[] args) throws Exception
{
Class.forName("Oracle.jdbc.driver.OracleDriver");
Connection connect = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521/XE" ,
"ashok" , "ashok");
Statement statement = connect.createStatement();
ResultSet resultSet = statement.executeQuery("select * from emp_tbl");
XSSFWorkbook workbook = new XSSFWorkbook();
XSSFSheet spreadsheet = workbook.createSheet("employe db");
XSSFRow row=spreadsheet.createRow(1);
XSSFCell cell;
cell=row.createCell(1);
JAVA / J2EE Mr. Ashok
cell.setCellValue("EMP ID");
cell=row.createCell(2);
cell.setCellValue("EMP NAME");
cell=row.createCell(3);
cell.setCellValue("DEG");
cell=row.createCell(4);
cell.setCellValue("SALARY");
cell=row.createCell(5);
cell.setCellValue("DEPT");
int i=2;
while(resultSet.next())
{
row=spreadsheet.createRow(i);
cell=row.createCell(1);
cell.setCellValue(resultSet.getInt("eid"));
cell=row.createCell(2);
cell.setCellValue(resultSet.getString("ename"));
cell=row.createCell(3);
cell.setCellValue(resultSet.getString("deg"));
cell=row.createCell(4);
cell.setCellValue(resultSet.getString("salary"));
cell=row.createCell(5);
cell.setCellValue(resultSet.getString("dept"));
i++;
}
FileOutputStream out = new FileOutputStream(
new File("exceldatabase.xlsx"));
workbook.write(out);
out.close();
System.out.println("exceldatabase.xlsx written successfully");
}
}
Interview Questions
1. What is JDBC API and when do we use it?
2. What are different types of JDBC Drivers?
3. How can you load the drivers?
4. How does JDBC API helps us in achieving loose coupling between Java Program and JDBC
Drivers API?
5. What is JDBC Connection? Explain steps to get Database connection in a simple java
program.
6. What is the use of JDBC DriverManager class?
7. How to get the Database server details in java program?
8. What are the types of statements in JDBC?
9. What is JDBC Statement?
JAVA / J2EE Mr. Ashok
10. What is the difference between executeQuery, executeUpdate?
11. What is JDBC PreparedStatement?
12. What are the benefits of PreparedStatement over Statement?
13. What is JDBC ResultSet?
14. What are different types of ResultSet?
15. Differentiate between TYPE_SCROLL_INSENSITIVE and TYPE_SCROLL_SENSITIVE.
16. How to use JDBC API to call Stored Procedures?
17. What is JDBC Batch Processing and what are it’s benefits?
18. What does setAutoCommit do?
19. What is JDBC Transaction Management and why do we need it?
20. How to rollback a JDBC transaction?
21. What is JDBC Savepoint? How to use it?
22. What is Metadata and why should I use it?
23. What is JDBC DataSource and what are it’s benefits?
24. How to achieve JDBC Connection Pooling using JDBC DataSource ?
25. What is Apache DBCP API?
26. What are common JDBC Exceptions?
27. What is CLOB and BLOB datatypes in JDBC?
28. What do you understand by DDL and DML statements?
29. What is difference between java.util.Date and java.sql.Date?
30. How to insert an image or raw data into database?
31. How to invoke Oracle Stored Procedure with Database Objects as IN/OUT?
32. When do we get java.sql.SQLException: No suitable driver found?
33. What are JDBC Best Practices?
34. What is connection pooling ?
35. What is the advantage of Properties file in jdbc ?
JAVA / J2EE Mr. Ashok
Servlets
The basic aim of servlets is to develop web applications. Before servlets came into picture there was a
specification called CGI. Servlets specification developed by SUN and released to the industry. Lot of server
vendors came forward for implementing these specifications of servlets. Servlets are nothing but set of rules
given by SUN in the form of Interfaces. The J2EE server vendors have developed their own classes by
implementing the interfaces developed by SUN.
The collection of classes developed by server vendors and Interfaces developed by SUN are known as Servlet-
API.
Internet Protocols
Lot of data transfer happens in an internet between computers and networks, and there should be some rules
to regulate these transfers. A communications protocol is a system of digital rules for data exchange within or
between computers.
The Internet protocol suite is a set of communications protocols used for the Internet and similar networks. It
is commonly known as TCP/IP, because it’s most important protocols are the Transmission Control Protocol
(TCP) and the Internet Protocol (IP), and they were the first networking protocols defined in this standard.
Transmission Control Protocol (TCP) is a connection-oriented protocol that provides reliable, ordered, error-
checked delivery of packets.
Internet Protocol (IP) has the task of delivering packets from the source host to the destination host solely
based on the IP addresses in the packet headers.
UDP is a connection-less protocol that does not provide reliability, order or error-checking. UDP messages are
referred to as datagrams and a datagram is defined as a basic transfer unit associated with a packet-switched
network in which the delivery, arrival time, and order of arrival are not guaranteed by the network.
JAVA / J2EE Mr. Ashok
HTTP is the protocol to exchange or transfer hypertext. Hypertext is structured text that uses logical links
(hyperlinks) between nodes containing text.
The World Wide Web (abbreviated as WWW or W3) or the web is a system of interlinked hypertext documents
accessed via the Internet. With a web browser, one can view web pages and navigate between them via
hyperlinks.
FTP is a standard network protocol used to transfer files from one host to another host over a TCP-based
network.
SMTP is an Internet standard for electronic mail (e-mail) transmission across Internet Protocol (IP) networks.
IP Address
Websites and pages over the internet have a unique worldwide address called the IP addresses (e.g.
192.168.1.6), but a domain name (e.g. javajee.com) is used to refer to a website as it is easy to remember.
There are two versions of IP specification in use now: IPv4 and IPv6. IPv4 is the most widely used version
currently. An IPv4 address contains 4 parts and each part will be a number between 0 and 255, e.g.
192.168.1.6. An IPv6 address has 8 parts and each part must be a hexadecimal number between 0 and FFFF,
e.g. FF3:9B3D:999:0:FF12:420:20:444D.
Web application
A web application is any application software that runs on a server and we can access it using a web browser
client. For instance, consider this website; you access it using a client browser, but it is deployed on a server
located elsewhere.
Popular server side technologies used to create web applications include JSP/Servlets, ASP, PHP etc.
Web server
A web server is software that helps to deliver web content (web pages) to the clients (e.g. web browser)
through the Internet using HTTP protocol. Some of the commonly used web servers are Apache web server,
Microsoft Internet Information Services (IIS), Nginx Nginx (pronounced "engine x") and GWS (Google Web
Server). Other older web servers include Jigsaw web server from W3C, Oracle web server and Xitami web and
FTP server developed by iMatix Corporation.
Java web containers like Apache Tomcat also can act as a web server, but is usually used along with another
web server like Apache server.
JAVA / J2EE Mr. Ashok
Web browser
A web browser (e.g. Internet Explorer, Google chrome, Mozilla Firefox and Opera web browser) can read HTML
documents and compose them into visible or audible web pages. JSP (Java Server Pages) based on Java, ASP
(Active Server Pages) based on .net or the open source PHP (PHP: Hypertext Preprocessor) pages, all finally
generate html pages with other client side technologies like JavaScript and CSS, and is sent to the web browser.
Try viewing the source of any web page through the view source option and you will only html, JavaScript or
CSS, but no JSP, ASP or PHP.
URI is an abstract concept and the two concrete forms of URI are
Uniform resource locator (URL), which is most common and is frequently referred to informally as a web
address. E.g. http://www.ososys.com/internet-and-web-technologies.
Uniform resource name (URN), which is rarely seen, and was designed to complement URLs by providing a
mechanism for the identification of resources in particular namespaces. E.g. (from wikipedia): The ISBN 0-486-27557-
4 cites unambiguously a specific edition of Shakespeare's play Romeo and Juliet. The URN for that edition would be
urn: isbn:0-486-27557-4. To gain access to this object and read the book, its location is needed, for which a URL
would have to be specified.
HTML (Hypertext Mark-up Language) is a markup language used to mark-up the different elements of a web page
like headings, paragraphs, tables, images etc. Without markup, the contents will just appear as normal text without
any headings, paragraphs, tables or images. A web browser (e.g. Internet Explorer, Google chrome, Mozilla Firefox
and Opera web browser) can read HTML documents and compose them into visible or audible web pages.
Cascading Style Sheets (CSS) is a style sheet language used for describing the presentation semantics (the look and
formatting) of a document written in a markup language like HTML. CSS is designed primarily to enable the
separation of document content (written in HTML or a similar markup language) from document presentation,
including elements such as the layout, colors, and fonts. You can also define the look and feel using HTML alone, but
that is not a good practice. One of the advantages of using CSS is that you can change the look and feel of a page just
by changing the style sheet and don’t have to change the web page itself.
JavaScript (JS) is a dynamic programming language understood by web browsers. We can write client-side (browser)
scripts using JavaScript to create dynamic content on web pages like scrolling text, expanding menu etc., interact
JAVA / J2EE Mr. Ashok
with the user, validate user inputs at client side, communicate asynchronously with a server, and even alter the
document content that is displayed. JavaScript is not related to Java through the name is similar and there is some
syntax similarity. JavaScript is not limited to web browsers, but can be used in many areas like mobile and desktop
applications. There are many JavaScript libraries that provide some JavaScript functions out of the box and we can
just use them without writing them again. Popular such libraries include JQuery, Angular JS, Dojo Toolkit, Ext JS,
Microsoft's Ajax library etc.
Container
Container provides runtime environment for Java2ee (j2ee) applications. A web container is a predefined
application provided by a server, its takes care of Servlet and JSP.
In console based java applications a class which contains main method acts as a container for other classes.
Operations of Container
• Life Cycle Management
• Communication Support
• Multithreaded support
• Security etc.
Life cycle management:
Servlet and JSP are dynamic resources of java based web application. The Servlet or JSP will run on a server
and at server side. A container will take care about life and death of a Servlet or JSP. A container will
instantiate, Initialize, Service and destroy of a Servlet or JSP. It means life cycle will be managed by a
container.
Communication Support
If Servlet or JSP wants to communicate with server than its need some communication logic like socket
programming. Designing communication logic is increase the burden on programmers, but container act as a
mediator between a server and a Servlet or JSP and provides communication between them.
Multithreading
A container creates a thread for each request, maintains the thread and finally destroy it whenever its work is
finished.
Security
A programmer is not required to write security code in a Servlet/JSP. A container will automatically provide
security for a Servlet/JSP.
HTTP
HTTP is a synchronous request-response application network protocol. Client sends a request specifying one of
the seven HTTP methods, the location of the resource to be invoked, a set of optional headers and an optional
message body. The server sends back a response containing the version of HTTP we are using, a response code,
a description of the response code, a set of optional headers, and an optional message body. HTTP is the
JAVA / J2EE Mr. Ashok
primary protocol for most web applications on the Internet, regardless of whether they are written in Java, PHP
or ASP.
HTTP Versions
Important versions that need to be considered are HTTP/1.0 and HTTP/1.1.
HTTP/1.0 defines the basics protocol with some methods such as GET, POST and HEAD, and did not support
informational status codes.
HTTP/1.1 defines seven HTTP methods GET, POST, HEAD, OPTIONS, TRACE, PUT, DELETE, and also add many
headers and facilities to the original HTTP/1.0.
HTTP is connectionless: The HTTP client, i.e., a browser initiates an HTTP request and after a request is made,
the client disconnects from the server and waits for a response. The server processes the request and re-
establishes the connection with the client to send a response back.
HTTP is media independent: It means, any type of data can be sent by HTTP as long as both the client and the
server know how to handle the data content. It is required for the client as well as the server to specify the
content type using appropriate MIME-type.
HTTP is stateless: As mentioned above, HTTP is connectionless and it is a direct result of HTTP being a stateless
protocol. The server and client are aware of each other only during a current request. Afterwards, both of them
forget about each other. Due to this nature of the protocol, neither the client nor the browser can retain
information between different requests across the web pages.
Initial Request Line :Initial Request Line is divided into following three parts. They are:
Method: The method indicates what operation has to be carried out by the server. The following are method of
http protocol. They are:
Request Resource: This is indicating the resource which has to be proceeding by the resource may be available
or may not available.
User-Agent
Accept-Language
User-Agent: Indicates which browser program has sent to request to server. To represent a next line character
we use CR LF.
Accept-Language: Header is use to specify what language is acceptable by the client based on the Accept-
Language server will send the output to the client.
Status Code: indicates the status code of the Request send by the server.
400 to 499 Request Resources not available 500 to 599 Failed to execute Request Resource
By using java we can develop both static and dynamic web-based applications.
According to directory structure, an application contain root folder with any name.
o Under root folder a sub folder is required with a name WEB-INF.
o Under WEB-INF two sub folder are required classes and lib.
o All jar files placed inside lib folder.
o Under root folder src folder are place for .java files
o Under root folder or under WEB-INF any other folders can exits.
o All image, html, .js, jsp, etc files are placed inside root folder
o All .class files placed inside classes folder.
JAVA / J2EE Mr. Ashok
Servlet Components
The following are the most important “packages” to develop servlets. They are:
i. Javax.servlet
ii. Javax.servlet.http
The following are the most important interfaces and classes of javax.servlet package.
The following are the most important interfaces and classes of javax.servlet.http package.
Servlet
The servlet is an API, Released by Sun Micro System. The servlet is a java program which runs inside the
Server.
The servlet is a java program which provides the ‘implementation’ of servlet interface directly or indirectly.
A servlet is a server side platform independent, dynamic and multithread java program, which runs in the
context of server for extending the functionality of server. When multiple users make a request to the same
servlet then all requests will be processed by the container by creating multiple threads for the same servlet.
Advantages of Servlet
• Better performance:
• Portability
• Robust
JAVA / J2EE Mr. Ashok
• Secure
Better performance: Because it creates a thread for each request not process (like CGI).
Robust: Servlet are managed by JVM so no need to worry about memory leak, garbage collection etc.
Servlet as technology
As a technology servlet provides a model of communication between a web user request and the application
or program on the web server.
Servlet as component
As a component servlet is a program which is executed in web server and responsible for dynamic content
generation.
3. destroy(): It is used to destroy the servlet. This method is called only once by the web container when all
threads of the servlet have exited or in a timeout case.
4. getServletConfig(): It returns a servlet config object. This config object is passed in init method. Servlet
config object contains initialization parameters and startup configuration for this servlet.
5. getServletInfo(): It returns a string of information about servlet’s author, version, and copyright etc.
package info.ashok;
import javax.servlet.Servlet;
import javax.servlet.ServletConfig;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
Step 3: Copy all servlet related .class files into classes folder(Which is in WEB-INF folder).
Step 4: Configure the servlet into web.xml file.
• <Servlet>
• <Serlet-mapping>
<servlet>: tag are used for configure the servlet, Within this tag we write Servlet name and class name.
The structure of web.xml files is already defined by sun MicroSystem. So as a developer we should follows the
While configuring a servlet in web.xml, three names are added for it.
<web-app>
<servlet>
<servlet-name>alias name</servlet-name>
<servlet-class>fully qualified class name</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>alias name</servlet-name>
<url-pattern>/url pattern</url-pattern>
</servlet-mapping>
</web-app>
http://localhost:8000/webapp/fs
JAVA / J2EE Mr. Ashok
It’s mandatory that every servlet must be configure in “web.xml” file. When we deploy the project server reads
Step 8: when we deploy any web-based application server will search for web.xml file. If the server found the
xml file it will read the contents from web.xml file and store it in JVM’s memory.
When we observe the above behavior it tomcat server. If it doesn’t found web.xml it’s not displaying any error
message. Where as the web logic server has displayed an error message invalid application type.
To read the contents from xml files are required “parser” programs. In java they are two parser are available.
1. SAX parser
2. DOM parser
When deploy a project if the xml file is valid xml file server reads the contents and store it in JVM’s memory. If
the xml file is invalid SAX parser program throws an error message.
When we develop a project, server will not create any servlet objects.
When the client sends the request to server, server creates two objects. They are request object and response
object. Now the server opens http request format and store the data into request object.
httpRequestFormat
httpResponseFormat
Tomcat Server Client
After the client has sent the request to server, server opens request and get the requested resource. Now the
server checks is there any url pattern configured in web.xml file for that requested resource.
If it is available if does the remaining work. If it is not available in web.xml file server sends httpResponseFormat
by using a status code you.
If the resource is available in web.xml file, server gets the servlet class name. Now the server checks is there
any servlet object is available in the server. If not available it is the responsibility of server to create servlet
object.
The server will try to load the class from class’s folder. If the class file is not available in the classes folder, server
throws an Exception java.lang.classnotFoundException.
If the class is loaded successfully server creates first servlet object and call the init().
JAVA / J2EE Mr. Ashok
Note: init() will be called only once when the servlet object is created.
Now the server will status the Exception service() to Execute the service() server supply request and response
objects as parameters.
After the server has executed service() if it is the responsibility of server to send the response back to client.
When the server sends the response to client, server removes request and response objects. The FirstServlet
object remains same in the server.
It is the responsibility of server to remove servlet object. In the following two scenarios server will remove
servlet objects.
When we stop the server.
When we undeploy the project.
Init(), service(), destroy() are called as servlet life cycle methods. In servlets the business logic will be written as
part of service(), any code which has to be Executed only one time when the server create servlet object is
provide in the init() method.
1. Load Servlet Class: Web container loads the servlet when the first request is received. This step is executed
only once at the time of first request.
2. Create Servlet instance: After loading the servlet class web container creates the servlet instance. Only one
instance is created for a servlet and all concurrent requests are executed on the same servlet instance.
3. Call init() method: After creating the servlet instance web container calls the servlet’s init method. This method
is used to initialize the servlet before processing first request. It is called only once by the web container.
4. Call service() method: After initialization process web container calls service method. Service method is called
for every request. For every request servlet creates a separate thread.
5.Call destoy() method: This method is called by web container before removing the servlet instance. Destroy
method asks servlet to releases all the resources associated with it. It is called only once by the web container
when all threads of the servlet have exited or in a timeout case.
JAVA / J2EE Mr. Ashok
If you observe the Servlet implementation clearly, we are writing our business logic only in service() method. But
unnecessarily every time we need to implement remaining four methods also. It is time waste process and
consumes time as well.
To simplify the development of servlets sun micro systems has given predefined classes. They are GenericServlet,
HttpServlet. The following diagram shows the relationship between these classes.
Content Type
Content Type is also known as MIME Type. MIME stand for Multipurpose internet Mail Extension. It is a HTTP
header that provides the description about what are you sending to the browser (like send image, text, video
etc.).
This is the format of http protocol to carry the response contains to the client..
Example: Suppose you send html text based file as a response to the client the MIME type specification is
response.setcontentType("text/html");
• Base name
• Extension name
Base name: It is the generic name of file.
GenericServlet
GenericServlet class Implements Servlet, ServletConfig and Serializable Interfaces. It provides the
implementation of all the methods of these Interfaces except the service method. GenericServlet class can
handle any type of request so it is protocol Independent. You may create a generic Servlet by inheriting the
GenericServlet class and providing the Implementation of the service method.
Methods of GenericServlet
All methods of Servlet Interface are inherit in GenericServlet class because it Implements Servlet Interface. Following
methods are used in GenericServlet.
import java.io.*;
import javax.servlet.*;
@Override
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>Hello World example using HttpServlet class.</h1>");
out.close();
}
}
The above is the servlet which send html contents to the client. To send the html context to the client we have
to write html tags as part of write() method or print() method.
The above servlet is trying to send html content to the client. Every time when the client send the request it is
displaying same output. These type of applications are called as static web based applications.
By using servlet also we can develop static applications as well as Dynamic applications. By using servlets it is not
recommended to develop static web based applications. It’s always recommended to develop Dynamic web
based applications.
Instead of writing printwriter object we can use “Servlet.OutputStream”. It is recommended to use
ServletOutputStream to send binary data.
Ex: ServletOutputStream out = response.getOutputStream();
out.Println(“Welcome”);
When multiple clients try to access one servlet only one servlet object will be created. This servlet
object is shared between multiple clients.
JAVA / J2EE Mr. Ashok
The following is the servlet code which retrieve the data from data base server and display to the
client.
public class RetrieveRecordsServlet Extends HttpServlet{
public void service( ------- ){
try{
// standard JDBC code
ResultSet rs = stmt.ExecuteQuery(“select * from product”);
PrintWriter out = response.getWriter();
}
}
When we deploy a project and if the server want to create the objects or server want to use the classes it will
check in the following order.
Server checks for class files in classes folder.
If it is not available in classes folder server checks for project lib folder.
If it is not available in project lib folder, server check in server lib folder. If it is not available in these entire
places server throws an Exception NoClassDefFound.
To secure the hard coding we are try to use command line arguments and system properties. But these will not
work in servlets. This is because we can’t supply command line arguments or system properties to the server.
As the server is running the servlet application we can’t use command line arguments or system properties.
ServletContext, ServletConfig objects are used to remove hard coding. These objects are managed by
servers(creation and removing the objects).
Get method is visible to every one (It will be Post method variables are not displayed
2
displayed in the address bar of browser ). in the URL.
Restriction on form data, only ASCII characters No Restriction on form data, Binary data
3
allowed. is also allowed.
Get methods have maximum size is 2000 Post methods have maximum size is 8
4
character. mb.
Restriction on form length, So URL length is
5 No restriction on form data.
restricted
6 Remain in browser history. Never remain the browser history.
<load-on-startup> Element
This is a web.xml configuration elements used to configure a servlet to create servlet object during startup time of
the server or application deploy on server. It is also known as pre initialization of servlet. This element need integer
value to configure.
web.xml
<web-app>
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>com.tutorial4us.FirstServlet</servlet-class>
<load-on-startup>0</load-on-startup>
</servlet>
JAVA / J2EE Mr. Ashok
<servlet>
<servlet-name>servlet2</servlet-name>
<servlet-class>com.tutorial4us.SecondServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
</web-app>
There are defined 2 servlets, both servlets will be loaded at the time of project deployment or server start.
But, servlet1 will be loaded first then servlet2.
ServletContext
ServletContext is one of pre-defined interface available in javax.servlet.*; Object of ServletContext interface is
available one per web application. An object of ServletContext is automatically created by the container when
the web application is deployed.
Assume there exist a web application with 2 servlet classes, and they need to get some technical values from
web.xml, in this case ServletContext concept will works great, i mean all servlets in the current web application
can access these context values from the web.xml but its not the case in ServletConfig.
In a server we will have multiple ServletContext objects. This is based on number of projects available in the
server. We can store the data into ServletContext object. The data stored in the ServletContext object can be
accessible by all the resources of that project.
JAVA / J2EE Mr. Ashok
From the above diagram if we store the data into ServerContext object. FS and SS servlets can access the data.
If we store the data into one ServletContext object the other project can’t access the data from current
project.
Way 1.
First obtain an object of ServletConfig interface ServletConfig interface contain direct method to get Context
object, getServletContext();.
Way 2.
Direct approach, just call getServletContext() method available in GenericServlet [pre-defined]. In general we
are extending our class with HttpServlet, but we know HttpServlet is the sub class of GenericServlet.
Way 3.
We can get the object of ServletContext by making use of HttpServletRequest object, we have direct method
in HttpServletRequest interface.
JAVA / J2EE Mr. Ashok
ServletConfig
An object of ServletConfig is created by the web container for each servlet using its initialization phase. This
object can be used to get configuration information from web.xml file.
Advantage of ServletConfig
If the configuration information is modified from the web.xml file, we don't need to change the Servlet. So it
is easier to manage the web application if any specific content is modified from time to time.
The core advantage of ServletConfig is that you don't need to edit the Servlet file if information is modified
from the web.xml file.
In the above statement, we are directly calling getServletConfig() method as it is available in Servlet interface,
inherited into GenericServlet and defined and further inherited into HttpServlet and later inherited into our
own servlet class.
Way 2
So finally we are able to create ServletConfig object in our servlet class, then how to get the data from that
object…?
interface.
I am not going to explain about these methods, these are similar to ‘Retrieve Client Input Data in Servlet‘ but
here we are retrieving values from web.xml that’s it.
So finally…….
No. of web applications = those many number of ServletContext objects [ 1 per web application ]
No. of servlet classes = those many number of ServletConfig objects
JAVA / J2EE Mr. Ashok
After creating RequestDispatcher object you call forword or include method as per your requirement.
requestDispatcher.forward(request, response);
or
requestDispatcher.include(request, response);
Example:
Create LoginServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
JAVA / J2EE Mr. Ashok
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
}
Create Login.html
Create Web.xml
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
sendRedirect in servlet
sendRedirect () is the method of HttpServletResponse interface which is used to redirect response to another
resource.
sendRedirect RequestDispatcher
1. Creates a new request from the client browser 1. No new request is created.
for the resource.
2. Accept relative url so control can go inside or 2. Not accept relative url so can go only inside the
outside the server. server.
3. New url can be seen in browser. 3. New url can’t be seen in browser.
Servlet Filters
Servlet filters are powerful tools that are available to web application developers using the Servlet 2.3
specification or above. Filters are designed to be able to manipulate a request or response (or both) that is sent
to a web application, yet provide this functionality in a method that won't affect servlets and JSPs being used by
the web application unless that is the desired effect. A good way to think of servlet filters is as a chain of steps
that a request and response must go through before reaching a servlet, JSP, or static resource such as an HTML
page in a web application.
Definition: A filter is an object that performs filtering tasks either on the request to a resource, or on the response
from a resource, or both.
Authentication filters.
Logging and auditing filters.
Data compression filters.
Encryption filters.
Tokenizing Filters.
Filters that trigger resource access events.
When encapsulating common functionality in a filter, the same filter can easily be used with several servlets.
The Filter Interface: There are three methods those need to be implemented in creating our own filter. According
to the javadocs,
JAVA / J2EE Mr. Ashok
Init method: Called by the web container to indicate to a filter that it is being placed into service. We can write
code in init method to get a reference to FilterConfig object which is like ServletConfig object and can read
initialization parameters declared in web.xml.
doFilter method : The doFilter method of the Filter is called by the container each time a request/response pair
is passed through the chain due to a client request for a resource at the end of the chain. The FilterChain passed
in to this method allows the Filter to pass on the request and response to the next entity in the chain.
All our business logic for what filter is created goes into this method. For example, you can place log statements
so that we can know after the resource is served and again filter is called after serving the resource.
destroy method: Called by the web container to indicate to a filter that it is being taken out of service.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
JAVA / J2EE Mr. Ashok
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
-----------------------------------------------------------web.xml----------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
JAVA / J2EE Mr. Ashok
<display-name>WebAppWithFilter</display-name>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.ashoksoft.apps.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>LoggerFilter</filter-name>
<filter-class>com.ashoksoft.apps.LoggerFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>LoggerFilter</filter-name>
<url-pattern>/ HelloServlet </url-pattern>
</filter-mapping>
</web-app>
-----------------------------------------------------------------0----------------------------------------------------------------------------
Here notice that, the LoggerFilter is mapped to HelloServlet in filter-mapping tag. That means this filter is applied
whenever a request for a servlet with name HelloServlet is made.
Deploy your application under tomcat server and hit url http://localhost:8080/WebAppWithFilter/HelloServlet .
Filter Chaining
A FilterChain is an object provided by the servlet container to the developer giving a view into the invocation
chain of a filtered request for a resource. Filters use the FilterChain to invoke the next filter in the chain, or if the
calling filter is the last filter in the chain, to invoke the resource at the end of the chain.
JAVA / J2EE Mr. Ashok
The javax.servlet.FilterChain interface is an argument to the doFilter() method. This interface has only one
method, doFilter(), which are used by the programnmer to causes the next filter in the chain to be invoked.
Methods in javax.servlet.FilterChain interface:
Note: The deployment descriptor is used to tell the container which, if any, filters in which sequence to call for
each servlet in the application.
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public AuthFilter() {
// TODO Auto-generated constructor stub
}
}
Step 4 : Configure Servlet & Filter in deployment descriptor (web.xml)
----------------------------------------------------------web.xml---------------------------------------------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>com.ashoksoft.apps.HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/HelloServlet</url-pattern>
</servlet-mapping>
<filter>
<filter-name>LoggerFilter</filter-name>
<filter-class>com.ashoksoft.apps.LoggerFilter</filter-class>
</filter>
<filter-mapping>
JAVA / J2EE Mr. Ashok
<filter-name>LoggerFilter</filter-name>
<url-pattern>/HelloServlet</url-pattern>
</filter-mapping>
<filter>
<filter-name>AuthFilter</filter-name>
<filter-class>com.ashoksoft.apps.AuthFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>AuthFilter</filter-name>
<url-pattern>/HelloServlet</url-pattern>
</filter-mapping>
</web-app>
-----------------------------------------------------------------------0---------------------------------------------------------------------------
Deploy your application under tomcat server and hit url http://localhost:8080/WebAppWithFilter/HelloServlet
.You will see the messages as follows
If there are two filters, for example, the key steps of this mechanism would be as follows
The target servlet is requested. The container detects that there are two filters and creates the filter
chain.
The first filter in the chain is invoked by its doFilter() method.
The first filter completes any preprocessing, then calls the doFilter() method of the filter chain. This
results in the second filter being invoked by its doFilter() method.
The second filter completes any preprocessing, then calls the doFilter() method of the filter chain. This
results in the target servlet being invoked by its service() method.
When the target servlet is finished, the chain doFilter() call in the second filter returns, and the second
filter can do any postprocessing.
When the second filter is finished, the chain doFilter() call in the first filter returns, and the first filter can
do any postprocessing.
When the first filter is finished, execution is complete.
None of the filters are aware of their order. Ordering is handled entirely through the filter chain,
according to the order in which filters are configured in web.xml.
Servlet Listeners
Listeners are the classes which listens to a particular type of events and when that event occurs , triggers the
functionality. Each type of listener is bind to a type of event. In this chapter we will discuss the types of listeners
supported by servlet framework.
During the lifetime of a typical web application, a number of events take place, such as:
The Servlet API provides a number of listener interfaces we can implement in order to react to these events.
There are total eight type of listeners available in servlet framework which listens to a particular event and they
are –
1. ServletRequestListener
2. ServletRequestAttributeListener
3. ServletContextListener
4. ServletContextAttributeListener
5. HttpSessionListener
6. HttpSessionAttributeListener
7. HttpSessionActivationListener
8. HttpSessionBindingListener
As the configurations of servlets, filters goes inside web.xml, similarly listeners are also configured inside web.xml
using <listener> </listener> tag.
JAVA / J2EE Mr. Ashok
Syntax: <listener>
<listener-class></listerner-class>
</listener>
ServletRequestListener
ServletRequestListener listens to ServletRequestEvent event which gives a notification when request is created
or destroyed.
A ServletRequest is defined as coming into scope of a web application when it is about to enter the first servlet
or filter of the web application, and as going out of scope as it exits the last servlet or the first filter in the chain.
Example:
------------------------------------------------------MyServletRequestListener.java---------------------------------------------
package com.ashoksoft.apps;
import javax.servlet.ServletRequest;
import javax.servlet.ServletRequestEvent;
import javax.servlet.ServletRequestListener;
public class MyServletRequestListener implements ServletRequestListener {
/**
* Default constructor.
*/
public MyServletRequestListener() {
}
public void requestDestroyed(ServletRequestEvent servletRequestEvent)
{
ServletRequest request = servletRequestEvent.getServletRequest();
System.out.println("Request Destroyed");
}
public void requestInitialized(ServletRequestEvent servletRequestEvent)
{
ServletRequest request = servletRequestEvent.getServletRequest();
System.out.println("Request initialized");
JAVA / J2EE Mr. Ashok
}
}
---------------------------------------------------------web.xml---------------------------------------------------------------------------
<listener>
<description> Servlet Request Listener Example</description>
<listener-class> com.ashoksoft.apps.MyServletRequestListener</listener-class>
</listener>
----------------------------------------------------------------------------------------------------------------------------------------
ServletRequestAttributeListener
ServletRequestAttributeListener listens to ServletRequestAttributeEvent event which gives a notification when
any object is added, removed or replaced from request .
Attribute name and value that has been added, removed or replaced can be obtained from the getName() and
getValue() method of ServletRequestAttributeEvent
ServletContextListener
ServletContextEvent class gives notifications about changes to the servlet context of a web application.
ServletContextListener receives the notifications about changes to the servlet context and perform some action.
ServletContextListener is used to perform important task at the time when context is initialized and destroyed.
In short, ServletContextEvent and ServletContextListener works in pair, whenever Servlet COntext changes,
ServletContextEvent publishes a notification which is received by ServletContextListener and then, based on that
certain tasks are performed by it.
ServletContext object can be obtained from ServletContextEvent and listener can set the attributes in Servlet
context object which can be used in servlets later.
We can use the “ServletContextListener “ listener for any activity that is required either at the application
deployment time or any clean up activity required when application is destroyed. One of the practical example
that I can think of is initializing database connections and clean up of database connections.
ServletContextAttributeListener
ServletContextAttributeListener listens to SessionContexAttributetEvent event which gives a notification when
any object is added, removed or replaced from servlet context .
JAVA / J2EE Mr. Ashok
ServletContextAttributeListener is the interface and it defines three methods –
HttpSessionListener
HttpSessionListener listens to HttpSessionEvent event which gives a notification when session is created or
destroyed.
HttpSessionAttributeListener
HttpSessionAttributeListener listens to HttpSessionBindingEvent event which gives a notification when any
object is added, removed or replaced from session.
Annotations
Java Annotations allow us to add metadata information into our source code, although they are not a part of
the program itself. Annotations were added to the java from JDK 5. Annotation has no direct effect on the
operation of the code they annotate (i.e. it does not affect the execution of the program).
Annotations basics
An annotation always starts with the symbol @ followed by the annotation name. The symbol @ indicates to the
compiler that this is an annotation.
For e.g. @Override
here @ symbol represents that this is an annotation and the Override is the name of this annotation.
1) @Override:
While overriding a method in the child class, we should use this annotation to mark that method. This makes
code readable and avoid maintenance issues, such as: while changing the method signature of parent class, you
must change the signature in child classes (where this annotation is being used) otherwise compiler would throw
compilation error. This is difficult to trace when you haven’t used this annotation.
public class MyParentClass {
@Override
public void justaMethod() {
System.out.println("Child class method");
}
}
2) @Deprecated
@Deprecated annotation indicates that the marked element (class, method or field) is deprecated and should no
longer be used. The compiler generates a warning whenever a program uses a method, class, or field that has already
been marked with the @Deprecated annotation. When an element is deprecated, it should also be documented using
the Javadoc @deprecated tag, as shown in the following example. Make a note of case difference with @Deprecated
and @deprecated. @deprecated is used for documentation purpose.
Example:
@Deprecated
public void anyMethodHere(){
// Do something
}
JAVA / J2EE Mr. Ashok
3) @SuppressWarnings
This annotation instructs compiler to ignore specific warnings. For example in the below code, I am calling a deprecated
method (lets assume that the method deprecatedMethod() is marked with @Deprecated annotation) so the compiler
should generate a warning, however I am using @@SuppressWarnings annotation that would suppress that
deprecation warning.
@SuppressWarnings("deprecation")
void myMethod() {
myObject.deprecatedMethod();
}
1. @HandlesTypes
2. @HttpConstraint
3. @HttpMethodConstraint
4. @MultipartConfig
5. @ServletSecurity
6. @WebFilter
7. @WebInitParam
8. @WebListener
9. @WebServlet
Class annotated with @WebServlet still needs to extend the HttpServlet class. With this annotation we can
specify servlet-name, url-mapping, load on Start up, description, init params, async supported etc
Let’s take an example Welcome Servlet which is defined in a web.xml like below
<servlet>
<description>Welcome Servlet</description>
<servlet-name>WelcomeServlet</servlet-name>
<servlet-class>com.servlet.tutorial.WelcomeServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>WelcomeServlet</servlet-name>
<url-pattern>/WelcomeServlet</url-pattern>
</servlet-mapping>
JAVA / J2EE Mr. Ashok
Same servlet configuration can be done with @WebServlet annotation as shown below. @WebServlet
annotation is highlighted below and all the attributes configured in web, xml are configured in annotation itself.
With this approach, we need not to configure any entry in web.xml for Welcome Servlet.
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@WebServlet(name="/AnnotatedServlet",urlPatterns="/AnnotatedServlet ",loadOnStartup=1,
description="Welcome Servlet")
public class AnnotationServlet extends HttpServlet {
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.print("<h1>Hello World example using annotations.</h1>");
out.close();
}
}
--------------------------------------------------------------0--------------------------------------------------------------------------------
Note: Did you notice the word “urlPatterns”? It is not a pattern, it is patterns which means we can map a
servlet with multiple URLs like below
Syntax :
@WebServlet (
name="/AnnotatedServlet",
urlPatterns= {"/AnnotatedServlet","/HelloServlet"},
loadOnStartup=1,
description="Welcome Servlet"
)
@WebInitParam: This annotation is used for init-param configurations of servlet. Remember we can define
multiple init parameters for a servlet which we can get in the servlet using servlet config object.
JSP technology is used to create dynamic web application same like Servlet technology. It is another web technology
given by Sun MicroSystem for the development of dynamic web pages an the client browser. It provides a tag based
approach to develop java web components.
JSP have .jsp extension, we can directly access these JSP pages from client system browser window. Because jsp pages
are contains outside of the WEB-INF folder.
A JSP page consists of Html tags and JSP tags. The jsp pages are easier to maintain than servlet. It provides some
additional features such as Expression Language, Custom Tag etc.
A JSP is called as page but not program because a JSP contains totally tags. Every JSP is internally converted into a
Servlet by the server container.
Why JSP?
The first technology given for the development of web application is CGI. In CGI have some drawback, So Sun
MicroSystem develop a new technology is servlet. But working with Servlet Sun MicroSystem identify some problem,
Servlet technology need in depth java code and Servlet is failed to attract the programmer.
JSP Tag
A JSP page contains both html tags and JSP tags. Html tags will produce static output and JSP tags will produced
dynamic output. Because of JSP tags we called as JSP is dynamic web page.
JSP
JSP is the extension of servlet that provides the solution of all above problems. JSP defines a structure which is java
code inside HTML code. With this structure it simplifies the web development.
Javax.servlet.jsp package.
Javax.servlet.jsp and its sub packages provide the classes and interfaces facilitate the development of JSP.
Note: jspInit(), _jspService() and jspDestroy() are the life cycle methods of JSP.
For first request all 6 steps will be executed but for next requests of this JSP page 2nd and 3rd step will not
execute.
Html is a Client side Technology and JSP is a Server side Technology. Some other differences are given below;
HTML JSP
1 Html is given by w3c (World Wide Web Consortium). JSP is given by SunMicro System.
2 Html generated static web pages. JSP generated dynamic web pages.
3 It do not allow to place java code inside Html pages. JSP allows to place java code inside JSP pages.
4 It is Client side technology It is a Server side technology.
5 Need Html Interpreter to execute these code. Need JSP container to execute jsp code.
6 It does not allow to place custom tag or third party tag. It allow to place custom tag or third party tag.
Servlet life cycle with an additional step which is required to translate a JSP into Servlet.
JAVA / J2EE Mr. Ashok
• _jspService()
• jspDestroy()
JAVA / J2EE Mr. Ashok
We can override jspInti(), jspDestroy(). But we can not override _jspService() method.
To inform the programmer that you should not override the service() method the method name is started with
'_' symbol.
Features of JSP
JSP are tag based approach to develop dynamic web application. JSP have all the features of Servlet because it is
internally Servlet. It have following feature these are;
• Extension to Servlet
• Powerful
• Portable
• Flexible
• Easy
• Less code than Servlet
Extension to Servlet: JSP is Extension to Servlet, it have all the features of servlet and it have also implicit objects,
predefined tags, expression language and Custom tags in JSP, that makes JSP easy to develop any application.
Powerful: These are internally Servlet, means consists byte code, so that all java features are applicable in case of
jsp like robust, dynamic, secure, platform independent.
Portable: JSP tags will process and execute by the server side web container, So that these are browser
independent and j2ee server independent.
Flexible: Allows to defined custom tags, the developer can fill conferrable to use any kind, framework based
markup tags in JSP.
Easy: JSP is easy to learn, easy to understand and easy to develop. JSPs are more convenient to write than Servlets
because they allow you to embed Java code directly into your HTML pages, in case of servlets you embed HTML
inside of Java code.
Less code than Servlet: In JSP, we can use a lot of tags such as action tags, jstl, custom tags etc. that reduces the
code.
JSP Translation
Each JSP page is internally translated into an equivalent Servlet. Every JSP tag written in the page will be internally
converted into an equivalent java code by the containers this process is called translation.
• Translation phase
Servlet.
Request processing phase: It is process of executing service() of jsp and generating response data on to the
browser.
JAVA / J2EE Mr. Ashok
When first time a request to a jsp then translation phase occurs first and then after service phase will be executed.
From next request to the jsp, only request processing phase is got executed but translation phase is not because jsp
is already translated.
Note:
• If we shutdown and restart the Servet then only request processing phase will be executed, Because
when we shutdown the server java and class files are not deleted from the server.
• If we remove the class file from server then partial translation occurs..
• If we remove both java and class file from server then again translation occurs.
• When a jsp is translated into an equivalent Servlet then that Servlet extends some base class
provided by the server, but internally it extends HttpServlet.
<web-app>
<servlet>
<servlet-name>test</servlet-name>
<jsp-file>/One</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>test</>
<url-pattern>/srv1</url-pattern>
</servlet-mapping>
</web-app>
Note: If we configure a jsp in web.xml then we can send the request to the jsp either by using jsp filename or by
httpp://localhost:2014/root/One.jsp
JAVA / J2EE Mr. Ashok
or
httpp://localhost:2014/root/srv1
With less request processing logic with more response generation logic we need JSP.
In Servlet, there is no such method for In JSP, we can use the client side validations using
4
running JavaScript at client side. running the JavaScript at client side.
For running a JSP there is no need to make an entry
To run a Servlet you have to make an entry
of Servlet mapping into the web.xml file externally,
5 of Servlet mapping into the deployment
you may or not make an entry for JSP file as
descriptor file i.e. web.xml file externally.
welcome file list.
Coding of jsp is easier than Servlet because it is tag
6 Coding of Servlet is harden than jsp.
based.
In MVC pattern, Servlet plays a controller In MVC pattern, JSP is used for showing output
7
role. data i.e. in MVC it is a view.
8 Servlet accept all protocol request. JSP will accept only http protocol request.
Because of jsp page contains outside of WEB-INF, JSP is a public file to the web application. You can directly access
these JSP pages from client system browser window.
Here i will give you a simple jsp example. First you write your first jsp code on any editor and save with .jsp
JSP program must be save with the .jsp extension. And for compile jsp code simply follow step of compilation
servlet code.
<html>
JAVA / J2EE Mr. Ashok
<body>
<% out.print("Hello word"); %>
</body>
</html>
Result
Hello word
After write your jsp code, deploy jsp program in your root directory and start server. Follow below steps to run jsp
code.
• Start Server
http://localhost:portnumber/RootDirectory/jspfile
Example
http://localhost:2015/jspapplication/index.jsp
Scripting Element
In JSP, java code can be written inside the jsp page using the scriptlet tag. JSP Scripting elementare written inside <%
%> tags. These code inside <% %> tags are processed by the JSP engine during translation of the JSP page.
JSP Comment
This is used to define comment description in jsp page. In jsp page we can insert three types of comments they
are;
• Jsp comment
• Html comment
• Java comment
JSP Comment
This type of comment is called as hidden comment, because it is invisible when a jsp is translated into a servlet
internally.
Syntax
JAVA / J2EE Mr. Ashok
Html Comment
Html comment tag is common for Html, xml and jsp. In a jsp page if we write html comment these comment are
Java Comment
We can write a single or multiline comment of java in a scriptlet tag. Java comment are allowed only inside
scriptlet tags because we can insert java code in a jsp only at a scriptlet tags.
/*
Multiline comment
*/
The variable and methods will become global to that jsp. It means in that jsp we can use those variables any where
and we can call those method any where.
At the time of translation container inserts the declaration tag into the class. So the variables become instants
variables and methods will become instants methods.
The code written inside the jsp declaration tag is placed outside the service() method of auto-generated Servlet, so
it does not get memory at each request.
Syntax: <%! Variable or method Declaration %>
JAVA / J2EE Mr. Ashok
JSP Expression Tag
Expression tag is used, to find the result of the given expression and send that result back to the client browser. In
other words; These are used to show or express the result or response on browser. We can use this as a display
result of variable and invoking method.
Each Expression tag of jsp will be internally converted into out.print() statement. In jsp out is an implicit object.
The expression tags are converted into out.print() statement and insert into the _jspService(-,-) of the servlet class
by the container.
The expression tags written in a jsp are executed for each request, because _jspService(-,-) is called for each request.
One expression tag should contains one java expression only. In a jsp we can use expression tag for any number of
times.
Expression does not need any semicolon (;) by default it places under jsp service() method scope.
Note: In jsp, the implicit object are allowed into the tags, which are inserted into _jspService(-,-). An expression
tag goes to _jspService(-,-) only. So implicit object are allowed in the expression tag.
It use to define or insert java code in a jsp. Every java statement should followed by semicolon (;). It will be place
The scriptlet tags goes to _jspService(-,-), during translation. It means scriptlet tags are executed for each request.
We can use implicit object of jsp in a scriptlet tag also because scriptlet tag goes to _jspService(-,-) only. In a jsp
implicit object are allowed in expression tags and scriptlet tags but not in the declaration tags.
JSP directives
JSP directives provides the instructions and directions to the web container about how to control the processing JSP
page.
JAVA / J2EE Mr. Ashok
The directive elements are used to do page related operation during page translation time. JSP supports 3 types of
directive elements, they are;.
• Page directive
• Include directive
• Taglib directive
Page directive is used to provide the instructions to the web container that are specific to the current JSP page. It
defines the page specific attributes like scripting language, error page etc.
Code Re-usability
</body>
</html>
Note: The include directive includes the original content, so the actual page size grows at run-time.
Taglib Directive
This is used to use custom tags in JSP page, here the custom tag may be user defined ot JSTL tag or strust, JSF,..... etc.
2. prefix: This attribute is to inform the web container that this markup is used for custom actions.
JAVA / J2EE Mr. Ashok
JSP implicit objects
These objects are created by JSP Engine during translation phase (while translating JSP to Servlet). They are
being created inside service method so we can directly use them within Scriptlet without initializing and
declaring them. There are total 9 implicit objects available in JSP.
out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
page java.lang.Object
pageContext javax.servlet.jsp.PageContext
config javax.servlet.ServletConfig
out
It’s an instance of javax.servlet.jsp.JspWriter. This allows us to access Servlet output stream. The output
which needs to be sent to the client (browser) is passed through this object. In simple words out implicit
object is used to write content to the client.
<%
out.print("Welcome");
%>
request
The JSP request is an implicit object of type HttpServletRequest i.e. created for each jsp request by the web
container. The main purpose of request implicit object is to get the data on a JSP page which has been entered
by user on the previous JSP page. While dealing with login and signup forms in JSP we often prompts user to fill
in those details, this object is then used to get those entered details on an another JSP page (action page) for
validation and other purposes.Example of request implicit object where we are printing the name of the user
with welcome message.
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
JAVA / J2EE Mr. Ashok
</form>
welcome.jsp
Example
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
response
It is basically used for modfying or delaing with the response which is being sent to the client(browser) after
processing the request.
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
%>
config
config object is an implicit object of type ServletConfig and it is created by the container, whenever servlet object is
created. This object can be used to get initialization parameter for a particular JSP page.
config object is created by the web container for every jsp page. It means if a web application has three jsp pages
then three config object are created.
JAVA / J2EE Mr. Ashok
In jsp, it is not mandatory to configure in web.xml. If we configure a jsp in web.xml then the logical name and init
parameter given in web.xml file are stored into config object by the container.
config object is accessible, only if the request is given to the jsp by using its url pattern, but not with name of the
jsp.
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
web.xml file
<web-app>
<servlet>
<servlet-name>Home</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
<init-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>Home</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
</web-app>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
JAVA / J2EE Mr. Ashok
String driver=config.getInitParameter("dname");
out.print("driver name is="+driver);
%>
page
In JSP, page is an implicit object of type Object class. When a jsp is translated to an internal Servlet, we can find the
Object page=this;
Since, it is of type Object it is less used because you can use this object directly in jsp.For example:
Example
session
In JSP, session is an implicit object of type HttpSession.This object used to set,get or remove attribute or to get
session information.
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
JAVA / J2EE Mr. Ashok
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
One.jsp
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
Exception
JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to print the exception.
But it can only be used in error pages.
Example of Exception implicit object
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
response.sendRedirect("http://www.google.com");
JAVA / J2EE Mr. Ashok
%>
application
In JSP, application is an implicit object of type ServletContext. this application object in the Servlet programming is
ServletContext.
For all jsp in a web application, there must be a single application object with application object we can share the
data from one JSP to any other JSP in the web application.
The instance of ServletContext is created only once by the web container when application or project is deployed
on the server.
This object can be used to get initialization parameter from configuration file (web.xml). It can also be used to get,
set or remove attribute from the application scope.
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
out.print("Welcome "+request.getParameter("uname"));
String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);
%>
web.xml
<web-app>
<servlet>
<servlet-name>One</servlet-name>
<jsp-file>/welcome.jsp</servlet-class>
</servlet>
JAVA / J2EE Mr. Ashok
<servlet-mapping>
<servlet-name>One</servlet-name>
<url-pattern>/welcome</url-pattern>
</servlet-mapping>
<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>
</web-app>
pageContext
In JSP, pageContext is an implicit object of type PageContext class.The pageContext object can be used to set,get or
• page
• request
• session
• application
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
<%
JAVA / J2EE Mr. Ashok
String name=request.getParameter("uname");
out.print("Welcome "+name);
pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
%>
One.jsp
String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
Action elements are used to performs specific operation using JSP container, like setting values into java class,
getting values from java class. The JSP action elements classified into two types are;
• <jsp: include>
• <jsp: forward>
• <jsp: param>
• <jsp: params>
• <jsp: plugin>
• <jsp: useBean>
• <jsp: setProperty>
• <jsp: getProperty>
• <jsp: fallback>
Session Tracking
Session is the conversion of user within span of time. In general meaning particular interval of time.
Session Tracking is remembering and recording of client conversion in span of time. It is also called as session
management.
If web application is capable of remembering and recording of client conversion in span of time then that web
application is called as stateful web application.
• Http protocol is stateless, to make stateful between client and server we need Session Tracking.
• Session Tracking is useful for online shopping, mailing application, E-Commerce application to track
the conversion.
• Http protocol is stateless, that means each request is considered as the new request. You can see in
below image.
JAVA / J2EE Mr. Ashok
If Http is stateful protocol for multiple requests given by client to web application single connection will be
used between browser and web server across the multiple requests. This may make clients to engage
connection with web server for long time event though the connection are ideal. Due to this the web server
reach to maximum connections even though most of its connection are idle. To overcome this problem Http is
given as stateless.
• Cookies
• URL Rewriting
• Hidden Form Field
• HttpSession
JAVA / J2EE Mr. Ashok
Cookies
Cookies are text files stored on the client computer and they are kept for various information like name, a
single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a
version number.
Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the
addCookie() method. This method sends cookie information over the HTTP response stream. getCookies()
method is used access the cookies that are added to response object.
In Http Session technique, container internally generates a cookies for transferring the session ID between
server and client. Apart from container generated cookie a servlet programmer can also generate cookies for
storing the data for a client.
By default, each request is considered as a new request. In cookies technique, we add cookie with response
from the servlet. So cookie is stored in the cache of the browser (chrome, firefox) at client side. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old
user.
When session ID is not required and when less number of input values are submitted by client in that case in
place of using HttpSession Technique you can use cookies Technique to reduce the burden on server.
Points to Remember
• Cookies is pressistance resource which is stores at client location.
• We can store 3000 cookies in cookies file at a time.
• The cookies are introduced by net scape communication.
JAVA / J2EE Mr. Ashok
• Cookies files exist up to 3 year.
• Size of cookies is 4 kb.
Type of Coockies
There are two types of cookies, those are given below;
• Persistent cookies
In-memory cookies: By default cookie is in-memory coockie, This type of cookie is lives until that browser is
destroy(close). It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookies: Presestent cookie lives on a browser until its expiration time is reached it means ,
eventhough you close or reopen the browser but still the cookie exists on the browser. It is valid for multiple
session. It is not removed each time when user closes the browser. It is removed only if user logout or signout.
Cookie class
javax.servlet.http.Cookie class provides the functionality of using cookies. It provides a some constructor and
methods for cookies.
Cookies are text files stored on the client computer and they are kept for various information like name, a
single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a
version number.
Cookies are created using Cookie class present in Servlet API. Cookies are added to response object using the
addCookie() method. This method sends cookie information over the HTTP response stream. getCookies()
method is used access the cookies that are added to response object.
In Http Session technique, container internally generates a cookies for transferring the session ID between
server and client. Apart from container generated cookie a servlet programmer can also generate cookies for
storing the data for a client.
By default, each request is considered as a new request. In cookies technique, we add cookie with response
from the servlet. So cookie is stored in the cache of the browser (chrome, firefox) at client side. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user as the old
user.
When session ID is not required and when less number of input values are submitted by client in that case in
place of using HttpSession Technique you can use cookies Technique to reduce the burden on server.
JAVA / J2EE Mr. Ashok
Points to Remember
• Cookies is pressistance resource which is stores at client location.
• We can store 3000 cookies in cookies file at a time.
• The cookies are introduced by net scape communication.
• Cookies files exist up to 3 year.
• Size of cookies is 4 kb.
Add Cookies
To read Cookies from browser to a servlet, we need to call getCookies methods given by request object and it
returns an array type of cookie class.
response.addCookie(c1);
Cookie c[]=request.getCookie();
Advantage of Cookie
<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
JAVA / J2EE Mr. Ashok
</servlet-mapping>
</web-app>
In Hidden Form Field we are use html tag is <input type="hidden"> and with this we assign session ID value.
<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>
JAVA / J2EE Mr. Ashok
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
try{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
//Getting the value from the hidden field
String n=request.getParameter("uname");
out.print("Hello "+n);
JAVA / J2EE Mr. Ashok
out.close();
}catch(Exception e){System.out.println(e);}
}
}
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
URL Rewriting
URL Rewriting track the conversion in server based on unique session ID value.
If the client has disabled cookie in the browser then coockie are not work for session management. In that case you
can use URL rewriting technique for session managment. URL rewriting will always work.
JAVA / J2EE Mr. Ashok
Advantage of URL Rewriting
• It will always work whether cookie is disabled or not (browser independent).
• Extra form submission is not required on each pages
<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
JAVA / J2EE Mr. Ashok
</web-app>
HttpSession
HttpSession is another kind of session management technique, In this technique create a session object at server
side for each client. Session is available until the session time out, until the client log out. The default session time is
30 minutes and can configure explicit session time in web.xml file. Configure session time in web.xml
<web-app>
<session-config>
<session-timeout>40</session-timeout>
</session-config>
</web-app>
HttpSession Api
<form action="servlet1">
Name:<input type="text" name="userName"/> <br/>
<input type="submit" value="continue"/>
</form>
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet {
JAVA / J2EE Mr. Ashok
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
web.xml
<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>FirstServlet</servlet-class>
JAVA / J2EE Mr. Ashok
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>s2</servlet-name>
<servlet-class>SecondServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>
The purpose of EL is to produce scriptless JSP pages. The syntax of EL in a JSP is as follows:
${expr}
Here expr is a valid EL expression. An expression can be mixed with static text/values and can also be combined
with other expressions to form larger expression.
JAVA / J2EE Mr. Ashok
JSP Expression Language provides many implicit objects that we can use to get attributes from different scopes and
parameter values. The list is given below.
pageScope It is used to access the value of any variable which is set in the Page scope
requestScope It is used to access the value of any variable which is set in the Request scope.
sessionScope It is used to access the value of any variable which is set in the Session scope
applicationScope It is used to access the value of any variable which is set in the Application scope
-------------------------------------------------------index.jsp-------------------------------------------------------------
<html>
<head>
<title>Welcome Page</title>
</head>
<body>
<h1>Welcome ${param.name}</h1>
</body>
</html>
------------------------------------------------------------0-------------------------------------------------------------------------------------
The JSTL tags can be classified, according to their functions, into following JSTL tag library groups that can be
used when creating a JSP page:
Core tags
Core tags provide variable support, flow control and URL administration and so on
Function Tags
Function tags gives support for sting manipulation.
URL tag is http://java.sun.com/jsp/jstl/functions and where fn is the prefix.
JAVA / J2EE Mr. Ashok
JSTL SQL Tags
Provides SQL support and the URL for SQL tag is http://java.sun.com/jsp/jstl/sql and where prefix is sql.
import java.io.IOException;
import javax.servlet.jsp.*;
import org.apache.commons.lang.StringUtils;
@Override
public int doStartTag() throws JspException {
try {
JspWriter out = pageContext.getOut();
out.println(StringUtils.countMatches(inputstring, lookupstring));
} catch (IOException e) {
e.printStackTrace();
}
return SKIP_BODY;
}
}
-----------------------------------------0-----------------------------------------------
In the above code, we have an implementation of the doStartTag() method which is must if we are
extending TagSupport class. We have declared two variables inputstring and lookupstring. These variables
represents the attributes of the custom tag. We must provide getter and setter for these variables in order to set
the values into these variables that will be provided at the time of using this custom tag. We can also specify
whether these attributes are required or not.
-------------------------------------MyTags.tld----------------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<taglib>
<tlibversion>1.0</tlibversion>
<jspversion>1.1</jspversion>
<shortname>cntmtchs</shortname>
<info>Sample taglib for Substr operation</info>
<uri>http://studytonight.com/jsp/taglib/countmatches</uri>
<tag>
<name>countmatches</name>
<tagclass>com.studytonight.taghandler.CountMatches</tagclass>
<info>String Utility</info>
<attribute>
<name>inputstring</name>
<required>true</required>
</attribute>
<attribute>
<name>lookupstring</name>
<required>true</required>
</attribute>
</tag>
</taglib>
The taglib element specifies the schema, required JSP version and the tags within this tag library. Each tag
element within the TLD represents an individual custom tag that exist in the library. Each of these tag should
have a tag handler class associated with them.
The uri element represents a Uniform Resource Identifier that uniquely identifies the tag library.
JAVA / J2EE Mr. Ashok
The two attribute elements within the tag element represents that the tag has two attributes and the true value
provided to the required element represents that both of these attributes are required for the tag to function
properly.
------------------------------------------index.jsp-------------------------------------
<%@taglib prefix="mytag" uri="/WEB-INF/CountMatchesDescriptor.tld"%>
<body>
<h3>Custom Tag Examole</h3>
<mytag:countmatches inputstring="ashoksoft" lookupstring="o" />
</body>
</html>
------------------------------------------0---------------------------------------------
If this tag works fine it should print a value 3 in the browser as there 't' occurs 2 times in the word “ashoksoft”..
JNDI
The Java Naming and Directory Interface (JNDI) is an application programming interface (API) for accessing
different kinds of naming and directory services. JNDI is not specific to a particular naming or directory service,
it can be used to access many different kinds of systems including file systems; distributed objects systems like
CORBA, Java RMI, and EJB; and directory services like LDAP, Novell NetWare, and NIS+.
JAVA / J2EE Mr. Ashok
JNDI is similar to JDBC in that they are both Object-Oriented Java APIs that provide a common abstraction for
accessing services from different vendors. While JDBC can be used to access a variety of relational databases,
JNDI can be used to access a variety of of naming and directory services.
The benefits of using a JNDI DataSource
There are major advantages to connecting to a data source using a DataSource object registered with a JNDI
naming service rather than using the DriverManager facility.
The first is that it makes code more portable. (With the DriverManager, the name of a JDBC driver
class, which usually identifies a particular driver vendor, is included in application code. This makes
the application specific to that vendor's driver product and thus non-portable)
It makes code much easier to maintain. If any of the necessary information about the data source
changes, only the relevant DataSource properties need to be modified
Multiple wars can use the same connection pool which might be better use of resources
It's a fine way to externalize configuration.
Add this element inside the root element <Context> in a context.xml file. There are two places where the
context.xml file can reside (create one if not exist):
1. Inside /META-INF directory of a web application: the JNDI DataSource is only available to the
application itself, thus it cannot be shared among other ones. In addition, this makes the configuration
dependent on the application.
2. Inside $CATALINA_BASE/conf directory (server conf folder): this is the preferred place because the
JNDI DataSource will be available to all web applications and it’s independent of any applications.
If you are using Tomcat inside Eclipse IDE, you need to modify the context.xml file under the Servers project. That
is because Eclipse made a copy of Tomcat configuration:
The following table describes the attributes specified in the above configuration:
This is necessary in order to make the JNDI DataSource available to the application under the specified
namespace jdbc/UsersDB
Step 4: Create JSP Page in web application to retrieve Employees data from Database with JNDI DataSource
JAVA / J2EE Mr. Ashok
Note: Here, we use the JSTL’s SQL tag query to make a SELECT query to the database. Note that
the DataSource attribute refers to the JNDI resource name declared in the web.xml file.
After obtaining the connection, we can write JDBC code using this conn object
Tomcat will look up the specified resource name and inject an actual implementation when it discovers this
annotation. Therefore, the servlet code looks like this:
JAVA / J2EE Mr. Ashok
If we want user to choose files from file system and upload to server then following are the important points
to be noted down:
Project Structure
JAVA / J2EE Mr. Ashok
====================================index.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>
</head>
<body>
<form action="UploadServlet" enctype="multipart/form-data"
method="post">
<table>
<tr>
<td>Enter Name :</td>
<td><input type="text" name="uname" /></td>
</tr>
<tr>
<td>Select Resume :</td>
<td><input type="file" name="file1" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Upload"
/></td>
</tr>
</table>
</form>
</body>
</html>
==========================UploadServlet.java==========================
package com.ashoksoft.apps;
import java.io.File;
JAVA / J2EE Mr. Ashok
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
try {
List<FileItem> list = upload.parseRequest(request);
Iterator<FileItem> itr = list.iterator();
String uname = "";
while (itr.hasNext()) {
FileItem fi = itr.next();
if (fi.isFormField()) {
String fieldName = fi.getFieldName();
if (fieldName.equals("uname")) {
uname = fi.getString();
}
} else {
String loc = fi.getName();
String fileName =
loc.substring(loc.lastIndexOf("\\") + 1);
File f = new File(filesPath + File.separator +
fileName);
fi.write(f);
out.print("File uploaded successfully");
out.write("<a href=\"DownLoadServlet?fileName="
+ fi.getName() + "\">Download " +
f.getName()
+ "</a>");
JAVA / J2EE Mr. Ashok
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
----------------------------------------------- DownloadServlet.java-----------------------------------------------------------------
package com.ashoksoft.apps;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
response.setContentType("APPLICATION/OCTET-STREAM");
String fileLoc = request.getParameter("filename");
response.setHeader("Content-Dispostion",
"attachment;filename=\"" + f.getName() + "\"");
int i = fis.read();
while (i != -1) {
out.write(i);
i = fis.read();
}
fis.close();
out.close();
}
}
====================================web.xml================================================
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
JAVA / J2EE Mr. Ashok
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>FileUploadAndDownload</display-name>
<servlet>
<servlet-name>UploadServlet</servlet-name>
<servlet-class>com.ashoksoft.apps.UploadServlet</servlet-class>
</servlet>
<servlet>
<display-name>DownloadServlet</display-name>
<servlet-name>DownloadServlet</servlet-name>
<servlet-class>com.ashoksoft.apps.DownloadServlet</servlet-
class>
</servlet>
<servlet-mapping>
<servlet-name>UploadServlet</servlet-name>
<url-pattern>/UploadServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DownloadServlet</servlet-name>
<url-pattern>/DownloadServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<context-param>
<param-name>filesPath</param-name>
<param-value>C:\Users\Ashok\Desktop\Files\</param-value>
</context-param>
</web-app>
=================================0========================================
After Deploying the application, below screen will be displayed to upload
the file into Server. We can change filesPath in web.xml file
JAVA / J2EE Mr. Ashok
Internationalization (I18N)
Internationalization is the process of designing a software application so that it can be adapted to various
languages and regions without engineering changes. The term is frequently abbreviated as i18n (where 18 stands
for the number of letters between the first i and last n in internationalization). Above definition essentially means
making changes in your application such that it should be usable in multiple locales (or languages in simple
words).
With the advent of globalization, the importance of internationalizing web applications has increased. This is
important because web applications are accessed by users from various regions and countries. The Internet has
no boundaries and neither should your web application. People all over the world access the Net to browse web
pages that are written in different languages. For example, you can check your web-based email from virtually
anywhere. A user in America can access the web and check her Facebook!. How does Facebook do it?
JAVA and Internationalization: Java Standard Edition, provides a rich set of API's to support Internationalization
and Localization of an application. The internationalization API's provided with Java(SE) can easily adapt different
messages, number, date, and currency formats according to different country and region conventions. The
internationalization and Localization API's specified under Java SE platform is based on the Unicode 3.0 character
encoding. Java provides two common classes to implement internationalization, Locale and ResourceBundle.
Internationalization and Localization: When you read about internationalizing applications, you will come across
terms such as localization, character encoding, locales, resource bundles and so on.
Describing the Locale Class: The java.util.Locale class is used while creating internationalization Java's
applications. The java.util.Locale class is a non-abstract final class packed into the java.util package. A Locale
object encapsulates the language, country, and variant of the specific locale. These Locales affects language
choice, collation, calendar usage, date and time formats, number and currency formats, and many other cultural
sensitive data representations. All other locale-oriented classes use the locale object to adapt to the specific
locale and provide the output accordingly.
The Locale class consists of three constructors:
Describing The ResourceBundle Class: The ResourceBundles class provides the mechanism to separate user
interface(ui) elements and other locale sensitive data from the application logic. ResourceBundle is an abstract
base class that represents a container of resources.
This Example shows you Internationalization of language. This application gives the way of format for different
languages. Here I have specified only three languages i.e.-English, Chinese, French. In the application given below
we will develop a form for users from different countries. So user can select the from language as per suitability
and operate further process.
----------------------------------------------------------application.jsp--------------------------------------------------------------------
<%@ page pageEncoding="UTF-8"%>
JAVA / J2EE Mr. Ashok
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<html>
<c:set var="loc" value="en_US" />
<c:if test="${!(empty param.locale)}">
<c:set var="loc" value="${param.locale}" />
</c:if>
<fmt:setLocale value="${loc}" />
<fmt:bundle basename="app">
<head>
<title><fmt:message key="newTitle" /></title>
</head>
<body>
<h1>
<fmt:message key="newTitle" />
</h1>
<c:url value="processForm.jsp" var="formActionURL" />
<form action="${formActionURL}" method="post">
<table>
<tr>
<td><fmt:message key="lastName" /></td>
<td><input type="hidden" name="locale" value="${loc}" /> <input
type="text" name="lastname" size="40" /></td>
</tr>
<tr>
<td><fmt:message key="firstName" /></td>
<td><input type="text" name="firstname" size="40" /></td>
</tr>
<tr>
<td><fmt:message key="postalCode" /></td>
<td><input type="text" name="postcode" size="40" /></td>
</tr>
<tr>
<td><fmt:message key="password" /></td>
<td><input type="password" name="pass" size="40" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit"
value="<fmt:message key='submitForm'/>" /></td>
</tr>
</table>
</form>
</body>
<!—Including Languages page
<jsp:include page="index.jsp" />
</fmt:bundle>
</html>
------------------------------------------------------------processForm.jsp------------------------------------------------------------------
JAVA / J2EE Mr. Ashok
<%@ page pageEncoding="UTF-8"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<fmt:requestEncoding value="UTF-8" />
<html>
<fmt:setLocale value="${param.locale}" />
<head>
<fmt:bundle basename="app">
<title><fmt:message key="appInfo" /></title>
</head>
<body>
<h1>
<fmt:message key="appInfo" />
</h1>
<br>
<table border="1">
<tr>
<td><fmt:message key="lastName" /></td>
<td>${param.lastname}</td>
</tr>
<tr>
<td><fmt:message key="firstName" /></td>
<td>${param.firstname}</td>
</tr>
<tr>
<td><fmt:message key="postalCode" /></td>
<td>${param.postcode}</td>
</tr>
<tr>
<td><fmt:message key="password" /></td>
<td>${param.pass}</td>
</tr>
</table>
</body>
</fmt:bundle>
</html>
-----------------------------web.xml--------------------------------
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>I18NWebApp</display-name>
<welcome-file-list>
<welcome-file>application.jsp</welcome-file>
</welcome-file-list>
</web-app>
-------------------------------------0-------------------------------
JAVA / J2EE Mr. Ashok
When User deployed this application, the first page would be like below
When User submit the form, form data will be displayed in selected language, like below
JAVA / J2EE Mr. Ashok
Design Patterns
A design pattern describes a proven solution to a recurring design problem, placing particular emphasis on the
context and forces surrounding the problem, and the consequences and impact of the solution. There are many
good reasons to use design patterns:
They are proven: You tap the experience, knowledge and insights of developers who have used these
patterns successfully in their own work.
They are reusable: When a problem recurs, you don’t have to invent a new solution; you follow the pattern
and adapt it as necessary.
They are expressive: Design patterns provide a common vocabulary of solutions, which you can use to
express larger solutions succinctly.
It is important to remember, however, that design patterns do not guarantee success. You can only determine
whether a pattern is applicable by carefully reading its description, and only after you’ve applied it in your own
work can you determine whether it has helped.
Web is the very complex issues these days. Since the desire of the companies and organizations are increasing
so the complexity and the performance of the web programming matters. Complexity with the different types of
communication devices is increasing. The business is demanding applications using the web and many
communication devices. So with the increase load of the data on the internet we have to take care of the
architecture issue. To overcome these issues, we need to have idea about design models. There are two types of
design models available in java, they are
1. Model 1 Architecture
2. Model 2 (MVC) Architecture
Model 1 Architecture
Servlet and JSP are the main technologies to develop the web applications.
Servlet was considered superior to CGI. Servlet technology doesn't create process, rather it creates thread to
handle request. The advantage of creating thread over process is that it doesn't allocate separate memory area.
Thus many subsequent requests can be easily handled by servlet.
Problem in Servlet technology Servlet needs to recompile if any designing code is modified. It doesn't provide
separation of concern. Presentation and Business logic are mixed up.
JSP overcomes almost all the problems of Servlet. It provides better separation of concern, now presentation and
business logic can be easily separated. You don't need to redeploy the application if JSP page is modified. JSP
provides support to develop web application using JavaBean, custom tags and JSTL so that we can put the
business logic separate from our JSP that will be easier to test and debug.
JAVA / J2EE Mr. Ashok
As you can see in the above figure, there is picture which show the flow of the model1 architecture.
Navigation control is decentralized since every page contains the logic to determine the next page. If JSP
page name is changed that is referred by other pages, we need to change it in all the pages that leads to
the maintenance problem.
Time consuming You need to spend more time to develop custom tags in JSP. So that we don't need to
use scriptlet tag.
Hard to extend It is better for small applications but not for large applications.
Model 2 Architecture
Model View Controller (MVC) is a software architecture pattern, commonly used to implement user interfaces:
it is therefore a popular choice for architecting web apps. In general, it separates out the application logic into
three separate parts, promoting modularity and ease of collaboration and reuse. It also makes applications
more flexible and welcoming to iterations.
The MVC pattern was first described in 1979 by Trygve Reenskaug, then working on Smalltalk at Xerox research
labs. The original implementation is described in depth in the influential paper “Applications Programming in
Smalltalk-80(TM): How to use Model-View-Controller”.
Smalltalk’s MVC implementation inspired many other GUI frameworks such as:
The NeXTSTEP and OPENSTEP development environments encourage the use of MVC. Cocoa and
GNUstep, based on these technologies, also use MVC.
Microsoft Foundation Classes (MFC) (also called Document/View architecture)
Java Swing
The Qt Toolkit (since Qt4 Release).
XForms has a clear separation of model (stored inside the HTML head section) from the presentation
(stored in the HTML body section). XForms uses simple bind commands to link the presentation to the
model.
JAVA / J2EE Mr. Ashok
MVC stands for Model, View and Controller. MVC separates application into three components - Model, View
and Controller.
Model: The Model is where data from the controller and sometimes the view is actually passed into, out of,
and manipulated. Keeping in mind our last example of logging into your web-based email, the model will take
the username and password given to it from the controller, check that data against the stored information in
the database, and then render the view accordingly. For example, if you enter in an incorrect password, the
model will tell the controller that it was incorrect, and the controller will tell the view to display an error
message saying something to the effect of “Your username or password is incorrect.”
View: In a web-based application, the view is exactly what it sounds like: the visible interface that the user
interacts with, displaying buttons, forms, and information. Generally speaking, the controller calls up the view
after interacting with the model, which is what gathers the information to display in the particular view.
Controller: The Controller is essentially the traffic cop of the application, directing traffic to where it needs to
go, figuring out which view it needs to load up, and interacting with the appropriate models. For example,
when you go to login to your email on a website, the controller is going to tell the application that it needs to
load the login form view. Upon attempting to login, the controller will load the model that handles logins,
which will check if the username and password match what exists within the system. If successful, the
controller will then pass you off to the first page you enter when logging in, such as your inbox. Once there, the
inbox controller will further handle that request.
The following figure illustrates the interaction between Model, View and Controller
JAVA / J2EE Mr. Ashok
As per the above figure, when the user enters a URL in the browser, it goes to the server and calls appropriate
controller. Then, the Controller uses the appropriate View and Model and creates the response and sends it back
to the user.
Points to Remember:
• MVC stands for Model, View and Controller.
• Model is responsible for maintaining application data and business logic.
• View is a user interface of the application, which displays the data.
• Controller handles user's requests and renders appropriate View with Model data.
Though MVC comes in different flavours, the control flow generally works as follows:
The user interacts with the user interface in some way (e.g., user presses a button)
A controller handles the input event from the user interface, often via a registered handler or callback.
The controller accesses the model, possibly updating it in a way appropriate to the user’s action (e.g.,
controller updates user’s shopping cart). Complex controllers are often structured using the command
pattern to encapsulate actions and simplify extension.
A view uses the model to generate an appropriate user interface (e.g., view produces a screen listing the
shopping cart contents). The view gets its own data from the model. The model has no direct knowledge of
the view. (However, the observer pattern can be used to allow the model to indirectly notify interested
parties, potentially including views, of a change.)
The user interface waits for further user interactions, which begins the cycle anew.
Conclusion
Now that you know the basic concepts of the MVC pattern, you’re probably wondering what makes it so special?
Essentially, it allows for the programmer to isolate these very separate pieces of code into their own domain,
which makes code maintenance and debugging much simpler than if all of these items were chunked into one
massive piece. If I have a problem with an application not displaying an error message when it should, I have a
very specific set of locations to look to see why this is not happening. First I would look at the “Login Controller”
to see if it is telling the view to display the error. If that’s fine, I would look at the “Login Model” to see if it is
passing the data back to the controller to tell it that it needs to show an error. Then if that’s correct, the last place
it could be happening would be in the “Login View.”
JAVA / J2EE Mr. Ashok
Using this development pattern allows for very easy maintenance, as well as independent development of pieces
of the same system by different programmers, which makes for quick turnover of applications all while still
maintaining a very high standard of quality for the application.