AJT Notes

Download as pdf or txt
Download as pdf or txt
You are on page 1of 99

1. Write a note on​ ​URL and URLConnection Class.

A URL contains many information:

1. Protocol:​ In this case, http is the protocol.


2. Server name or IP Address:​ In this case, www.google.com is the server
name.
3. Port Number:​ It is an optional attribute. If we write
http//www.google.com:80/index.heml , 80 is the port number. If port
number is not mentioned in the URL, it returns -1.
4. File Name or directory name:​ In this case, index.jsp is the file name.

//URLDemo.java
import java.io.*;
import java.net.*;
public class URLDemo{
public static void main(String[] args){
try{
URL url=new URL("http://www.google.com/index.html");

System.out.println("Protocol: "+url.getProtocol());
System.out.println("Host Name: "+url.getHost());
System.out.println("Port Number: "+url.getPort());
System.out.println("File Name: "+url.getFile());

}catch(Exception e){System.out.println(e);}
}
}

2 Java URLConnection class

The ​Java URLConnection​ class represents a communication link between the URL
and the application. This class can be used to read and write data to the specified
resource referred by the URL.
import java.io.*;
import java.net.*;
public class URLConnectionExample {
public static void main(String[] args){
try{
URL url=new URL("http://www.google.com/ait.html");
URLConnection urlcon=url.openConnection();
InputStream stream=urlcon.getInputStream();
int i;
while((i=stream.read())!=-1){
System.out.print((char)i);
}
}catch(Exception e){System.out.println(e);}
}
}

3
Java InetAddress class :

InetAddress class provides the object representation of IP address. An object of


InetAddressa class is used to represent the IP address of any system in the form of
Object. InetAddress is a Singleton class which provides factory methods to create
and manage the object. There are no constructors for this class but static methods
which returns instances of InetAddress class for general use.

Java InetAddress​ class represents an IP address


getAllByName​,​ ​getByName​,​ ​getLocalHost

import java.io.*;
import java.net.*;
public class InetDemo{
public static void main(String[] args){
String host = "";
Scanner sc = new Scanner(System.in);
System.out.println("Host: ");
host = sc.next();
try
{
InetAddress ia = InetAddress.getByName(host);
System.out.println(ia);
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}
try
{
InetAddress[] ia = InetAddress.getAllByName(host);
for(int i=0; i<ia.length; i++)
{
System.out.println(ia[i].toString());
}
}
catch(UnknownHostException uhe)
{
System.out.println(uhe.toString());
}

try{
InetAddress ip=InetAddress.getByName("www.google.com");

System.out.println("Host Name: "+ip.getHostName());


System.out.println("IP Address: "+ip.getHostAddress());
}catch(Exception e){System.out.println(e);}

}
}
4 Java Socket Programming connection oriented communication

Java Socket programming is used for communication between the applications


running on different JRE.
Java Socket programming can be connection-oriented or connection-less.
Socket and ServerSocket classes are used for connection-oriented socket
programming and DatagramSocket and DatagramPacket classes are used for
connection-less socket programming.
The client in socket programming must know two information:

1. IP Address of Server, and


2. Port number.

import java.io.*;
import java.net.*;
public class MyServer {
public static void main(String[] args){
try{
ServerSocket ss=new ServerSocket(6666);
Socket s=ss.accept();//establishes connection
DataInputStream dis=new DataInputStream(s.getInputStream());
String str=(String)dis.readUTF();
System.out.println("message= "+str);
ss.close();
}catch(Exception e){System.out.println(e);}
}
}

import java.io.*;
import java.net.*;
public class MyClient {
public static void main(String[] args) {
try{
Socket s=new Socket("localhost",6666);
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
dout.writeUTF("Hello Server");
dout.flush();
dout.close();
s.close();
}catch(Exception e){System.out.println(e);}
}
}
Two Way communication ;
import java.net.*;
import java.io.*;
class MyServer{
public static void main(String args[])throws Exception{
ServerSocket ss=new ServerSocket(3333);
Socket s=ss.accept();
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){
str=din.readUTF();
System.out.println("client says: "+str);
str2=br.readLine();
dout.writeUTF(str2);
dout.flush();
}
din.close();
s.close();
ss.close();
}}
import java.net.*;
import java.io.*;
class MyClient{
public static void main(String args[])throws Exception{
Socket s=new Socket("localhost",3333);
DataInputStream din=new DataInputStream(s.getInputStream());
DataOutputStream dout=new DataOutputStream(s.getOutputStream());
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));

String str="",str2="";
while(!str.equals("stop")){
str=br.readLine();
dout.writeUTF(str);
dout.flush();
str2=din.readUTF();
System.out.println("Server says: "+str2);
}

dout.close();
s.close();
}}
5
Example of Java Socket Programming Connectionless communication

Java DatagramSocket and DatagramPacket


//DSender.java
import java.net.*;
public class DSender{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket();
String str = "Welcome java";
InetAddress ip = InetAddress.getByName("127.0.0.1");

DatagramPacket dp = new DatagramPacket(str.getBytes(), str.length(), ip, 3000);


ds.send(dp);
ds.close();
}
}

//DReceiver.java
import java.net.*;
public class DReceiver{
public static void main(String[] args) throws Exception {
DatagramSocket ds = new DatagramSocket(3000);
byte[] buf = new byte[1024];
DatagramPacket dp = new DatagramPacket(buf, 1024);
ds.receive(dp);
String str = new String(dp.getData(), 0, dp.getLength());
System.out.println(str);
ds.close();
}
}
6 Explain JDBC Architecture

JDBC​ is an API specification developed by ​Sun Microsystems​ that defines a uniform


interface for accessing various relational databases. JDBC is a core part of the Java
platform and is included in the standard JDK distribution.

The primary function of the JDBC API is to provide a means for the developer to
issue SQL statements and process the results in a consistent, database-independent
manner. JDBC provides rich, object-oriented access to databases by defining classes
and interfaces that represent objects such as:

1. Database connections
2. SQL statements
3. Result Set
4. Database metadata
5. Prepared statements
6. Binary Large Objects (BLOBs)
7. Character Large Objects (CLOBs)
8. Callable statements
9. Database drivers
10. Driver manager

The JDBC API uses a Driver Manager and database-specific drivers to provide
transparent connectivity to heterogeneous databases. The JDBC driver manager
ensures that the correct driver is used to access each data source. The Driver
Manager is capable of supporting multiple concurrent drivers connected to multiple
heterogeneous databases

We can use JDBC API to handle database using Java program and can perform the
following activities:

1. Connect to the database


2. Execute queries and update statements to the database
3. Retrieve the result received from the database.

7 Explain types of various JDBC drivers


JDBC Driver is a software component that enables java application to interact with
the database. There are 4 types of JDBC drivers:

1. JDBC-ODBC bridge driver


2. Native-API driver (partially java driver)
3. Network Protocol driver (fully java driver)
4. Thin driver (fully java driver)

1) JDBC-ODBC bridge driver


The JDBC-ODBC bridge driver uses ODBC driver to connect to the database. The
JDBC-ODBC bridge driver converts JDBC method calls into the ODBC function calls
Advantages:

● easy to use.
● can be easily connected to any database.

Disadvantages:

● Performance degraded because JDBC method call is converted into the


ODBC function calls.
● The ODBC driver needs to be installed on the client machine.

2) Native-API driver
The Native API driver uses the client-side libraries of the database. The driver
converts JDBC method calls into native calls of the database API. It is not written
entirely in java.
Advantage:

● performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:

● The Native driver needs to be installed on the each client machine.


● The Vendor client library needs to be installed on client machine.

3) Network Protocol driver


The Network Protocol driver uses middleware (application server) that converts
JDBC calls directly or indirectly into the vendor-specific database protocol. It is fully
written in java.
Advantage:

● No client side library is required because of application server that can


perform many tasks like auditing, load balancing, logging etc.

Disadvantages:

● Network support is required on client machine.


● Requires database-specific coding to be done in the middle tier.
● Maintenance of Network Protocol driver becomes costly because it requires
database-specific coding to be done in the middle tier.

4) Thin driver
The thin driver converts JDBC calls directly into the vendor-specific database
protocol. That is why it is known as thin driver. It is fully written in Java language.
Advantage:

● Better performance than all other drivers.


● No software is required at client side or server side.

Disadvantage:
Drivers depend on the Database
8 How to connect java with database write steps?
There are 5 steps to connect any java application with the database using JDBC.
These steps are as follows:
1) Register the driver class
The ​forName()​ method of Class class is used to register the driver class. This
method is used to dynamically load the driver class.

Class.forName("oracle.jdbc.driver.OracleDriver");

2) Create the connection object


The ​getConnection()​ method of DriverManager class is used to establish connection
with the database.
Connection con=DriverManager.getConnection(

"jdbc:oracle:thin:@localhost:1521:xe","system","password");

3) Create the Statement object


The createStatement() method of Connection interface is used to create statement.
The object of statement is responsible to execute queries with the database.
Statement stmt=con.createStatement();

4) Execute the query


The executeQuery() method of Statement interface is used to execute queries to
the database. This method returns the object of ResultSet that can be used to get
all the records of a table.

ResultSet rs=stmt.executeQuery("select * from emp");

while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}

5) Close the connection object


By closing connection object statement and ResultSet will be closed automatically.
The close() method of Connection interface is used to close the connection.
con.close();

MYSQL:

1. create database ait;


2. use ait;
3. create table emp(id int(10),name varchar(40),age int(3));

Ex:

// MysqlCon.java

import java.sql.*;
class MysqlCon{
public static void main(String args[]){
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/ait","root","root");
//here sonoo is database name, root is username and password
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery("select * from emp");
while(rs.next())
System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
con.close();
}catch(Exception e){ System.out.println(e);}
}
}

9 Explain DriverManager class ,Connection class?


The DriverManager class acts as an interface between user and drivers. It keeps
track of the drivers that are available and handles establishing a connection
between a database and the appropriate driver. The DriverManager class maintains
a list of Driver classes that have registered themselves by calling the method
DriverManager.registerDriver().

Method Description

1) public static void is used to register the given


registerDriver(Driver driver): driver with DriverManager.

2) public static void is used to deregister the given


deregisterDriver(Driver driver): driver (drop the driver from
with DriverManager.

3) public static Connection is used to establish the


getConnection(String url): connection with the specified url.

4) public static Connection is used to establish the


getConnection(String url,String connection with the specified url, u
userName,String password): and password.

A Connection is the session between java application and database. The Connection
interface is a factory of Statement, PreparedStatement, and DatabaseMetaData i.e.
object of Connection can be used to get the object of Statement and
DatabaseMetaData. The Connection interface provide many methods for
transaction management like commit(), rollback() etc.

10 Explain Statement Interface?


The ​Statement interface​ provides methods to execute queries with the database.
The statement interface is a factory of ResultSet i.e. it provides factory method to
get the object of ResultSet.

Commonly used methods of Statement interface:


The important methods of Statement interface are as follows:
1) public ResultSet executeQuery(String sql):​ is used to execute SELECT query. It
returns the object of ResultSet.
2) public int executeUpdate(String sql):​ is used to execute specified query, it may
be create, drop, insert, update, delete etc.
​3) public boolean execute(String sql):​ is used to execute queries that may return
multiple results.
​4) public int[] executeBatch():​ is used to execute batch of commands.
Ex:
import java.sql.*;
class GetRecord{
public static void main(String args[])throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system"
,"oracle");
Statement stmt=con.createStatement();

//stmt.executeUpdate("insert into emp values(3,'Ram',50000)");


//int result=stmt.executeUpdate("update emp set name='Vimal',salary=10000
where id=3");
int result=stmt.executeUpdate("delete from emp where id=33");
System.out.println(result+" records affected");
con.close();
}}

11 Explain PreparedStatement?

The PreparedStatement interface is a subinterface of Statement. It is used to


execute parameterized query.
Improves performance​: The performance of the application will be faster if you use
PreparedStatement interface because query is compiled only once.
Method Description

public void setInt(int paramIndex, sets the integer value to the g


int value) parameter index.

public void setString(int sets the String value to the gi


paramIndex, String value) parameter index.

public void setFloat(int sets the float value to the giv


paramIndex, float value) parameter index.

public void setDouble(int sets the double value to the g


paramIndex, double value) parameter index.

public int executeUpdate() executes the query. It is used


create, drop, insert, update, d

public ResultSet executeQuery() executes the select query. It r


instance of ResultSet.

Ex:
Mysql:
create table emp(id number(10),name varchar2(50));
import java.sql.*;
class InsertUsingPrepared{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");

Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system"
,"oracle");

PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");


stmt.setInt(1,101);//1 specifies the first parameter in the query
stmt.setString(2,"Ram");

int i=stmt.executeUpdate();
System.out.println(i+" records inserted");

con.close();

}catch(Exception e){ System.out.println(e);}

}
}
12 Explain CallableStatement?
CallableStatement interface is used to call the ​stored procedures and functions​.
We can have business logic on the database by the use of stored procedures and
functions that will make the performance better because these are precompiled.
Suppose you need the get the age of the employee based on the date of birth, you
may create a function that receives date as the input and returns age of the
employee as the output.
Mysql:
create table testuser(id number(10), name varchar2(200));

create or replace procedure "insertdata"


(id IN NUMBER,
name IN VARCHAR2)
is
begin
insert into testuser values(id,name);
end;
/
import java.sql.*;
public class Proc {
public static void main(String[] args) throws Exception{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

CallableStatement stmt=con.prepareCall("{call insertdata(?,?)}");


stmt.setInt(1,1011);
stmt.setString(2,"Amit");
stmt.execute();

System.out.println("success");
}
}

13 Explain ResultSet and ResultSetMetaData?


The object of ResultSet maintains a cursor pointing to a row of a table. Initially,
cursor points to before the first row.

Commonly used methods of ResultSet interface

1) public boolean next(): is used to move the cursor to the one


from the current position.

2) public boolean previous(): is used to move the cursor to the one


previous from the current position.

3) public boolean first(): is used to move the cursor to the first


result set object.

4) public boolean last(): is used to move the cursor to the last


result set object.

5) public boolean absolute(int row): is used to move the cursor to the spec
number in the ResultSet object.

6) public boolean is used to move the cursor to the relat


relative(int row): number in the ResultSet object, it may
positive or negative.

7) public int getInt(int is used to return the data of specified


columnIndex): index of the current row as int.

8) public int getInt(String columnName): is used to return the data of specified


name of the current row as int.

9) public String getString(int columnIndex): is used to return the data of specified


index of the current row as String.

10) public String getString(String is used to return the data of specified


columnName): name of the current row as String.

EX:
import java.sql.*;
class FetchDataRecord{
public static void main(String args[])throws Exception{

Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe","system"
,"oracle");
Statement
stmt=con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_
UPDATABLE);
ResultSet rs=stmt.executeQuery("select * from emp");
//getting the record of 3rd row
rs.absolute(3);
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));

con.close();
}}

ResultSetMetaData
The metadata means data about data i.e. we can get further information from the
data.
If you have to get metadata of a table like total number of column, column name,
column type etc. , ResultSetMetaData interface is useful because it provides
methods to get metadata from the ResultSet object.

Method Description

public int getColumnCount()throws it returns the total number of co


SQLException the ResultSet object.

public String getColumnName(int index)throws it returns the column name of th


SQLException specified column index.

public String getColumnTypeName(int it returns the column type name


index)throws SQLException specified index.

public String getTableName(int index)throws it returns the table name for the
SQLException specified column index.

EX:
import java.sql.*;
class ResulSetEx{
public static void main(String args[]){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:@localhost:1521:xe","system","oracle");

PreparedStatement ps=con.prepareStatement("select * from emp");


ResultSet rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("Total columns: "+rsmd.getColumnCount());


System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));
System.out.println("Column Type Name of 1st column:
"+rsmd.getColumnTypeName(1));

con.close();
}catch(Exception e){ System.out.println(e);}
}
}

14 What is servlet ? Difference between Servlet and CGI?

CGI (Commmon Gateway Interface) :

1. CGI (Common Gateway Interface) is used to provide dynamic content to the


user.
2. CGI is used to execute a program that resides in the server to process data
or access databases to produce the relevant dynamic content.
3. Programs that resides in server can be written in native operating system
such as C++.

Diagrammatic Representation :

We have listed some problems in CGI technology –

Disadvantages of CGI :

1. For each request CGI Server receives, It creates new Operating System
Process.
2. If the number of requests from the client increases then more time it will
take to respond to the request.
3. As programs executed by CGI Script are written in the native languages such
as C, C++, perl which are platform independent.

Servlet :
CGI programs are used to execute programs written inside the native language. But
in Servlet all the programs are compiled into the Java bytecode which is then run in
the Java virtual machine.

In Servlet, All the requests coming from the Client are processed with the threads
instead of the OS process.

Servlet CGI (Common Gateway Interface)

Servlets are portable CGI is not portable.

In Servlets each request is handled by IN CGI each request is handled by he


lightweight Java Thread weight OS process

In Servlets, Data sharing is possible In CGI, data sharing is not available.

Servlets can link directly to the Web server CGI cannot directly link to Web serve

Session tracking and caching of previous Session tracking and caching of previ
computations can be performed computations cannot be performed

Automatic parsing and decoding of HTML Automatic parsing and decoding of H


form data can be performed. data cannot be performed.

Servlets can read and Set HTTP Headers CGI cannot read and Set HTTP Heade

Servlets can handle cookies CGI cannot handle cookies


Servlets can track sessions CGI cannot track sessions

Servlets is inexpensive than CGI CGI is more expensive than Servlets

14 Explain MVC architecture in detail.


● Model − The lowest level of the pattern which is responsible for maintaining
data.
● View − This is responsible for displaying all or a portion of the data to the
user.
● Controller − Software Code that controls the interactions between the
Model and View.

MVC is popular as it isolates the application logic from the user interface layer and
supports separation of concerns. Here the Controller receives all requests for the
application and then works with the Model to prepare any data needed by the
View. The View then uses the data prepared by the Controller to generate a final
presentable response. The MVC abstraction can be graphically represented as
follows.

The Model
The model is responsible for managing the data of the application. It responds to
the request from the view and it also responds to instructions from the controller to
update itself.

The View
It means presentation of data in a particular format, triggered by a controller's
decision to present the data. They are script-based templating systems like JSP, ASP,
PHP and very easy to integrate with AJAX technology.

The Controller
The controller is responsible for responding to the user input and perform
interactions on the data model objects. The controller receives the input, it
validates the input and then performs the business operation that modifies the
state of the data model.

15 Explain Servlet Life Cycle in detail


The web container maintains the life cycle of a servlet instance. Let's see the life
cycle of the servlet:

1. Servlet class is loaded.


2. Servlet instance is created.
3. init method is invoked.
4. service method is invoked.
5. destroy method is invoked.

Event Sequences
Typically, a servlet goes through the following sequence of events:

1. A client makes an HTTP request to the Web server via a Web browser.
2. The Web server delegates the request to the servlet container. The
container may be running as the same process as the network services or a
different process on the same host.
3. Depending upon the configuration of the servlet, the container invokes the
appropriate servlet class with the response/request object.
4. The request object provides information about the remote user, HTTP POST
parameters, and other details. Once these details are known, the servlet
processes the data according to the program logic and then sends back to
the client via a response object.
5. The servlet container returns the control back to the Web server after
request processing is finished.

1) Servlet class is loaded


The classloader is responsible to load the servlet class. The servlet class is loaded
when the first request for the servlet is received by the web container.

2) Servlet instance is created


The web container creates the instance of a servlet after loading the servlet class.
The servlet instance is created only once in the servlet life cycle.
3) init method is invoked
The web container calls the init method only once after creating the servlet
instance. The init method is used to initialize the servlet. It is the life cycle method
of the javax.servlet.Servlet interface

4) service method is invoked


The web container calls the service method each time when request for the servlet
is received. If servlet is not initialized, it follows the first three steps as described
above then calls the service method. If servlet is initialized, it calls the service
method. Notice that servlet is initialized only once.

5) destroy method is invoked


The web container calls the destroy method before removing the servlet instance
from the service. It gives the servlet an opportunity to clean up any resource for
example memory, thread etc
Ex:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

// Extend HttpServlet class


public class HelloWorld extends HttpServlet {

private String message;

public void init() throws ServletException {


// Do required initialization
message = "Hello World";
}

public void doGet(HttpServletRequest request, HttpServletResponse response)


throws ServletException, IOException {

// Set response content type


response.setContentType("text/html");
// Actual logic goes here.
PrintWriter out = response.getWriter();
out.println("<h1>" + message + "</h1>");
}

public void destroy() {


// do nothing.
}
}

16 Give the characteristics of the HTTP protocol ?


The Hypertext Transfer Protocol (HTTP) is application-level protocol for
collaborative, distributed, hypermedia information systems. It is the data
communication protocol used to establish communication between client and
server.
HTTP is TCP/IP based communication protocol, which is used to deliver the data like
image files, query results, HTML files etc on the World Wide Web (WWW) with the
default port is TCP 80. It provides the standardized way for computers to
communicate with each other.

The Basic Characteristics of HTTP (Hyper Text Transfer Protocol):

● It is the protocol that allows web servers and browsers to exchange data
over the web.
● It is a request response protocol.
● It uses the reliable TCP connections by default on TCP port 80.
● It is stateless means each request is considered as the new request. In other
words, server doesn't recognize the user by default.
The Basic Features of HTTP (Hyper Text Transfer Protocol):
There are three fundamental features that make the HTTP a simple and powerful
protocol used for communication:

● HTTP is media independent:​ It specifies that any type of media content can
be sent by HTTP as long as both the server and the client can handle the
data content.
● HTTP is connectionless:​ It is a connectionless approach in which HTTP client
i.e., a browser initiates the HTTP request and after the request is sent the
client disconnects from server and waits for the response.
● HTTP is stateless:​ The client and server are aware of each other during a
current request only. Afterwards, both of them forget each other. Due to
the stateless nature of protocol, neither the client nor the server can retain
the information about different request across the web pages.

The Basic Architecture of HTTP (Hyper Text Transfer Protocol):


The below diagram represents the basic architecture of web application and depicts
where HTTP stands:

HTTP is request/response protocol which is based on client/server based


architecture. In this protocol, web browser, search engines, etc. behave as HTTP
clients and the Web server like Servlet behaves as a server
17 Write sample deployment descriptor file (web.xml). Explain various configuration
parameters of it.
What is Deployment Descriptor?
As the name indicates, the ​deployment descriptor​ describes the deployment
information (or Web Information) of a Servlet. The deployment descriptor is an XML
file known as ​web.xml​. XML is the easiest way to give the information to a server,
just writing in between the tags, instead of writing in a text file or RDBMS file. The
name and tags of ​web.xml​ are Servlet API specifications.
<​web​-​app​>

<​servlet​>
<​servlet​-​name​>​servletName​</​servlet​-​name​>
<​servlet​-​class​>​servletClass​</​servlet​-​class​>
</​servlet​>
<​servlet​-​mapping​>
<​servlet​-​name​>​servletName​</​servlet​-​name​>
<​url​-​pattern​>*​.​*</​url​-​pattern​>
</​servlet​-​mapping​>

​ <init-param>
<param-name>myParam</param-name>
<param-value>paramValue</param-value>
</init-param>

<load-on-startup>1</load-on-startup>

<context-param>
<param-name>myParam</param-name>
<param-value>the value</param-value>
</context-param>

<filter>
<filter-name>MyFilter</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<servlet-name>first</servlet-name>
</filter-mapping>
<welcome-file-list>
<welcome-file>myhome.htm</welcome-file>
<welcome-file>myindex.htm</welcome-file>
<welcome-file>mydefaultpage.htm</welcome-file>
</welcome-file-list>

</​web​-​app​>
18 Draw and explain J2EE architecture

J2EE ​(Java 2 Enterprise Edition) is an environment for developing and deploying


enterprise applications. The J2EE platform consists of J2EE components, services,
Application Programming Interfaces (APIs) and protocols that provide the
functionality for developing multi-tiered and distributed Web based applications.
J2EE is four-tier architecture. These consist of Client Tier (Presentation tier or
Application tier), Web tier, Enterprise JavaBeans Tier (or Application server tier),
and the Enterprise Information Systems Tier or the Data tier.
Two or more tiers can physically reside on the same Java Virtual Machine although
each tier provides a specific type of functionality to an application. Some of the APIs
of J2EE components can be used on more than one tier (i.e. XML API), while other
APIs (i.e., EJB API) or associated with a particular tier. Following diagram is
representing the multi-tier architecture of J2EE.
CLIENT TIER : ​Client tier consists of programs that interact with the user. It prompts
the user for input and then convert the user’s response into requests that are
forwarded to software on a component that processes the request and returns
results to the client program. J2EE clients can be classified as follows
Web client is A software (usually browser) that accesses resources located on the
web tier.
Ejb client can access one or more enterprise java beans that are located on the EJB
tier rather than resources on the web tier.
EIS clients ​ are the interface between users and resources located on the EIS tier.
Multi-tier clients can access components located on tiers other than the tier where
the multi-tier client resides.
WEB TIER : ​Web tier accepts requests from other software that was sent using
POST, GET, and PUT operations, which are part of HTTP transmissions. The two
major components of web tier are Servlets and Java Server Pages. A servlet is a java
class that resides on the web tier and is called by a request from a browser client
that operates on the client tier. A servlet is associated with a URL that is mapped by
the servlet container. It typically generates an HTML output stream that is returned
to the web server. The web server in turn transmits the data to the client. JSP is
different than a servlet depending on the container that is used. JSP uses custom
tags to access the bean.
ENTERPRISE JAVA BEANS TIER OR APPLICATION TIER : ​Enterprise java bean is a
class that contains business logic and callable from a servlet or Jsp. EJB tier contains
the enterprise java beans server that stores and manages enterprise java beans.
This tier automatically handles concurrency issues that assure multiple clients have
simultaneous access to the same object and also manages instances of
components. EJB server and EJB container is responsible for low level system
services that are essential for implementing business logic.
ENTERPRISE INFORMATION SYSTEMS TIER OR DATA TIER : ​This tier provides
flexibility to developers of J2EE applications since it include variety of resources and
support connectivity to resources. It defines all the elements that are needed to
communicate between J2EE application and non-J2EE software.

19 Explain ​GenericServlet​ class?


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 class


There are many methods in GenericServlet class. They are as follows:

1. public void init(ServletConfig config)​ is used to initialize the servlet.


2. public abstract void service(ServletRequest request, ServletResponse
response)​ provides service for the incoming request. It is invoked at each
time when user requests for a servlet.
3. public void destroy()​ is invoked only once throughout the life cycle and
indicates that servlet is being destroyed.
4. public ServletConfig getServletConfig()​ returns the object of ServletConfig.
5. public String getServletInfo()​ returns information about servlet such as
writer, copyright, version etc.
6. public void init()​ it is a convenient method for the servlet programmers,
now there is no need to call super.init(config)
7. public ServletContext getServletContext()​ returns the object of
ServletContext.
8. public String getInitParameter(String name)​ returns the parameter value
for the given parameter name.
9. public Enumeration getInitParameterNames()​ returns all the parameters
defined in the web.xml file.
10. public String getServletName()​ returns the name of the servlet object.
11. public void log(String msg)​ writes the given message in the servlet log file.
12. public void log(String msg,Throwable t)​ writes the explanatory message in
the servlet log file and a stack trace.

Ex:

import java.io.*;
import javax.servlet.*;

public class First extends GenericServlet{


public void service(ServletRequest req,ServletResponse res)
throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");

}
}

20 Explain use of ServletConfig and ServletContext object with example? Explain


SendRedirect?
ServletConfig Interface
1. ServletConfig Interface
2. Methods of ServletConfig interface
3. How to get the object of ServletConfig
4. Syntax to provide the initialization parameter for a servlet
5. Example of ServletConfig to get initialization parameter
6. Example of ServletConfig to get all the initialization parameter

An object of ServletConfig is created by the web container for each servlet. This
object can be used to get configuration information from web.xml file.
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.

Advantage of ServletConfig
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.

Methods of ServletConfig interface

1. public String getInitParameter(String name):​Returns the parameter value


for the specified parameter name.
2. public Enumeration getInitParameterNames():​Returns an enumeration of
all the initialization parameter names.
3. public String getServletName():​Returns the name of the servlet.
4. public ServletContext getServletContext():​Returns an object of
ServletContext.

Ex:

DemoServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();

ServletConfig config=getServletConfig();
String driver=config.getInitParameter("driver");
out.print("Driver is: "+driver);

out.close();
}

web.xml

<web-app>

<servlet>
<servlet-name>DemoServlet</servlet-name>
<servlet-class>DemoServlet</servlet-class>

<init-param>
<param-name>driver</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</init-param>

</servlet>

<servlet-mapping>
<servlet-name>DemoServlet</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>

</web-app>

Servlet Context:
An object of ServletContext is created by the web container at time of deploying
the project. This object can be used to get configuration information from web.xml
file. There is only one ServletContext object per web application.
If any information is shared to many servlet, it is better to provide it from the
web.xml file using the <context-param> element.

Advantage of ServletContext
Easy to maintain if any information is shared to all the servlet, it is better to make it
available for all the servlet. We provide this information from the web.xml file, so if
the information is changed, we don't need to modify the servlet. Thus it removes
maintenance problem.

Usage of ServletContext Interface


There can be a lot of usage of ServletContext object. Some of them are as follows:

1. The object of ServletContext provides an interface between the container


and servlet.
2. The ServletContext object can be used to get configuration information from
the web.xml file.
3. The ServletContext object can be used to set, get or remove attribute from
the web.xml file.
4. The ServletContext object can be used to provide inter-application
communication.

Commonly used methods of ServletContext interface


There is given some commonly used methods of ServletContext interface.

1. public String getInitParameter(String name):Returns the parameter value for


specified parameter name.
2. public Enumeration getInitParameterNames():Returns the names of the cont
initialization parameters.
3. public void setAttribute(String name,Object object):sets the given object in th
application scope.
4. public Object getAttribute(String name):Returns the attribute for the specifie
5. public Enumeration getInitParameterNames():Returns the names of the cont
initialization parameters as an Enumeration of String objects.
6. public void removeAttribute(String name):Removes the attribute with the giv
name from the servlet context.

Ex:

DemoServlet.java

import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

//creating ServletContext object


ServletContext context=getServletContext();

//Getting the value of the initialization parameter and printing it


String driverName=context.getInitParameter("dname");
pw.println("driver name is="+driverName);

pw.close();

}}

web.xml

<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>

<context-param>
<param-name>dname</param-name>
<param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
</context-param>

<servlet-mapping>
<servlet-name>sonoojaiswal</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>

</web-app>

SendRedirect :
The ​sendRedirect()​ method of ​HttpServletResponse​ interface can be used to
redirect response to another resource, it may be servlet, jsp or html file.
It accepts relative as well as absolute URL.
It works at client side because it uses the url bar of the browser to make another
request. So, it can work inside and outside the server.
Ex:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class DemoServlet extends HttpServlet{


public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("text/html");
PrintWriter pw=res.getWriter();

response.sendRedirect("http://www.google.com");

pw.close();
}}

21 Explain Servlet Interface and Request and Response Objects in servlet.


Servlet interface provides​ commonbehaviorto all the servlets.Servlet interface
defines methods that all servlets must implement.
Servlet interface needs to be implemented for creating any servlet (either directly
or indirectly). It provides 3 life cycle methods that are used to initialize the servlet,
to service the requests, and to destroy the servlet and 2 non-life cycle methods.
Ex:
import java.io.*;
import javax.servlet.*;

public class First implements Servlet{


ServletConfig config=null;

public void init(ServletConfig config){


this.config=config;
System.out.println("servlet is initialized");
}

public void service(ServletRequest req,ServletResponse res)


throws IOException,ServletException{

res.setContentType("text/html");

PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello simple servlet</b>");
out.print("</body></html>");

}
public void destroy(){System.out.println("servlet is destroyed");}
public ServletConfig getServletConfig(){return config;}
public String getServletInfo(){return "copyright 2007-1010";}

22 Discuss the use of GET and POST with example

GET POST

1) In case of Get request, only In case of post request, large amount of data
limited amount of data can be can be sent because data is sent in body.
sent because data is sent in
header.

2) Get request is not secured Post request is secured because data is not
because data is exposed in URL exposed in URL bar.
bar.

3) Get request can be Post request cannot be bookmarked.


bookmarked.

4) Get request is idempotent . It Post request is non-idempotent.


means second request will be
ignored until response of first
request is delivered

5) Get request is more efficient Post request is less efficient and used less than g
and used more than Post.

23 What is Request Dispatcher? What is the difference between Request dispatcher’s


forward() and include() method?

The RequestDispatcher interface provides the facility of dispatching the request to


another resource it may be html, servlet or jsp. This interface can also be used to
include the content of another resource also. It is one of the way of servlet
collaboration.
There are two methods defined in the RequestDispatcher interface.
1) Both include() and forward() methods are part of RequestDispatcher interface of
Servlet API

2) Both methods accept objects of ServletRequest and ServletResponse interface.

3) Both include() and forward() can interact with static and dynamic resource e.g.
another Servlet, JSP or HTML files.

differences between include and forward() method​ from Servlet API:

1) First and foremost difference is that include() method includes the content of a
resource in the response, the resource could be another Servlet, JSP or HTML file.
While forward() method is used to forward the request to another resource.

2) The second difference between include() and forward() from Servlet API is that If
you include a servlet or JSP document, the included resource must not attempt to
change the response status code or HTTP headers, any such request will be ignored.
On the other hand, If you include a Servlet or JSP document, the included resource
must not attempt to change the response status code or HTTP headers, any such
request will be ignored.

3) Third and a useful difference between forward() and include() method is that
former is often used to include common boilerplate text of template markup which
might be included by many Servlets e.g. header or footer. While, forward() method
is often used where a servlet is taking a controller role; processing some input and
deciding the outcome by returning a particular response page.
You should use include() method to load a resource which could be a JSP page or
another Servlet, and use forward() to redirect the request to another resource for
further processing, again you can forward the request to another Servlet or JSP
page.

Methods of RequestDispatcher interface


The RequestDispatcher interface provides two methods. They are:

1. public void forward(ServletRequest request,ServletResponse


response)throws ServletException,java.io.IOException:​Forwards a request
from a servlet to another resource (servlet, JSP file, or HTML file) on the
server.
2. public void include(ServletRequest request,ServletResponse
response)throws ServletException,java.io.IOException:​Includes the content
of a resource (servlet, JSP page, or HTML file) in the response.

As you see in the above figure, response of second servlet is sent to the client.
Response of the first servlet is not displayed to the user.
As you can see in the above figure, response of second servlet is included in the
response of the first servlet that is being sent to the client.
24 What is session? List the different ways to manage the session.
Session​ simply means a particular interval of time.
Session Tracking​ is a way to maintain state (data) of an user. It is also known as
session management​ in servlet.
Http protocol is a stateless so we need to maintain state using session tracking
techniques. Each time user requests to the server, server treats the request as the
new request. So we need to maintain the state of an user to recognize to particular
user.
HTTP is stateless that means each request is considered as the new request. It is
shown in the figure given below:
There are four techniques used in Session tracking:

1. Cookies
2. Hidden Form Field
3. URL Rewriting
4. HttpSession

1. A ​cookie​ is a small piece of information that is persisted between the multiple


client requests. A cookie has a name, a single value, and optional attributes such as
a comment, path and domain qualifiers, a maximum age, and a version number.

How Cookie works


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. 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.

Advantage of Cookies

1. Simplest technique of maintaining the state.


2. Cookies are maintained at client side.

Disadvantage of Cookies

1. It will not work if cookie is disabled from the browser.


2. Only textual information can be set in Cookie object.

Ex:

index.html

1. <form action="servlet1" method="post">


2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

Cookie ck=new Cookie("uname",n);//creating cookie object


response.addCookie(ck);//adding cookie in the response

//creating submit button


out.print("<form action='servlet2'>");
out.print("<input type='submit' value='go'>");
out.print("</form>");

out.close();
}catch(Exception e){System.out.println(e);}
}
}

SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class SecondServlet extends HttpServlet {

public void doPost(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

Cookie ck[]=request.getCookies();
out.print("Hello "+ck[0].getValue());

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>

HttpSession :
container creates a session id for each user.The container uses this id to identify the
particular user.An object of HttpSession can be used to perform two tasks:

1. bind objects
2. view and manipulate information about a session, such as the session
identifier, creation time, and last accessed time.

Ex:

index.html

1. <form action="servlet1">
2. Name:<input type="text" name="userName"/><br/>
3. <input type="submit" value="go"/>
4. </form>

FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class FirstServlet extends HttpServlet {

public void doGet(HttpServletRequest request, HttpServletResponse response){


try{

response.setContentType("text/html");
PrintWriter out = response.getWriter();

String n=request.getParameter("userName");
out.print("Welcome "+n);

HttpSession session=request.getSession();
session.setAttribute("uname",n);

out.print("<a href='servlet2'>visit</a>");

out.close();

}catch(Exception e){System.out.println(e);}
}

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();

HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);

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>
25 What is Filter? List the applications of filter.
A filter is an object that is invoked at the preprocessing and postprocessing of a
request.
It is mainly used to perform filtering tasks such as conversion, logging, compression,
encryption and decryption, input validation etc.
The servlet filter is pluggable, i.e. its entry is defined in the web.xml file, if we
remove the entry of filter from the web.xml file, filter will be removed
automatically and we don't need to change the servlet.
So maintenance cost will be less.

Usage of Filter

● recording all incoming requests


● logs the IP addresses of the computers from which the requests originate
● conversion
● data compression
● encryption and decryption
● input validation etc.

Advantage of Filter

1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance

Ex:

index.html

<a href="servlet1">click here</a>

MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.*;

public class MyFilter implements Filter{

public void init(FilterConfig arg0) throws ServletException {}

public void doFilter(ServletRequest req, ServletResponse resp,


FilterChain chain) throws IOException, ServletException {

PrintWriter out=resp.getWriter();
out.print("filter is invoked before");

chain.doFilter(req, resp);//sends request to next resource

out.print("filter is invoked after");


}
public void destroy() {}
}

HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;

public class HelloServlet extends HttpServlet {


public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {

response.setContentType("text/html");
PrintWriter out = response.getWriter();

out.print("<br>welcome to servlet<br>");

web.xml

For defining the filter, filter element of web-app must be defined just like servlet.

<web-app>
<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>HelloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>s1</servlet-name>
<url-pattern>/servlet1</url-pattern>
</servlet-mapping>
<filter>
<filter-name>f1</filter-name>
<filter-class>MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>f1</filter-name>
<url-pattern>/servlet1</url-pattern>
</filter-mapping>
</web-app>
26 Explain Attribute in servlet?
An ​attribute in servlet​ is an object that can be set, get or removed from one of the
following scopes:

1. request scope
2. session scope
3. application scope

The servlet programmer can pass informations from one servlet to another using
attributes. It is just like passing object from one class to another so that we can
reuse the same object again and again.

Attribute specific methods of ServletRequest, HttpSession and ServletContext


interface
There are following 4 attribute specific methods. They are as follows:

1. public void setAttribute(String name,Object object):​sets the given object in


the application scope.
2. public Object getAttribute(String name):​Returns the attribute for the
specified name.
3. public Enumeration getInitParameterNames():​Returns the names of the
context's initialization parameters as an Enumeration of String objects.
4. public void removeAttribute(String name):​Removes the attribute with the
given name from the servlet context.

DemoServlet1.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet1 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{

res.setContentType("text/html");
PrintWriter out=res.getWriter();

ServletContext context=getServletContext();
context.setAttribute("company","IBM");

out.println("Welcome to first servlet");


out.println("<a href='servlet2'>visit</a>");
out.close();

}catch(Exception e){out.println(e);}

}}
DemoServlet2.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class DemoServlet2 extends HttpServlet{
public void doGet(HttpServletRequest req,HttpServletResponse res)
{
try{

res.setContentType("text/html");
PrintWriter out=res.getWriter();

ServletContext context=getServletContext();
String n=(String)context.getAttribute("company");

out.println("Welcome to "+n);
out.close();

}catch(Exception e){out.println(e);}
}}

web.xml
<web-app>

<servlet>
<servlet-name>s1</servlet-name>
<servlet-class>DemoServlet1</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>DemoServlet2</servlet-class>
</servlet>

<servlet-mapping>
<servlet-name>s2</servlet-name>
<url-pattern>/servlet2</url-pattern>
</servlet-mapping>
</web-app>

27 What is JSP? Advantages of JSP over Servlet?


JSP​ technology is used to create web application just like Servlet technology. It can
be thought of as an extension to Servlet because it provides more functionality than
servlet such as expression language, JSTL, etc.
A JSP page consists of HTML tags and JSP tags. The JSP pages are easier to maintain
than Servlet because we can separate designing and development. It provides some
additional features such as Expression Language, Custom Tags, etc.

1) Extension to Servlet
JSP technology is the extension to Servlet technology. We can use all the features of
the Servlet in JSP. In addition to, we can use implicit objects, predefined tags,
expression language and Custom tags in JSP, that makes JSP development easy.

2) Easy to maintain
JSP can be easily managed because we can easily separate our business logic with
presentation logic. In Servlet technology, we mix our business logic with the
presentation logic.

3) Fast Development: No need to recompile and redeploy


If JSP page is modified, we don't need to recompile and redeploy the project. The
Servlet code needs to be updated and recompiled if we have to change the look and
feel of the application.

4) Less code than Servlet


In JSP, we can use many tags such as action tags, JSTL, custom tags, etc. that
reduces the code. Moreover, we can use EL, implicit objects, etc.

28 JSP life cycle?


The JSP pages follow these phases:

● Translation of JSP Page


● Compilation of JSP Page
● Classloading (the classloader loads class file)
● Instantiation (Object of the Generated Servlet is created).
● jspInit(): The container calls the jspInit() to initialize the servlet instance. It is
called before any other method, and is called only once for a servlet
instance.
● _jspService(): The container calls the _jspService() for each request and it
passes the request and the response objects. _jspService() method cann?t
be overridden.
● jspDestroy(): The container calls this when its instance is about to destroyed.

29 JSP Scripting element ?


The scripting elements provides the ability to insert java code inside the jsp. There
are three types of scripting elements:

● scriptlet tag
● expression tag
● declaration tag

JSP scriptlet tag


A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:

<% java source code %>

Example of JSP scriptlet tag


In this example, we are displaying a welcome message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>

JSP expression tag:


<html> <body> <%= "welcome to jsp" %> </body> </html>
EX:
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
JSP Declaration Tag :
The JSP declaration tag is used ​to declare fields and methods​.
The code written inside the jsp declaration tag is placed outside the service()
method of auto generated servlet.
So it doesn't get memory at each request.
Ex:
<html>
<body>
<%!
int cube(int n){
return n*n*n*;
}
%>
<%= "Cube of 3 is:"+cube(3) %>
</body>
</html>
30 Write all Implicit Object of JSP in detail.
There are ​9 jsp implicit objects​. These objects are ​created by the web container​ that
are available to all the jsp pages.
The available implicit objects are out, request, config, session, application etc.
A list of the 9 implicit objects is given below:

Object Type

out JspWriter

request HttpServletRequest

response HttpServletResponse

config ServletConfig

application ServletContext

session HttpSession

pageContext PageContext

page Object

exception Throwable
​ ) JSP out implicit object
1
For writing any data to the buffer, JSP provides an implicit object named out. It is
the object of JspWriter. In case of servlet you need to write:
PrintWriter out=response.getWriter();

index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>

2) JSP request implicit object


The ​JSP request​ is an implicit object of type HttpServletRequest i.e. created for each
jsp request by the web container. It can be used to get request information such as
parameter, header information, remote address, server name, server port, content
type, character encoding etc.
It can also be used to set, get and remove attributes from the jsp request scope.

index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>

welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>

3) JSP response implicit object

In JSP, response is an implicit object of type HttpServletResponse. The instance of


HttpServletResponse is created by the web container for each jsp request.

It can be used to add or manipulate response such as redirect response to another


resource, send error etc.

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");
%>

4) JSP config implicit object

In JSP, config is an implicit object of type ​ServletConfig​. This object can be used to
get initialization parameter for a particular JSP page. The config object is created by
the web container for each jsp page.

Generally, it is used to get initialization parameter from the web.xml file.


Example of config implicit object:

index.html

1. <form action="welcome">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>

web.xml file

1. <web-app>
2.
3. <servlet>
4. <servlet-name>sonoojaiswal</servlet-name>
5. <jsp-file>/welcome.jsp</jsp-file>
6.
7. <init-param>
8. <param-name>dname</param-name>
9. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
10. </init-param>
11.
12. </servlet>
13.
14. <servlet-mapping>
15. <servlet-name>sonoojaiswal</servlet-name>
16. <url-pattern>/welcome</url-pattern>
17. </servlet-mapping>
18.
19. </web-app>

welcome.jsp

1. <%
2. out.print("Welcome "+request.getParameter("uname"));
3.
4. String driver=config.getInitParameter("dname");
5. out.print("driver name is="+driver);
6. %>

5) JSP application implicit object


In JSP, application is an implicit object of type ​ServletContext​.
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 configuaration file
(web.xml). It can also be used to get, set or remove attribute from the application
scope.
This initialization parameter can be used by all jsp pages.

Example of application implicit object:


index.html
<form action="welcome">
<input type="text" name="uname">
<input type="submit" value="go"><br/>

</form>

web.xml file
<web-app>

<servlet>
<servlet-name>sonoojaiswal</servlet-name>
<jsp-file>/welcome.jsp</jsp-file>
</servlet>

<servlet-mapping>
<servlet-name>sonoojaiswal</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>
welcome.jsp
<%

out.print("Welcome "+request.getParameter("uname"));

String driver=application.getInitParameter("dname");
out.print("driver name is="+driver);

%>

6) session implicit object


In JSP, session is an implicit object of type HttpSession.The Java developer can use
this object to set,get or remove attribute or to get session information.

Example of session implicit object

index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

welcome.jsp
<html>
<body>
<%

String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
<a href="second.jsp">second jsp page</a>
%>
</body>
</html>

second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>

7) pageContext implicit object


In JSP, pageContext is an implicit object of type PageContext class.The pageContext
object can be used to set,get or remove attribute from one of the following scopes:

● page
● request
● session
● application

In JSP, page scope is the default scope.

Example of pageContext implicit object

index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>

welcome.jsp
<html>
<body>
<%

String name=request.getParameter("uname");
out.print("Welcome "+name);

pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);

<a href="second.jsp">second jsp page</a>

%>
</body>
</html>

second.jsp
<html>
<body>
<%

String
name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);

%>
</body>
</html>

8) page implicit object:

In JSP, page is an implicit object of type Object class.This object is assigned to the
reference of auto generated servlet class. It is written as: Object page=this; For
using this object it must be cast to Servlet type.For example: <%
(HttpServlet)page.log("message"); %> Since, it is of type Object it is less used
because you can use this object directly in jsp.For example: <% this.log("message");
%>

9) exception implicit object


<%@ page isErrorPage="true" %>
<html>
<body>

Sorry following exception occured:<%= exception %>

</body>
</html>
31 JSP directive with example
The ​jsp directives​ are messages that tells the web container how to translate a JSP
page into the corresponding servlet.
There are three types of directives:

● page directive
● include directive
● taglib directive

Syntax of JSP Directive

<%@ directive attribute="value" %>


JSP page directive
The page directive defines attributes that apply to an entire JSP page.

Syntax of JSP page directive

<%@ page attribute="value" %>

Attributes of JSP page directive

● import
● contentType
● extends
● info
● buffer
● language
● isELIgnored
● isThreadSafe
● autoFlush
● session
● pageEncoding
● errorPage
● isErrorPage

1)import

The import attribute is used to import class,interface or all the members of a


package.It is similar to import keyword in java class or interface.

Example of import attribute


<html>
<body>

<%@ page import="java.util.Date" %>


Today is: <%= new Date() %>

</body>
</html>
2)contentType
The contentType attribute defines the MIME(Multipurpose Internet Mail Extension)
type of the HTTP response.The default value is "text/html;charset=ISO-8859-1".

Example of contentType attribute


<html>
<body>

<%@ page contentType=application/msword %>


Today is: <%= new java.util.Date() %>

</body>
</html>

3)extends
The extends attribute defines the parent class that will be inherited by the
generated servlet.It is rarely used.

4)info
This attribute simply sets the information of the JSP page which is retrieved later by
using getServletInfo() method of Servlet interface.

Example of info attribute


<html>
<body>

<%@ page info="composed by Sonoo Jaiswal" %>


Today is: <%= new java.util.Date() %>

</body>
</html>
The web container will create a method getServletInfo() in the resulting servlet.For
example:
public String getServletInfo() {
return "composed by Sonoo Jaiswal";
}
5)buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated by
the JSP page.The default size of the buffer is 8Kb.

Example of buffer attribute


<html>
<body>

<%@ page buffer="16kb" %>


Today is: <%= new java.util.Date() %>

</body>
</html>

6)language
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".

7)isELIgnored

We can ignore the Expression Language (EL) in jsp by the isELIgnored attribute. By
default its value is false i.e. Expression Language is enabled by default. We see
Expression Language later.
1. <%@ page isELIgnored="true" %>//Now EL will be ignored

8)isThreadSafe

Servlet and JSP both are multithreaded.If you want to control this behaviour of JSP
page, you can use isThreadSafe attribute of page directive.The value of isThreadSafe
value is true.If you make it false, the web container will serialize the multiple
requests, i.e. it will wait until the JSP finishes responding to a request before passing
another request to it.If you make the value of isThreadSafe attribute like:

<%@ page isThreadSafe="false" %>


The web container in such a case, will generate the servlet as:
1. public class SimplePage_jsp extends HttpJspBase
2. implements SingleThreadModel{
3. .......
4. }

9)errorPage
The errorPage attribute is used to define the error page, if exception occurs in the
current page, it will be redirected to the error page.

Example of errorPage attribute


//index.jsp
<html>
<body>

<%@ page errorPage="myerrorpage.jsp" %>

<%= 100/0 %>

</body>
</html>

10)isErrorPage
The isErrorPage attribute is used to declare that the current page is the error page.

Note: The exception object can only be used in the error page.

Example of isErrorPage attribute


//myerrorpage.jsp
<html>
<body>

<%@ page isErrorPage="true" %>

Sorry an exception occured!<br/>


The exception is: <%= exception %>

</body>
</html>
Include Directive :
The include directive is used to include the contents of any resource it may be jsp
file, html file or text file. The include directive includes the original content of the
included resource at page translation time (the jsp page is translated only once so it
will be better to include static resource).

Advantage of Include directive


Code Reusability

Syntax of include directive

1. <%@ include file="resourceName" %>

Example of include directive


In this example, we are including the content of the header.html file. To run this
example you must create an header.html file.
<html>
<body>

<%@ include file="header.html" %>

Today is: <%= java.util.Calendar.getInstance().getTime() %>

</body>
</html>
Jsp Taglib Directive​:
The JSP taglib directive is used to define a tag library that defines many tags. We
use the TLD (Tag Library Descriptor) file to define the tags. In the custom tag section
we will use this tag so it will be better to learn it in custom tag.

Syntax JSP Taglib directive

<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

Example of JSP Taglib directive


In this example, we are using our tag named currentDate. To use this tag we must
specify the taglib directive so the container may get information about the tag.
<html>
<body>
<%@ taglib uri="http://www.google.com/tags" prefix="mytag" %>

<mytag:currentDate/>

</body>
</html>
32 Enlist and explain the purpose and use of action tags in JSP?
There are many JSP action tags or elements. Each JSP action tag is used to perform
some specific tasks.
The action tags are used to control the flow between pages and to use Java Bean.
The Jsp action tags are given below.

jsp:forward action tag


The jsp:forward action tag is used to forward the request to another resource it
may be jsp, html or another resource.

Syntax of jsp:forward action tag without parameter

1. <jsp:forward page="relativeURL | <%= expression %>" />

Syntax of jsp:forward action tag with parameter

1. <jsp:forward page="relativeURL | <%= expression %>">


2. <jsp:param name="parametername" value="parametervalue |
<%=expression%>" />
3. </jsp:forward>

Example of jsp:forward action tag without parameter


In this example, we are simply forwarding the request to the printdate.jsp file.

index.jsp
<html>
<body>
<h2>this is index page</h2>

<jsp:forward page="printdate.jsp" />


</body>
</html>

printdate.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
jsp:include action tag :
It is used to include the content of another resource it may be jsp, html or servlet.
The jsp include action tag includes the resource at request time so it is ​better for
dynamic pages​ because there might be changes in future.
The jsp:include tag can be used to include static as well as dynamic pages.

Advantage of jsp:include action tag


Code reusability​ : We can use a page many times such as including header and
footer pages in all pages. So it saves a lot of time.

Syntax of jsp:include action tag without parameter

<jsp:include page="relativeURL | <%= expression %>" />

Syntax of jsp:include action tag with parameter


<jsp:include page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue | <%=expression%>"
/>
</jsp:include>

Java Bean
A Java Bean is a java class that should follow following conventions:

● It should have a no-arg constructor.


● It should be Serializable.
● It should provide methods to set and get the values of the properties,
known as getter and setter methods.

jsp:useBean action tag:


The jsp:useBean action tag is used to locate or instantiate a bean class. If bean
object of the Bean class is already created, it doesn't create the bean depending on
the scope. But if object of bean is not created, it instantiates the bean.

Syntax of jsp:useBean action tag


<jsp:useBean id= "instanceName" scope= "page | request | session | application"
class= "packageName.className" type= "packageName.className"
beanName="packageName.className | <%= expression >" >
</jsp:useBean>
Attributes and Usage of jsp:useBean action tag

1. id: ​is used to identify the bean in the specified scope.


2. scope: ​represents the scope of the bean. It may be page, request, session or
application. The default scope is page.
○ page: ​specifies that you can use this bean within the JSP page. The
default scope is page.
○ request: ​specifies that you can use this bean from any JSP page that
processes the same request. It has wider scope than page.
○ session: ​specifies that you can use this bean from any JSP page in the
same session whether processes the same request or not. It has
wider scope than request.
○ application: ​specifies that you can use this bean from any JSP page in
the same application. It has wider scope than session.
3. class: ​instantiates the specified bean class (i.e. creates an object of the bean
class) but it must have no-arg or no constructor and must not be abstract.
4. type: ​provides the bean a data type if the bean already exists in the scope. It
is mainly used with class or beanName attribute. If you use it without class
or beanName, no bean is instantiated.
5. beanName: ​instantiates the bean using the java.beans.Beans.instantiate()
method.

Calculator.java (a simple Bean class)


package com.abc;
public class Calculator{

public int cube(int n){return n*n*n;}

index.jsp file
<jsp:useBean id="obj" class="com.abc.Calculator"/>

<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>

jsp:setProperty and jsp:getProperty action tags:


The setProperty and getProperty action tags are used for developing web
application with Java Bean. In web devlopment, bean class is mostly used because it
is a reusable software component that represents data.
The jsp:setProperty action tag sets a property value or values in a bean using the
setter method.

Syntax of jsp:setProperty action tag


<jsp:setProperty name="instanceOfBean" property= "*" |
property="propertyName" param="parameterName" |
property="propertyName" value="{ string | <%= expression %>}"
/>

Example of jsp:setProperty action tag if you have to set all the values of incoming
request in the bean

<jsp:setProperty name="bean" property="*" />

Example of jsp:setProperty action tag if you have to set value of the incoming
specific property

<jsp:setProperty name="bean" property="username" />

Example of jsp:setProperty action tag if you have to set a specific value in the
property

<jsp:setProperty name="bean" property="username" value="Kumar" />

jsp:getProperty action tag


The jsp:getProperty action tag returns the value of the property.

Syntax of jsp:getProperty action tag

<jsp:getProperty name="instanceOfBean" property="propertyName" />

Simple example of jsp:getProperty action tag


<jsp:getProperty name="obj" property="name" />

Ex:

index.html
<form action="process.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password" name="password"><br>
Email:<input type="text" name="email"><br>
<input type="submit" value="register">

</form>

process.jsp
<jsp:useBean id="u" class="org.sssit.User"></jsp:useBean>
<jsp:setProperty property="*" name="u"/>

Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>

<jsp:getProp​erty property="email" name="u" /><br>

User.java
package org.sssit;

public class User {


private String name,password,email;
//setters and getters
}
33 Give an example showing the use of EL functions.
34 Explain JSTL in detail.
JSTL stands for​ Java​ ​server pages standard tag library, and it is a collection of
custom JSP tag libraries that provide common web development functionality.

Advantages of JSTL

1. Standard Tag​: It provides a rich layer of the portable functionality of JSP


pages. It's easy for a developer to understand the code.
2. Code Neat and Clean​: As scriplets confuse developer, the usage of JSTL
makes the code neat and clean.
3. Automatic JavabeansInterospection Support​: It has an advantage of JSTL
over JSP scriptlets. JSTL Expression language handles JavaBean code very
easily. We don't need to downcast the objects, which has been retrieved as
scoped attributes. Using JSP scriptlets code will be complicated, and JSTL has
simplified that purpose.
4. Easier for humans to read​: JSTL is based on XML, which is very similar to
HTML. Hence, it is easy for the developers to understand.
5. Easier for computers to understand​: Tools such as Dreamweaver and front
page are generating more and more HTML code. HTML tools do a great job
of formatting HTML code. The HTML code is mixed with the scriplet code. As
JSTL is expressed as XML compliant tags, it is easy for HTML generation to
parse the JSTL code within the document.

Tag Name Description

Core tags The JSTL core tag provide variable support, URL management, flow
control, etc. The URL for the core tag is
http://java.sun.com/jsp/jstl/core​. The prefix of core tag is ​c​.

Function tags The functions tags provide support for string manipulation and
string length. The URL for the functions tags is
http://java.sun.com/jsp/jstl/functions​ and prefix is ​fn​.

Formatting The Formatting tags provide support for message formatting,


tags number and date formatting, etc. The URL for the Formatting tags is
http://java.sun.com/jsp/jstl/fmt​ and prefix is ​fmt​.

XML tags The XML tags provide flow control, transformation, etc. The URL for
the XML tags is ​http://java.sun.com/jsp/jstl/xml​ and prefix is ​x​.

SQL tags The JSTL SQL tags provide SQL support. The URL for the SQL tags is
http://java.sun.com/jsp/jstl/sql​ and prefix is ​sql​.

35 JSTL Core teg?


The core tags are most frequently used tags in JSP. They provide support for

● Iteration
● Conditional logic
● Catch exception
● url forward
● Redirect, etc.

To use core tags we need to define tag library first and below is the syntax to
include a tag library.
JSTL Core Tags List
C:out​ ​: It display the result of an expression, similar to the way <%=...%> tag work.
C:import​ ​: It Retrives relative or an absolute URL and display the contents to either
a String in 'var',a Reader in 'varReader' or the page.
C​:set​ ​:It sets the result of an expression under evaluation in a 'scope' variable.
C:remove​ : It is used for removing the specified scoped variable from a particular
scope.
C:catch​ : It is used for Catches any Throwable exceptions that occurs in the body.
C:if​ :​ It is conditional tag used for testing the condition and display the body content
only if the expression evaluates is true.
c:choose, c:when, c:otherwise​ :It is the simple conditional tag that includes its body
content if the evaluated condition is true.
c:forEach​ ​:It is the basic iteration tag. It repeats the nested body content for fixed
number of times or over collection.
C:for :​T​okens​ It iterates over tokens which is separated by the supplied delimeters.
c:param​ : It adds a parameter in a containing 'import' tag's URL.
C:redirect​ : It redirects the browser to a new URL and supports the context-relative
URLs.
​C:url​ ​: It creates a URL with optional query parameters.
Ex:
<%@ page language="java" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
<title>Core Tag JSP4</title>
</head>
<body>
<c:forEach var="gurucount" begin="5" end="10">
<c:out value="${gurucount}"/>
</c:forEach>
</body>
</html>

36
JSTL Function Tags :
The JSTL function provides a number of standard functions, most of these functions
are common string manipulation functions. The syntax used for including JSTL
function library in your JSP is:
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>

Tag List

fn:contains()​ :It is used to test if an input string containing the specified substring in
a program.

fn:containsIgnoreCase()​ It is used to test if an input string contains the specified


substring as a case insensitive way.

​fn:endsWith()​ It is used to test if an input string ends with the specified suffix.

​fn:escapeXml()​ It escapes the characters that would be interpreted as XML markup.

f​ n:indexOf()​ It returns an index within a string of first occurrence of a specified


substring.

fn:trim()​ It removes the blank spaces from both the ends of a string.

​fn:startsWith()​ It is used for checking whether the given string is started with a
particular string value.

fn:split()​ It splits the string into an array of substrings.

fn:toLowerCase()​ It converts all the characters of a string to lower case.

fn:toUpperCase()​ It converts all the characters of a string to upper case.

fn:substring()​ It returns the subset of a string according to the given start and end
position.

​fn:substringAfter()​ It returns the subset of string after a specific substring.

fn:substringBefore()​ It returns the subset of string before a specific substring.

fn:length()​ ​It returns the number of characters inside a string, or the number of
items in a collection.

fn:replace()​ It replaces all the occurrence of a string with another string sequence.

Ex:
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<title> Using JSTL Function </title>
</head>
<body>
<c:set var="string" value="Welcome to JSP Programming"/>
${fn:toLowerCase("HELLO,")}
${fn:toLowerCase(string)}
</body>
</html>
37 JSTL XML tag:
The JSTL XML tags are used for providing a JSP-centric way of manipulating and
creating XML documents.
The xml tags provide flow control, transformation etc. The url for the xml tags is
http://java.sun.com/jsp/jstl/xml​ and prefix is x. The JSTL XML tag library has
custom tags used for interacting with XML data. The syntax used for including JSTL
XML tags library in your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/xml" prefix="x" %>

Tag list:

x:out​ Similar to <%= ... > tag, but for XPath expressions.

x:parse​ It is used for parse the XML data specified either in the tag body or an
attribute.

x:set​ It is used to sets a variable to the value of an XPath expression.

x:choose​ It is a conditional tag that establish a context for mutually exclusive


conditional operations.

x:when​ It is a subtag of that will include its body if the condition evaluated be 'true'.

x:otherwise​ It is subtag of that follows tags and runs only if all the prior conditions
evaluated be 'false'.

x​ :if​ It is used for evaluating the test XPath expression and if it is true, it will
processes its body content.

x:transform​ It is used in a XML document for providing the XSL(Extensible


Stylesheet Language) transformation.

x:param​ It is used along with the transform tag for setting the parameter in the
XSLT style sheet.
Ex:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>


<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>

<html>
<head>
<title>XML Tags</title>
</head>
<body>
<h2>Vegetable Information:</h2>
<c:set var="vegetable">
<vegetables>
<vegetable>
<name>onion</name>
<price>40/kg</price>
</vegetable>
<vegetable>
<name>Potato</name>
<price>30/kg</price>
</vegetable>
<vegetable>
<name>Tomato</name>
<price>90/kg</price>
</vegetable>
</vegetables>
</c:set>
<x:parse xml="${vegetable}" var="output"/>
<b>Name of the vegetable is</b>:
<x:out select="$output/vegetables/vegetable[1]/name" /><br>
<b>Price of the Potato is</b>:
<x:out select="$output/vegetables/vegetable[2]/price" />
</body>
</html>
38 JSTL SQL Tag:
The JSTL sql tags provide SQL support. The url for the sql tags is
http://java.sun.com/jsp/jstl/sql​ and prefix is ​sql​.
The SQL tag library allows the tag to interact with RDBMSs (Relational Databases)
such as Microsoft SQL Server, mySQL, or Oracle. The syntax used for including JSTL
SQL tags library in your JSP is:

<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>


Tag list:

sql:setDataSource​ It is used for creating a simple data source suitable only for
prototyping.

sql:query​ It is used for executing the SQL query defined in its sql attribute or the
body.

sql:update​ It is used for executing the SQL update defined in its sql attribute or in
the tag body.

s​ ql:param​ It is used for sets the parameter in an SQL statement to the specified
value.

sql:dateParam​ It is used for sets the parameter in an SQL statement to a specified


java.util.Date value.

sql:transaction​ It is used to provide the nested database action with a common


connection.

Ex:

<%@ page import="java.io.*,java.util.*,java.sql.*"%>


<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

<html>
<head>
<title>sql:query Tag</title>
</head>
<body>

<sql:setDataSource var="db" driver="com.mysql.jdbc.Driver"


url="jdbc:mysql://localhost/test"
user="root" password="1234"/>

<sql:query dataSource="${db}" var="rs">


SELECT * from Students;
</sql:query>

<table border="2" width="100%">


<tr>
<th>Student ID</th>
<th>First Name</th>
<th>Last Name</th>
<th>Age</th>
</tr>
<c:forEach var="table" items="${rs.rows}">
<tr>
<td><c:out value="${table.id}"/></td>
<td><c:out value="${table.First_Name}"/></td>
<td><c:out value="${table.Last_Name}"/></td>
<td><c:out value="${table.Age}"/></td>
</tr>
</c:forEach>
</table>

</body>
</html>
39 What is JSF ? Explain JSF life cycle phases.
When the user requests for a page, the lifecycle of JSF begins. JavaServer faces
builds the current view from the previously saved state which is infact from the
state of the submission of the previous page. The framework performs certain tasks
like validating the inputs fields of the page, generating response and so on.
● Restore view phase
● Apply request values phase; process events
● Process validations phase; process events
● Update model values phase; process events
● Invoke application phase; process events
● Render response phase

1. Restore view phase​: Whenever a request arrives, this is the first phase that
gets initiated. When the request arrives​​ – that is, when a button or a link is
clicked, jsf builds the view, prepares the event handlers, validates the ui
components and saves the view in a faces context. This faces context will
have all the previous request’s information to process the current request. If
the request is an initial one, the JSF creates an empty view and displays it to
the user during a postback. If the postback view already exists, the
information is popped out from the saved state.
2. Apply request values​: Once the components are restored from in the first
phase, each component extracts its new value which might have been
changed from the previous state through a decode method. The extracted
value is then stored locally(native data type) along with the component. If
the process of decoding fails, an error message is generated and stored in
faces context for further action. If the components have their immediate JSF
attributes set to true in the page then the events, validation and conversion
related to the page will be processed. If any decode method calls the render
response phase then the the control is redirected to render response phase
itself.
If the application needs to redirect to a different application it can call
FacesContext.responseComplete. By the end of this phase the new values
will be set and messages, events will be queued.
3. Process validations phase​: During this phase all the field related validations
are processed and added to the component tree. Each and every rule is
examined and compared with the values stored on the local component. If
the values on the local component is invalid, error messages are registered
in faces context and the same page is rendered again with the error
message there by navigating to the render response phase.
4. Update model values phase​: Since the Data validations are done in the
validation phase now the corresponding server object properties are set and
stored in the local components. The bean properties are updated to the
corresponding input component attributes.
5. Invoke application phase​: The events like submitting a form, click of a link
are handled in this phase. If the processed views are reconstructed based on
state information of previous request and if the event is fired it will be
broadcasted to interested listeners. If redirection to different web
application is invoked again the transition to response render phase takes
place.
6. Render response phase​: The Java Server Faces first checks whether it is a jsp
page and if yes, the control is transferred to JSP Container. If the request is
an initial one, the page is added to the component tree first and stored. If it
is not an initial request, the component will already be stored and hence it
just gets rendered. In either case the components will render themselves as
the JSP container traverses the tags in the page. If any errors are
encountered during this process the relevant messages are displayed. After
the view is rendered the content will be stored so that when the same
request arrives, it can be accessed and also be available for restore view
phase.

40 What is JSF ?Explain JSF Standard Component in detail.


JavaServer Faces (JSF) is a new standard Java framework for building Web
applications. It simplifies development by providing a component-centric approach
to developing Java Web user interfaces. JavaServer Faces also appeals to a diverse
audience of Java/Web developers. "Corporate developers" and Web designers will
find that JSF development can be as simple as dragging and dropping user interface
(UI) components onto a page, while "systems developers" will find that the rich and
robust JSF API offers them unsurpassed power and programming flexibility. JSF also
ensures that applications are well designed with greater maintainability by
integrating the well established Model-View-Controller (MVC) design pattern into
it's architecture. Finally, since JSF is a Java standard developed through Java
Community Process (JCP), development tools vendors are fully empowered to
provide easy to use, visual, and productive develop environments for JavaServer
Faces.

Library Namespace Identifier Commonly


Used Prefix

Core http://java.sun.com/jsf/core f:

HTML http://java.sun.com/jsf/html h:

Facelets h​ttp://java.sun.com/jsf/facelets ui:

Composite Components http://java.sun.com/jsf/composite composite:

JSTL Core http://java.sun.com/jsp/jstl/core c:

JSTL Functions http://java.sun.com/jsp/jstl/functions fn:

41 List the JSF facelets tags


JSF provides a special set of tags that gives the flexibility to manage common tags/parts
in one place for more than one application. These tags allow us to create a common
layout that can be used across applications.
To use the Facelet tags in the JSF page include the following namespace.
<html
xmlns="http://www.w3.org/1999/xhtml"
xmlns:ui="​http://java.sun.com/jsf/facelets​">
The following tags are provided by the Facelet tags.
1 <ui:component> tag

2 <ui:composition> tag

3 <ui:decorate> tag

4 <ui:define> tag

5 <ui:fragment> tag

6 <ui:include> tag

7 <ui:insert> tag

8 <ui:param> tag

9 <ui:remove> tag

10 <ui:repeat> tag

<ui:component> tag​ :

<?xml version='1.0' encoding='UTF-8' ?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://xmlns.jcp.org/jsf/html"
xmlns:ui="http://xmlns.jcp.org/jsf/facelets">
<h:head>
<title>UI Component tag</title>
</h:head>
<h:body>
<ui:component>
Hello!!!

</ui:component>
Hi You there?
</h:body>
</html>

42 List the JSF validation tags


JSF validation model defines a set of standard classes for validating the UI
components. The JSF library defines a group of core tags that corresponds to
javax.faces.validator.Validator implementations. Apart from the standard error
messages validation model allows us to define the custom validations. Validations
in JSF can be categorized into Imperative and Declarative.

JSF Validation – Declarative Validator

<?xml version='1.0' encoding='UTF-8' ?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
<h3>Add Mobile Details</h3>
<h:form>
<h:panelGrid columns="3">
<h:outputLabel for="mname">Mobile Name:</h:outputLabel>
<h:inputText id="mname" required="true"
requiredMessage="Mobile Name is
mandatory"></h:inputText>
<br>
<br>

<h:outputLabel for="color">Color:</h:outputLabel>
<h:inputText id="color" required="true"></h:inputText>
<br>
<br>

<h:outputLabel for="model">Model Number:</h:outputLabel>


<h:inputText id="model"></h:inputText>
<br>
<br>

<h:commandButton value="Submit"></h:commandButton>
</h:panelGrid>
</h:form>
</h:body>
</html>

JSF Imperative validation

<?xml version='1.0' encoding='UTF-8' ?>


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
</h:head>
<h:body>
<h3>Add Mobile Details</h3>
<h:form>
<h:outputLabel for="mno">Model Number:</h:outputLabel>
<h:inputText id="mno" value="#{mobile.mno}" required="true" size="4"
disabled="#{mobile.mno}" validator="#{mobile.validateModelNo}">
</h:inputText>
<h:commandButton value="Submit"></h:commandButton>
</h:form>
</h:body>
</html>

package com.journaldev.jsf.bean;

import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.component.UIComponent;
import javax.faces.component.UIInput;
import javax.faces.context.FacesContext;
@ManagedBean
@SessionScoped
public class Mobile implements Serializable {

private static final long serialVersionUID = -7250065889869767422L;

// @NotNull(message="Please enter the model number")


private String mno;

public String getMno() {


return mno;
}

public void setMno(String mno) {


this.mno = mno;
}

public void validateModelNo(FacesContext context, UIComponent comp,


Object value) {

System.out.println("inside validate method");

String mno = (String) value;

if (mno.length() < 4) {
((UIInput) comp).setValid(false);

FacesMessage message = new FacesMessage(


"Minimum length of model number is 4");
context.addMessage(comp.getClientId(context), message);

}
}
}
43 What is hibernate? List the advantages of hibernate over JDBC.
Hibernate is a free, open source object-relational mapping library for Java designed
to map objects to an RDBMS and to implement the object-oriented programming
concepts in a relational database.
1)Hibernate is data base independent, same code will work for all data bases like
ORACLE,MySQL ,SQLServer etc. In case of JDBC query must be data base specific.

2)As Hibernate is set of Objects , you don't need to learn SQL language.
You can treat TABLE as a Object .In case of JDBC you need to learn SQL.

3)Don't need Query tuning in case of Hibernate. If you use Criteria Quires in
Hibernate then hibernate automatically tuned your query and return best result
with performance.
In case of JDBC you need to tune your queries.

4)You will get benefit of Cache. Hibernate support two level of cache. First level and
2nd level. So you can store your data into Cache for better performance.In case of
JDBC you need to implement your java cache .
5)Hibernate supports Query cache and It will provide the statistics about your query
and database status.JDBC Not provides any statistics.

6)Development fast in case of Hibernate because you don't need to write queries.

7)No need to create any connection pool in case of Hibernate. You can use c3p0.
In case of JDBC you need to write your own connection pool.

8)In the xml file you can see all the relations between tables in case of Hibernate.
Easy readability.

9)You can load your objects on start up using lazy=false in case of Hibernate.JDBC
Don't have such support.
10 ) Hibernate Supports automatic versioning of rows but JDBC Not.
44 Explain architecture of Hibernate
Configuration
It represents a configuration required to use the hibernate , which could be properties
file or XML file.
The Configuration object is usually created once during application initialization.
The Configuration object uses the configuration details from the configuration file to
get connected to a database.
A Configuration object is used to create a SessionFactory.

Object Relational Mapping


The mapping between Java POJO class and the database tables is provided using either
XML or annotation.

SessionFactory
It is the factory for the session objects.
It is thread safe and immutable object representing the mappings for a single database.
It can hold the second level cache in hibernate

Session
It’s a single-threaded, short-lived object which acts as a bridge between Java
application and Hibernate.
It wraps a JDBC connection and is a factory for Transaction.
Session holds a mandatory first-level cache of persistent objects

Transient objects
Instances of persistent classes which are not currently associated with a Session

Persistent objects
They are associated with Session and Once the Session is closed, they will be detached
and free to use in any application layer

Query
Query objects use Native SQL or Hibernate Query Language (HQL) to retrieve data from
the database.
A Query instance is used to bind query parameters such as number of results returned
by the query.
We can obtain the query object from the session using session.createQuery()

Criteria
The org.hibernate.Criteria is used to retrieve the entities based on some criteria like
getting all employees by specific age or specific date of joining etc.
We can get the Criteria from the Session.

TransactionFactory
A factory for Transaction instances,It is not exposed to the application and it’s optional.

Transaction
single-threaded, short-lived object used by the application to specify atomic units of
work
We can obtain the transaction from the Session object.

ConnectionProvider
It’s a pool of JDBC connections

45 Explain the OR mapping in hibernate with example.


ORM stands for ​O​bject-​R​elational ​M​apping (ORM) is a programming technique for
converting data between relational databases and object oriented programming
languages such as Java, C#, etc.
Hibernate ORM enables developers to more easily write applications whose data
outlives the application process. As an Object/Relational Mapping (ORM)
framework, Hibernate is concerned with data persistence as it applies to relational
databases (via JDBC). Unfamiliar with the notion of ORM?

JPA Provider
In addition to its own "native" API, Hibernate is also an implementation of the Java
Persistence API (JPA) specification. As such, it can be easily used in any environment
supporting JPA including Java SE applications, Java EE application servers, Enterprise
OSGi containers, etc.

Idiomatic persistence
Hibernate enables you to develop persistent classes following natural
Object-oriented idioms including inheritance, polymorphism, association,
composition, and the Java collections framework. Hibernate requires no interfaces
or base classes for persistent classes and enables any class or data structure to be
persistent.

High Performance
Hibernate supports lazy initialization, numerous fetching strategies and optimistic
locking with automatic versioning and time stamping. Hibernate requires no special
database tables or fields and generates much of the SQL at system initialization
time instead of at runtime.
Hibernate consistently offers superior performance over straight JDBC code, both in
terms of developer productivity and runtime performance.

Scalability
Hibernate was designed to work in an application server cluster and deliver a highly
scalable architecture. Hibernate scales well in any environment: Use it to drive your
in-house Intranet that serves hundreds of users or for mission-critical applications
that serve hundreds of thousands.

Reliable
Hibernate is well known for its excellent stability and quality, proven by the
acceptance and use by tens of thousands of Java developers.
Extensibility
Hibernate is highly configurable and extensible.

Granularity
Sometimes you will have an object model which has more classes than the number
of corresponding tables in the database (we says the object model is more granular
than the relational model). Take for example the notion of an Address…​

Subtypes (inheritance)
Inheritance is a natural paradigm in object-oriented programming languages.
However, RDBMSs do not define anything similar on the whole (yes some databases
do have subtype support but it is completely non-standardized)…​

Identity
A RDBMS defines exactly one notion of 'sameness': the primary key. Java, however,
defines both object identity a==b and object equality a.equals(b).

Associations
Associations are represented as unidirectional references in Object Oriented
languages whereas RDBMSs use the notion of foreign keys. If you need bidirectional
relationships in Java, you must define the association twice.
Likewise, you cannot determine the multiplicity of a relationship by looking at the
object domain model.

Data navigation
The way you access data in Java is fundamentally different than the way you do it in
a relational database. In Java, you navigate from one association to an other
walking the object network.
This is not an efficient way of retrieving data from a relational database. You
typically want to minimize the number of SQL queries and thus load several entities
via JOINs and select the targeted entities before you start walking the object
network.
Ex:
public class Employee {
private int id;
private String first_name;
private String last_name;
private int salary;

public Employee() {}
public Employee(String fname, String lname, int salary) {
this.first_name = fname;
this.last_name = lname;
this.salary = salary;
}

public int getId() {


return id;
}

public String getFirstName() {


return first_name;
}

public String getLastName() {


return last_name;
}

public int getSalary() {


return salary;
}
}
create table EMPLOYEE (
id INT NOT NULL auto_increment,
first_name VARCHAR(20) default NULL,
last_name VARCHAR(20) default NULL,
salary INT default NULL,
PRIMARY KEY (id)
);

46 What is HQL? How does it differ from SQL? Give its advantages.
Hibernate uses a powerful query language (HQL) that is similar in appearance to
SQL. Compared with SQL, however, HQL is fully object-oriented and understands
notions like inheritance, polymorphism and association.
Advantages:
1. HQL is similar to SQL and is also case insensitive.
2. HQL and SQL both fire queries in a database. In the case of HQL, the queries are
in
the form of objects that are translated to SQL queries in the target database.
3. SQL works with tables and columns to manipulate the data stored in it.
4. HQL works with classes and their properties to finally be mapped to a table
structure
in a database.
5. HQL supports concepts like polymorphism, inheritance, association, etc. It is a
powerful and easy-to-learn language that makes SQL object oriented.
6. SQL lets you modify the data through insert, update, and delete queries. You can
add
tables, procedures, or views to your database. The permissions on these added
objects
can be changed.
7 database independent
8 supports polymorphic queries

9 easy to learn for Java Programmer

Ex 1:

Query query=session.createQuery("from Emp");//here persistent class name is Emp


List list=query.list();

Ex 2:

Transaction tx=session.beginTransaction();
Query q=session.createQuery("update User set name=:n where id=:i");
q.setParameter("n","Udit Kumar");
q.setParameter("i",111);

int status=q.executeUpdate();
System.out.println(status);
tx.commit();
47 Briefly explain spring bean life cycle.
1. Creation of bean instance by a​ factory method​.
2. Set the values and bean references to the bean properties.
3. Call the initialization call back method.
4. Bean is ready for use.
5. Call the destruction call back method.

Spring can recognize the initialization and destruction callback methods in the below
three ways.

1. A Bean can implement the ​InitializingBean​ ​and ​DisposableBean​ l​ ife cycle


interfaces and overriding the ​afterPropertiesSet() ​(Called during​ Spring bean
initialization​) and ​destroy()​ methods for initialization and destruction
respectively.
2. Set the ​init-method​ a​ nd ​destroy-method​ attributes in the bean configuration
file.
3. Use ​@PostConstruct​ and ​@PreDestroy​ over the methods (Spring 2.5 or later)
which is defined in JSR-250.

48 What is Spring Web MVC framework? List its key features.


● Model​ - A model contains the data of the application. A data can be a single
object or a collection of objects.
● Controller​ - A controller contains the business logic of an application. Here,
the @Controller annotation is used to mark the class as the controller.
● View​ - A view represents the provided information in a particular format.
Generally, JSP+JSTL is used to create a view page. Although spring also
supports other view technologies such as Apache Velocity, Thymeleaf and
FreeMarker.
● Front Controller​ - In Spring Web MVC, the DispatcherServlet class works as
the front controller. It is responsible to manage the flow of the Spring MVC
application.

Features Of Spring Framework:

● Lightweight: ​Spring Framework is lightweight with respect to size and


transparency.
● Inversion Of Control (IOC): ​In Spring Framework, loose coupling is achieved
using Inversion of Control. The objects give their own dependencies instead
of creating or looking for dependent objects.
● Aspect Oriented Programming (AOP): ​By separating application business
logic from system services, Spring Framework supports Aspect Oriented
Programming and enables cohesive development.
● Container: ​Spring Framework creates and manages the life cycle and
configuration of application objects.
● MVC Framework: ​Spring Framework is a MVC web application framework.
This framework is configurable via interfaces and accommodates multiple
view technologies.
● Transaction Management: ​For transaction management,​ ​Spring framework
provides a generic abstraction layer. It is not tied to J2EE environments and
it can be used in container-less environments.
● JDBC Exception Handling: ​The JDBC abstraction layer of the Spring
Framework offers an exception hierarchy, which simplifies the error
handling strategy.

49 What is Spring IoC container?


The IoC container is responsible to instantiate, configure and assemble the objects.
The IoC container gets informations from the XML file and works accordingly. The
main tasks performed by IoC container are:

● to instantiate the application class


● to configure the object
● to assemble the dependencies between the objects

There are two types of IoC containers. They are:

1. BeanFactory
2. ApplicationContext

Using BeanFactory
The XmlBeanFactory is the implementation class for the BeanFactory interface. To
use the BeanFactory, we need to create the instance of XmlBeanFactory class as
given below:

Resource resource=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(resource);

The constructor of XmlBeanFactory class receives the Resource object so we need


to pass the resource object to create the object of BeanFactory.

Using ApplicationContext
The ClassPathXmlApplicationContext class is the implementation class of
ApplicationContext interface. We need to instantiate the
ClassPathXmlApplicationContext class to use the ApplicationContext as given below:
ApplicationContext context = new
ClassPathXmlApplicationContext("applicationContext.xml");

The constructor of ClassPathXmlApplicationContext class receives string, so we can


pass the name of the xml file to create the instance of ApplicationContext.
50 What is Dependency Injection?
Dependency Injection (DI) is a design pattern that removes the dependency from
the programming code so that it can be easy to manage and test the application.
Dependency Injection makes our programming code loosely coupled.
Two ways to perform Dependency Injection in Spring framework
Spring framework provides two ways to inject dependency

● By Constructor
● By Setter method

We can inject the dependency by constructor. The ​<constructor-arg>​ subelement


of ​<bean>​ is used for constructor injection. Here we are going to inject

1. primitive and String-based values


2. Dependent object (contained object)
3. Collection values etc.

Injecting primitive and string-based values


Ex:
package com.ait;

public class Employee {


private int id;
private String name;

public Employee() {System.out.println("def cons");}

public Employee(int id) {this.id = id;}

public Employee(String name) { this.name = name;}

public Employee(int id, String name) {


this.id = id;
this.name = name;
}

void show(){
System.out.println(id+" "+name);
}

applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans
xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:p="http://www.springframework.org/schema/p"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

<bean id="e" class="com.ait.Employee">


<constructor-arg value="10" type="int"></constructor-arg>
</bean>

</beans>
Test.java
package com.ait;

import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;

public class Test {


public static void main(String[] args) {

Resource r=new ClassPathResource("applicationContext.xml");


BeanFactory factory=new XmlBeanFactory(r);

Employee s=(Employee)factory.getBean("e");
s.show();

}
}

51 What is Spring AOP?


Aspect Oriented Programming​ (AOP) compliments OOPs in the sense that it also
provides modularity. But the key unit of modularity is aspect than class.
AOP breaks the program logic into distinct parts (called concerns). It is used to
increase modularity by ​cross-cutting concerns​.
A ​cross-cutting concern​ is a concern that can affect the whole application and
should be centralized in one location in code as possible, such as transaction
management, authentication, logging, security etc.
AOP concepts and terminologies are as follows:

● Join point
● Advice
● Pointcut
● Introduction
● Target Object
● Aspect
● Interceptor
● AOP Proxy
● Weaving

Join point
Join point is any point in your program such as method execution, exception
handling, field access etc. Spring supports only method execution join point.

Advice
Advice represents an action taken by an aspect at a particular join point. There are
different types of advices:

● Before Advice​: it executes before a join point.


● After Returning Advice​: it executes after a joint point completes normally.
● After Throwing Advice​: it executes if method exits by throwing an
exception.
● After (finally) Advice​: it executes after a join point regardless of join point
exit whether normally or exceptional return.
● Around Advice​: It executes before and after a join point.

Pointcut
It is an expression language of AOP that matches join points.

Introduction
It means introduction of additional method and fields for a type. It allows you to
introduce new interface to any advised object.

Target Object
It is the object i.e. being advised by one or more aspects. It is also known as proxied
object in spring because Spring AOP is implemented using runtime proxies.

Aspect
It is a class that contains advices, joinpoints etc.

Interceptor
It is an aspect that contains only one advice.

AOP Proxy
It is used to implement aspect contracts, created by AOP framework. It will be a JDK
dynamic proxy or CGLIB proxy in spring framework.

Weaving
It is the process of linking aspect with other application types or objects to create
an advised object. Weaving can be done at compile time, load time or runtime.
Spring AOP performs weaving at runtime.

AOP Implementations
AOP implementations are provided by:

1. AspectJ
2. Spring AOP
3. JBoss AOP

You might also like