AJT Notes
AJT Notes
//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);}
}
}
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 :
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");
}
}
4 Java Socket Programming connection oriented communication
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
//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
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:
● easy to use.
● can be easily connected to any database.
Disadvantages:
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:
Disadvantage:
Disadvantages:
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:
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");
"jdbc:oracle:thin:@localhost:1521:xe","system","password");
while(rs.next()){
System.out.println(rs.getInt(1)+" "+rs.getString(2));
}
MYSQL:
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);}
}
}
Method Description
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.
11 Explain PreparedStatement?
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");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
}
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));
System.out.println("success");
}
}
5) public boolean absolute(int row): is used to move the cursor to the spec
number in the ResultSet object.
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 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");
con.close();
}catch(Exception e){ System.out.println(e);}
}
}
Diagrammatic Representation :
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.
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
Servlets can read and Set HTTP Headers CGI cannot read and Set HTTP Heade
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.
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.
● 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.
<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
Ex:
import java.io.*;
import javax.servlet.*;
res.setContentType("text/html");
PrintWriter out=res.getWriter();
out.print("<html><body>");
out.print("<b>hello generic servlet</b>");
out.print("</body></html>");
}
}
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.
Ex:
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.
Ex:
DemoServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.*;
response.sendRedirect("http://www.google.com");
pw.close();
}}
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";}
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.
5) Get request is more efficient Post request is less efficient and used less than g
and used more than Post.
3) Both include() and forward() can interact with static and dynamic resource e.g.
another Servlet, JSP or HTML files.
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.
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
Advantage of Cookies
Disadvantage of Cookies
Ex:
index.html
FirstServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}catch(Exception e){System.out.println(e);}
}
}
SecondServlet.java
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
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.*;
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.*;
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
Advantage of Filter
1. Filter is pluggable.
2. One filter don't have dependency onto another resource.
3. Less Maintenance
Ex:
index.html
MyFilter.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.*;
PrintWriter out=resp.getWriter();
out.print("filter is invoked before");
HelloServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.*;
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.
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");
}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>
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.
● scriptlet tag
● expression tag
● declaration tag
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>
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);
%>
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");
%>
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.
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. %>
</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);
%>
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>
● page
● request
● session
● application
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);
%>
</body>
</html>
second.jsp
<html>
<body>
<%
String
name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOPE);
out.print("Hello "+name);
%>
</body>
</html>
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");
%>
</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
● import
● contentType
● extends
● info
● buffer
● language
● isELIgnored
● isThreadSafe
● autoFlush
● session
● pageEncoding
● errorPage
● isErrorPage
1)import
</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".
</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.
</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.
</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:
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.
</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.
</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).
</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.
<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.
index.jsp
<html>
<body>
<h2>this is index page</h2>
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.
Java Bean
A Java Bean is a java class that should follow following conventions:
index.jsp file
<jsp:useBean id="obj" class="com.abc.Calculator"/>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
Example of jsp:setProperty action tag if you have to set all the values of incoming
request in the bean
Example of jsp:setProperty action tag if you have to set value of the incoming
specific property
Example of jsp:setProperty action tag if you have to set a specific value in the
property
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>
User.java
package org.sssit;
Advantages of JSTL
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.
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.
● 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 :Tokens 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:endsWith() It is used to test if an input string ends with the specified suffix.
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:substring() It returns the subset of a string according to the given start and end
position.
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:
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: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:param It is used along with the transform tag for setting the parameter in the
XSLT style sheet.
Ex:
<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:
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.
Ex:
<html>
<head>
<title>sql:query Tag</title>
</head>
<body>
</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.
Core http://java.sun.com/jsf/core f:
HTML http://java.sun.com/jsf/html h:
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 :
</ui:component>
Hi You there?
</h:body>
</html>
<h:outputLabel for="color">Color:</h:outputLabel>
<h:inputText id="color" required="true"></h:inputText>
<br>
<br>
<h:commandButton value="Submit"></h:commandButton>
</h:panelGrid>
</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 {
if (mno.length() < 4) {
((UIInput) comp).setValid(false);
}
}
}
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.
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
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;
}
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
Ex 1:
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. 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:
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");
● By Constructor
● By Setter method
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">
</beans>
Test.java
package com.ait;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.xml.XmlBeanFactory;
import org.springframework.core.io.*;
Employee s=(Employee)factory.getBean("e");
s.show();
}
}
● 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:
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