0% found this document useful (0 votes)
6 views58 pages

unit 4,5 web tech

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 58

UNIT-4

Enterprise Java Beans (EJB)


• EJB stands for Enterprise Java Beans.
• Enterprise Java Beans is a server-side component.
• EJB is an essential part of a J2EE platform.
• J2EE application container contains the components that can be used by client for executing
business logic. These components are called EJB.
• EJB Mainly contain the business logic and business data.
• EJB component always lie in some container which is called EJB container.
• EJB component is an EJB class which is written by developer that implement business logic.
• It is a specification provided by Sun Microsystems to develop secured, robust and scalable
distributed applications.
• To run EJB application, you need an application server (EJB Container) such as Jboss,
Glassfish, Weblogic, Websphere etc.
• EJB application is deployed on the server, so it is called server-side component also.
• EJB Container performs:
1. life cycle management,
2. security,
3. transaction management, and
4. object pooling

When use Enterprise Java Bean?

1. Application needs Remote Access. In other words, it is distributed.


2. Application needs to be scalable. EJB applications supports load balancing, clustering
and fail-over.
3. Application needs encapsulated business logic. EJB application is separated from
presentation and persistent layer.

EJB Architecture:

• EJB Server: contains EJB container


• EJB client: An EJB client usually provides the user interface logic on a client machine.
• An EJB client does not communicate directly with an EJB component.
1. remote interface: defines the business method that can be called by the client.
2. home interface: methods to create and destroy proxy from remote servers.
• EJB container: the EJB specification defines a container as the environment in which
one or more EJB components execute.
Advantages of EJB:

1. It can run in multithreaded environment.


2. It contains only business logic.
3. EJB provides distributed transaction support.
4. It provides portable and scalable solutions of the problem.
5. It provides a mechanism to store and retrieve data in a persistent way.

Disadvantages of EJB:

1. It requires application server.


2. It requires only Java client. For other language client, we need to go for web service.
3. It is complex to understand and develop EJB applications.

Java Bean: JavaBeans are classes that encapsulate many objects into a single object (the
bean). It is a java class that should follow following conventions:

1. Must implement Serializable.


2. It should have a public no-arg constructor.
3. All properties in java bean must be private with public getters and setter
methods.
Syntax for setter methods:
1. It should be public in nature.
2. The return-type should be void.
3. The setter method should be prefixed with set.
4. It should take some argument i.e.; it should not be no-arg method.
Syntax for getter methods:
1. It should be public in nature.
2. The return-type should not be void i.e., according to our requirement we have to
give return-type.
3. The getter method should be prefixed with get.
4. It should not take any argument.
// Java program to illustrate the structure of JavaBean class
public class TestBean {
private String name;
public void setName(String name)
{
this.name = name;
}
public String getName()
{
return name;
}
}

// Java Program of JavaBean class

package geeks;

public class Student implements java.io.Serializable

private int id;

private String name;

public Student()

public void setId(int id)

this.id = id;

public int getId()

return id;

public void setName(String name)

this.name = name;
}

public String getName()

return name;

// Java program to access JavaBean class

package geeks;

public class Test {

public static void main(String args[])

Student s = new Student(); // object is created

s.setName("GFG"); // setting value to the object

System.out.println(s.getName());

JavaBean Properties

A JavaBean property is a named feature that can be accessed by the user of the object. The
feature can be of any Java data type, containing the classes that you define.

A JavaBean property may be read, write, read-only, or write-only. JavaBean features are
accessed through two methods in the JavaBean's implementation class:

1. getPropertyName ()

For example, if the property name is firstName, the method name would be getFirstName() to
read that property. This method is called the accessor.

2. setPropertyName ()

For example, if the property name is firstName, the method name would be setFirstName() to
write that property. This method is called the mutator.
Advantages of JavaBean

The following are the advantages of JavaBean:/p>

o The JavaBean properties and methods can be exposed to another application.


o It provides an easiness to reuse the software components.

Disadvantages of JavaBean

The following are the disadvantages of JavaBean:

o JavaBeans are mutable. So, it can't take advantages of immutable objects.


o Creating the setter and getter method for each property separately may lead to the
boilerplate code.

Creating a Java Bean:


Step 1: Put this source code into a file named "SimpleBean.java"
import java.awt.*;
import java.io.Serializable;

public class SimpleBean extends Canvas


implements Serializable{

//Constructor sets inherited properties


public SimpleBean(){
setSize(60,40);
setBackground(Color.red);
}

Step 2: Compile the file:


javac SimpleBean.java
Step 3: Create a manifest file, named "manifest.tmp":
Name: SimpleBean.class
Java-Bean: True
Step 4: Create the JAR file, named "SimpleBean.jar":
jar cfm SimpleBean.jar manifest.tmp SimpleBean.class

Then verify that the content is correct by the command "jar tf SimpleBean.jar".

Step 5:

1. Start the Bean Box.

CD to c:\Program Files\BDK1.1\beanbox\.
Then type "run".
2. Load JAR into Bean Box by selecting "LoadJar..." under the File menu.

Step 6:

1. After the file selection dialog box is closed, change focus to the "ToolBox"
window. You'll see "SimpleBean" appear at the bottom of the toolbox window.
2. Select SimpleBean.jar.
3. Cursor will change to a plus. In the middle BeanBox window, you can now click to
drop in what will appear to be a colored rectangle.

Step 7:
Try changing the red box's color with the Properties windows.
Step 8:
Chose "Events" under the "Edit" menu in the middle window to see what events SimpleBean
can send. These events are inherited from java.awt.Canvas.

Steps to build application using BDK:

Step 1: Create a directory for the new bean.

Step 2: Create the Java source file(s).

Step 3: Compile the source file(s).

Step 4: Create a manifest file.

Step 5: Generate a JAR file.

Step 6: Start the BDK.

Step 7: Test the newly created Java Bean.

Types of Beans: It is divided into three:

1. Session bean
i) stateless
ii) statefull
2. Entity bean
3. Message driven bean

Session Bean:

• A session bean is an EJB 3.0 or EJB 2.1 enterprise bean component created by a client
for the duration of a single client/server session.
• A session bean performs operations for the client. Although a session bean can be
transactional, it is not recoverable if failure occurs.
• For example, in an on-line store application, you can use a session bean to implement
a Shopping Cart Bean that provides a Cart interface that the client uses to invoke such
methods as purchase Item and checkout.

Stateless Session Bean:

• A stateless session bean is a session bean with no conversational state.


• All instances of a particular stateless session bean class are identical.
• A stateless session bean and its client do not share state or identity between method
invocations.
• A stateless session bean is strictly a single invocation bean.
• It is employed for reusable business services that are not connected to any specific
client, such as generic currency calculations, mortgage rate calculations, and so on.
• Stateless session beans may contain clientindependent, read-only state across a call.

Stateful Session Bean:

• A stateful session bean is a session bean that maintains conversational state.


• Stateful session beans are useful for conversational sessions, in which it is necessary to
maintain state, such as instance variable values or transactional state, between method
invocations.
• These session beans are mapped to a single client for the life of that client.
• A stateful session bean maintains its state between method calls. Thus, there is one
instance of a stateful session bean created for each client.
• Each stateful session bean contains an identity and a one-to-one mapping with an
individual client.
• For example, a stateful session bean could implement the server side of a shopping cart
on-line application, which would have methods to return a list of objects that are
available for purchase, put items in the customer's cart, place an order, change a
customer's profile, and so on.

Entity Bean:

• An entity bean is an enterprise bean component that manages persistent data, performs
complex business logic, potentially uses several dependent Java objects, and can be
uniquely identified by a primary key.
• Entity beans are persistent because their data is stored persistently in some form of data
storage, such as a database
• Entity beans survive a server failure, failover, or a network failure.
• When an entity bean is reinstantiated, the state of the previous instance is automatically
restored.

Message Driven Bean:

• A message-driven bean (MDB) is an EJB 3.0 or EJB 2.1 enterprise bean component
that functions as an asynchronous message consumer.
• An MDB has no client-specific state but may contain message-handling state such as
an open database connection or object references to another EJB.
• A client uses an MDB to send messages to the destination for which the bean is a
message listener.
• The purpose of an MDB is to exist within a pool and to receive and process incoming
messages from a message provider.
• The container invokes a bean from the queue to handle each incoming message from
the queue.
• No object invokes an MDB directly: all invocation for an MDB comes from the
container.
• After the container invokes the MDB, it can invoke other enterprise beans or Java
objects to continue the request.

Java Database Connectivity (JDBC):

JDBC stands for Java Database Connectivity, which is a standard Java API for database-
independent connectivity between the Java programming language and a wide range of
databases.
The JDBC library includes APIs for each of the tasks mentioned below that are commonly
associated with database usage.
• Making a connection to a database.
• Creating SQL or MySQL statements.
• Executing SQL or MySQL queries in the database.
• Viewing & modifying the resulting records.
We can use JDBC API to access tabular data stored in any relational database. By the help of
JDBC API, we can save, update, delete and fetch data from the database. It is like Open
Database Connectivity (ODBC) provided by Microsoft.

Why Should We Use JDBC?

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.
JDBC Architecture:

The JDBC API supports both two-tier and three-tier processing models for database access but
in general, JDBC Architecture consists of two layers −
• JDBC API − This provides the application-to-JDBC Manager connection.
• JDBC Driver API − This supports the JDBC Manager-to-Driver Connection.
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.
Following is the architectural diagram, which shows the location of the driver manager with
respect to the JDBC drivers and the Java application −

Common JDBC Components:

The JDBC API provides the following interfaces and classes −


• DriverManager − This class manages a list of database drivers. Matches connection
requests from the java application with the proper database driver using
communication sub protocol. The first driver that recognizes a certain subprotocol
under JDBC will be used to establish a database Connection.
• Driver − This interface handles the communications with the database server. You will
interact directly with Driver objects very rarely. Instead, you use DriverManager
objects, which manages objects of this type. It also abstracts the details associated with
working with Driver objects.
• Connection − This interface with all methods for contacting a database. The
connection object represents communication context, i.e., all communication with
database is through connection object only.
• Statement − You use objects created from this interface to submit the SQL statements
to the database. Some derived interfaces accept parameters in addition to executing
stored procedures.
• ResultSet − These objects hold data retrieved from a database after you execute an
SQL query using Statement objects. It acts as an iterator to allow you to move through
its data.
• SQLException − This class handles any errors that occur in a database application.
Working of JDBC:

• The Java application calls JDBC classes and interfaces to submit SQL statements and
retrieve results.
• The JDBC API is implemented through the JDBC driver.
• The JDBC Driver is a set of classes that implement the JDBC interfaces to process
JDBC calls and return result sets to a Java application.
• The database (or data store) stores the data retrieved by the application using the
JDBC Driver.

JDBC Driver:
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. This is now discouraged because of thin
driver.

Oracle does not support the JDBC-ODBC Bridge from Java 8. Oracle recommends that you
use JDBC drivers provided by the vendor of your database instead of the JDBC-ODBC Bridge.

Advantages:
o easy to use.
o can be easily connected to any database.

Disadvantages:
o Performance degraded because JDBC method call is converted into the ODBC function
calls.
o 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:
o performance upgraded than JDBC-ODBC bridge driver.

Disadvantage:
o The Native driver needs to be installed on each client machine.
o 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:
o No client-side library is required because of application server that can perform many
tasks like auditing, load balancing, logging etc.
Disadvantages:
o Network support is required on client machine.
o Requires database-specific coding to be done in the middle tier.
o 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:
o Better performance than all other drivers.
o No software is required at client side or server side.

Disadvantage:
o Drivers depend on the Database.

Java Database Connectivity:


There are 5 steps to connect any java application with the database using JDBC. These steps
are as follows:
o Register the Driver class
o Create connection
o Create statement
o Execute queries
o Close connection

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.

Syntax of forName() method:


public static void forName(String className)throws ClassNotFoundException
Example to register the OracleDriver 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.

Syntax of getConnection() method:


1) public static Connection getConnection(String url)throws SQLException
2) public static Connection getConnection(String url,String name,String password)
throws SQLException
Example to establish connection with the Oracle 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.

Syntax of createStatement() method:


public Statement createStatement()throws SQLException
Example to create the statement object:
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.

Syntax of executeQuery() method:


public ResultSet executeQuery(String sql)throws SQLException
Example to execute query:
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.

Syntax of close() method:


public void close()throws SQLException
Example to close connection:
con.close();
Example to Connect Java Application with Oracle database
1. import java.sql.*;
2. class OracleCon{
3. public static void main(String args[]){
4. try{
5. //step1 load the driver class
6. Class.forName("oracle.jdbc.driver.OracleDriver");
7.
8. //step2 create the connection object
9. Connection con=DriverManager.getConnection(
10. "jdbc:oracle:thin:@localhost:1521:xe","system","oracle");
11.
12. //step3 create the statement object
13. Statement stmt=con.createStatement();
14.
15. //step4 execute query
16. ResultSet rs=stmt.executeQuery("select * from emp");
17. while(rs.next())
18. System.out.println(rs.getInt(1)+" "+rs.getString(2)+" "+rs.getString(3));
19.
20. //step5 close the connection object
21. con.close();
22.
23. }catch(Exception e){ System.out.println(e);}
24.
25. }
26. }
Prepared Statements:
The PreparedStatement interface is a subinterface of Statement. It is used to execute
parameterized query.

Let's see the example of parameterized query:

1. String sql="insert into emp values(?,?,?)";


Why use PreparedStatement?

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

How to get the instance of PreparedStatement?

The prepareStatement() method of Connection interface is used to return the object of


PreparedStatement.

Syntax:

public PreparedStatement prepareStatement(String query)throws SQLException{}

Example of PreparedStatement interface that inserts the record

First of all create table as given below:

create table emp(id number(10),name varchar2(50));

Now insert records in this table by the code given below:

1. import java.sql.*;
2. class InsertPrepared{
3. public static void main(String args[]){
4. try{
5. Class.forName("oracle.jdbc.driver.OracleDriver");
6.
7. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
8.
9. PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
10. stmt.setInt(1,101);//1 specifies the first parameter in the query
11. stmt.setString(2,"Ratan");
12.
13. int i=stmt.executeUpdate();
14. System.out.println(i+" records inserted");
15.
16. con.close();
17.
18. }catch(Exception e){ System.out.println(e);}
19.
20. }
21. }
Example of PreparedStatement interface that updates the record
1. PreparedStatement stmt=con.prepareStatement("update emp set name=? where id=?")
;
2. stmt.setString(1,"Sonoo");//1 specifies the first parameter in the query i.e. name
3. stmt.setInt(2,101);
4.
5. int i=stmt.executeUpdate();
6. System.out.println(i+" records updated");
Example of PreparedStatement interface that deletes the record
1. PreparedStatement stmt=con.prepareStatement("delete from emp where id=?");
2. stmt.setInt(1,101);
3.
4. int i=stmt.executeUpdate();
5. System.out.println(i+" records deleted");
Example of PreparedStatement interface that retrieve the records of a table
1. PreparedStatement stmt=con.prepareStatement("select * from emp");
2. ResultSet rs=stmt.executeQuery();
3. while(rs.next()){
4. System.out.println(rs.getInt(1)+" "+rs.getString(2));
5. }
Transaction Management in JDBC:

Transaction represents a single unit of work.

The ACID properties describe the transaction management well. ACID stands for Atomicity,
Consistency, isolation and durability.

Atomicity means either all successful or none.

Consistency ensures bringing the database from one consistent state to another consistent state.

Isolation ensures that transaction is isolated from other transaction.


Durability means once a transaction has been committed, it will remain so, even in the event
of errors, power loss etc

Advantage of Transaction Mangaement

fast performance It makes the performance fast because database is hit at the time of commit.

In JDBC, Connection interface provides methods to manage transaction.

Method Description

void setAutoCommit(boolean status) It is true bydefault means each transaction is committed bydefault.

void commit() commits the transaction.

void rollback() cancels the transaction.


Simple example of transaction management in jdbc using Statement:
1. import java.sql.*;
2. class FetchRecords{
3. public static void main(String args[])throws Exception{
4. Class.forName("oracle.jdbc.driver.OracleDriver");
5. Connection con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:xe
","system","oracle");
6. con.setAutoCommit(false);
7.
8. Statement stmt=con.createStatement();
9. stmt.executeUpdate("insert into user420 values(190,'abhi',40000)");
10. stmt.executeUpdate("insert into user420 values(191,'umesh',50000)");
11.
12. con.commit();
13. con.close();
14. }}
Stored Procedures:
 Just as a Connection object creates the Statement and PreparedStatement objects, it
also creates the CallableStatement object, which would be used to execute a call to a
database stored procedure.
 A stored procedure is a java of SQL statements to form an logical unit and performs a
particular task and they are used to encapsulate a set of operations or queries to
execute on a database server.
 Stored procedure can be compiled and executed with different parameters and they
can have any combination of input or output parameters.
 For example:
Operation on an employ database server(retired, promoted) could be coded as stored
procedures executed by code.
UNIT-5
Servlets
Servlet technology is used to create a web application (resides at server side and generates a
dynamic web page).

Servlet technology is robust and scalable because of java language. Before Servlet, CGI
(Common Gateway Interface) scripting language was common as a server-side programming
language.

o Servlet is a technology which is used to create a web application.


o Servlet is an API that provides many interfaces and classes including documentation.
o Servlet is an interface that must be implemented for creating any Servlet.
o Servlet is a class that extends the capabilities of the servers and responds to the
incoming requests. It can respond to any requests.
o Servlet is a web component that is deployed on the server to create a dynamic web page.
Java Servlets Architecture:

Step 1: Client i.e., web browser sends the request to the web server.

Step 2: Web server receives the request and sends it to the servlet container. Servlet container
is also called web container or servlet engine. It is responsible for handling the life of a
servlet.

Step 3: Servlet container understands the request’s URL and calls the particular servlet.
Actually, it creates a thread for execution of that servlet. If there are multiple requests for the
same servlet, then for each request, one thread will be created.

Step 4: Servlet processes the request object and prepares response object after interacting
with the database or performing any other operations and sends the response object back to
the web server.

Step 5: Then web server sends the response back to the client.

Advantages:
• Prime functionality of a servlet is that they are independent of server
configuration and they are pretty much compatible with any of the web servers
• Servlets are also protocol-independent supporting FTP, HTTP, SMTP, etc.
protocols to the fullest.
• Until destroyed manually, servlets can be retained in the memory helping
process several requests over time. Also, once a database connection is
established, it can facilitate process several requests for a database in the very
same database session.
• Servlets inherit Java’s property of portability and hence are compatible with
nearly any web server.
• Servlets are first converted into byte codes and then executed, which helps in
increasing the processing time.
Disadvantages:
• Designing a servlet can be pretty laborious.
• Exceptions need to be handled while designing a servlet since they are not
thread-safe.
• Developers may need additional skills to program a servlet.

Life-Cycle of Servlets: 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

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. Syntax of the init
method is given below:

public void init(ServletConfig config) throws ServletException


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. The syntax of the service method of the Servlet interface is given below:
public void service(ServletRequest request, ServletResponse response)
throws ServletException, IOException
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. The syntax of the destroy method of the Servlet interface is given below:

public void destroy()

Properties of Servlets are as follows:


• Servlets work on the server-side.
• Servlets are capable of handling complex requests obtained from the webserver.

Working of Servlets:

1. The clients send the request to the web server.


2. The web server receives the request.
3. The web server passes the request to the corresponding servlet.
4. The servlet processes the request and generates the response in the form of output.
5. The servlet sends the response back to the web server.
6. The web server sends the response back to the client and the client browser displays it
on the screen.

Characteristics of Servlet:

• Servlet operates on input data that is encapsulated in a request object.


• Servlet responds to a query with data encapsulated in a response object.
• Servlet can call EJB components to perform business logic functions.
• Servlet can call JSPs to perform page layout functions.
• Servlet can call other servlets.

Servlet Interface:

Servlet interface provides common behaviour to 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.

Methods of Servlet interface

There are 5 methods in Servlet interface. The init, service and destroy are the life cycle methods
of servlet. These are invoked by the web container.
Method Description

public void init(ServletConfig config) initializes the servlet. It is the life cycle method of
servlet and invoked by the web container only once.

public void service(ServletRequest provides response for the incoming request. It is


request,ServletResponse response) invoked at each request by the web container.

public void destroy() is invoked only once and indicates that servlet is being
destroyed.

public ServletConfig getServletConfig() returns the object of ServletConfig.

public String getServletInfo() returns information about servlet such as writer,


copyright, version etc.

Servlet Example by implementing Servlet interface:


1. import java.io.*;
2. import javax.servlet.*;
3.
4. public class First implements Servlet{
5. ServletConfig config=null;
6.
7. public void init(ServletConfig config){
8. this.config=config;
9. System.out.println("servlet is initialized");
10. }
11.
12. public void service(ServletRequest req,ServletResponse res)
13. throws IOException,ServletException{
14.
15. res.setContentType("text/html");
16.
17. PrintWriter out=res.getWriter();
18. out.print("<html><body>");
19. out.print("<b>hello simple servlet</b>");
20. out.print("</body></html>");
21.
22. }
23. public void destroy(){System.out.println("servlet is destroyed");}
24. public ServletConfig getServletConfig(){return config;}
25. public String getServletInfo(){return "copyright 2007-1010";}
26.
27. }
Handling in HTTP get and post request in servlet with example:
 Now we know that client can make the request to the web server using HTTP protocol.
 There is HtttpServlet class in which two important method doGet(), and doPost() used to
handle http request.
 doGet(): When we submitting his request using doGet method then the url string displays
the request submitting by user.
 doPost(): When we submitting his request using doPost method then the url string does
not show the request submitting by user.

Handling GET requests

Handling GET requests involves overriding the doGet method. The following example shows
the BookDetailServlet doing this. The methods discussed in the Requests and
Responses section are shown in bold.

public class BookDetailServlet extends HttpServlet {

public void doGet (HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content-type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title>Book Description</title></head>" +
...);

//Get the identifier of the book to display


String bookId = request.getParameter("bookId");
if (bookId != null) {
// and the information about the book and print it
...
}
out.println("</body></html>");
out.close();
}
...
}

The servlet extends the HttpServlet class and overrides the doGet method.

Within the doGet method, the getParameter method gets the servlet's expected argument.

To respond to the client, the example doGet method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing the writer,
the example sets the content-type header. At the end of the doGet method, after the response
has been sent, the Writer is closed.

Handling POST Requests

Handling POST requests involves overriding the doPost method. The following example
shows the ReceiptServlet doing this. Again, the methods discussed in the Requests and
Responses section are shown in bold.

public class ReceiptServlet extends HttpServlet {

public void doPost(HttpServletRequest request,


HttpServletResponse response)
throws ServletException, IOException
{
...
// set content type header before accessing the Writer
response.setContentType("text/html");
PrintWriter out = response.getWriter();

// then write the response


out.println("<html>" +
"<head><title> Receipt </title>" +
...);

out.println("<h3>Thank you for purchasing your books from us " +


request.getParameter("cardname") +
...);
out.close();
}
...
}

The servlet extends the HttpServlet class and overrides the doPost method.

Within the doPost method, the getParameter method gets the servlet's expected argument.

To respond to the client, the example doPost method uses a Writer from
the HttpServletResponse object to return text data to the client. Before accessing the writer
the example sets the content-type header. At the end of the doPost method, after the response
has been set, the Writer is closed.

Session Tracking:

• Session simply means a particular interval of time.


• Session Tracking is a way to maintain state (data) of a 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:

Session Tracking Techniques

There are four techniques used in Session tracking:

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

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.

Types of Cookies

There are 2 types of cookies in servlets.

1. Non-persistent cookie
2. Persistent cookie

Non-persistent cookie

It is valid for single session only. It is removed each time when user closes the browser.

Persistent cookie

It is valid for multiple session. It is not removed each time when user closes the browser. It is
removed only if user logout or signout.

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.
Session Tracking with HTTPSession:

In such case, 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.

How to get the HttpSession object?

The HttpServletRequest interface provides two methods to get the object of HttpSession:

1. public HttpSession getSession():Returns the current session associated with this


request, or if the request does not have a session, creates one.
2. public HttpSession getSession(boolean create):Returns the current HttpSession
associated with this request or, if there is no current session and create is true, returns a
new session.

Commonly used methods of HttpSession interface


1. public String getId():Returns a string containing the unique identifier value.
2. public long getCreationTime():Returns the time when this session was created,
measured in milliseconds since midnight January 1, 1970 GMT.
3. public long getLastAccessedTime():Returns the last time the client sent a request
associated with this session, as the number of milliseconds since midnight January 1,
1970 GMT.
4. public void invalidate():Invalidates this session then unbinds any objects bound to it.
Difference Between Session and Cookies :

Cookie Session

Cookies are client-side files on a


local computer that hold user
information. Sessions are server-side files that contain user data.

Cookies end on the lifetime set by When the user quits the browser or logs out of the
the user. programmed, the session is over.

It can only store a certain amount


of info. It can hold an indefinite quantity of data.

We can keep as much data as we like within a


session, however there is a maximum memory
The browser’s cookies have a restriction of 128 MB that a script may consume at
maximum capacity of 4 KB. one time.

Because cookies are kept on the


local computer, we don’t need to To begin the session, we must use the session start()
run a function to start them. method.

Servlet Login and Logout Example using Cookies

In this application, we have created following files.

1. index.html
2. link.html
3. login.html
4. LoginServlet.java
5. LogoutServlet.java
6. ProfileServlet.java
7. web.xml

File: index.html

1. <!DOCTYPE html>
2. <html>
3. <head>
4. <meta charset="ISO-8859-1">
5. <title>Servlet Login Example</title>
6. </head>
7. <body>
8.
9. <h1>Welcome to Login App by Cookie</h1>
10. <a href="login.html">Login</a>|
11. <a href="LogoutServlet">Logout</a>|
12. <a href="ProfileServlet">Profile</a>
13.
14. </body>
15. </html>

File: link.html

1. <a href="login.html">Login</a> |
2. <a href="LogoutServlet">Logout</a> |
3. <a href="ProfileServlet">Profile</a>
4. <hr>

File: login.html

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


2. Name:<input type="text" name="name"><br>
3. Password:<input type="password" name="password"><br>
4. <input type="submit" value="login">
5. </form>

File: LoginServlet.java

1. package com.javatpoint;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.Cookie;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. public class LoginServlet extends HttpServlet {
11. protected void doPost(HttpServletRequest request, HttpServletResponse response)

12. throws ServletException, IOException {


13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15.
16. request.getRequestDispatcher("link.html").include(request, response);
17.
18. String name=request.getParameter("name");
19. String password=request.getParameter("password");
20.
21. if(password.equals("admin123")){
22. out.print("You are successfully logged in!");
23. out.print("<br>Welcome, "+name);
24.
25. Cookie ck=new Cookie("name",name);
26. response.addCookie(ck);
27. }else{
28. out.print("sorry, username or password error!");
29. request.getRequestDispatcher("login.html").include(request, response);
30. }
31.
32. out.close();
33. }
34.
35. }

File: LogoutServlet.java

1. package com.javatpoint;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.Cookie;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. public class LogoutServlet extends HttpServlet {
11. protected void doGet(HttpServletRequest request, HttpServletResponse response)

12. throws ServletException, IOException {


13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15.
16.
17. request.getRequestDispatcher("link.html").include(request, response);
18.
19. Cookie ck=new Cookie("name","");
20. ck.setMaxAge(0);
21. response.addCookie(ck);
22.
23. out.print("you are successfully logged out!");
24. }
25. }

File: ProfileServlet.java

1. package com.javatpoint;
2.
3. import java.io.IOException;
4. import java.io.PrintWriter;
5. import javax.servlet.ServletException;
6. import javax.servlet.http.Cookie;
7. import javax.servlet.http.HttpServlet;
8. import javax.servlet.http.HttpServletRequest;
9. import javax.servlet.http.HttpServletResponse;
10. public class ProfileServlet extends HttpServlet {
11. protected void doGet(HttpServletRequest request, HttpServletResponse response)

12. throws ServletException, IOException {


13. response.setContentType("text/html");
14. PrintWriter out=response.getWriter();
15.
16. request.getRequestDispatcher("link.html").include(request, response);
17.
18. Cookie ck[]=request.getCookies();
19. if(ck!=null){
20. String name=ck[0].getValue();
21. if(!name.equals("")||name!=null){
22. out.print("<b>Welcome to Profile</b>");
23. out.print("<br>Welcome, "+name);
24. }
25. }else{
26. out.print("Please login first");
27. request.getRequestDispatcher("login.html").include(request, response);
28. }
29. out.close();
30. }
31. }

File: web.xml

1. <?xml version="1.0" encoding="UTF-8"?>


2. <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
3. xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/
xml/ns/javaee
4. http://java.sun.com/xml/ns/javaee/web-
app_2_5.xsd" id="WebApp_ID" version="2.5">
5.
6. <servlet>
7. <description></description>
8. <display-name>LoginServlet</display-name>
9. <servlet-name>LoginServlet</servlet-name>
10. <servlet-class>com.javatpoint.LoginServlet</servlet-class>
11. </servlet>
12. <servlet-mapping>
13. <servlet-name>LoginServlet</servlet-name>
14. <url-pattern>/LoginServlet</url-pattern>
15. </servlet-mapping>
16. <servlet>
17. <description></description>
18. <display-name>ProfileServlet</display-name>
19. <servlet-name>ProfileServlet</servlet-name>
20. <servlet-class>com.javatpoint.ProfileServlet</servlet-class>
21. </servlet>
22. <servlet-mapping>
23. <servlet-name>ProfileServlet</servlet-name>
24. <url-pattern>/ProfileServlet</url-pattern>
25. </servlet-mapping>
26. <servlet>
27. <description></description>
28. <display-name>LogoutServlet</display-name>
29. <servlet-name>LogoutServlet</servlet-name>
30. <servlet-class>com.javatpoint.LogoutServlet</servlet-class>
31. </servlet>
32. <servlet-mapping>
33. <servlet-name>LogoutServlet</servlet-name>
34. <url-pattern>/LogoutServlet</url-pattern>
35. </servlet-mapping>
36. </web-app>
Output
JAVA SERVER PAGES (JSP)
• It is a server side technology.
• It is used for creating web application.
• It is used to create dynamic web content.
• In this JSP tags are used to insert JAVA code into HTML pages.
• It is an advanced version of Servlet Technology.
• It is a Web based technology helps us to create dynamic and platform
independent web pages.
• In this, Java code can be inserted in HTML/ XML pages or both.
• JSP is first converted into servlet by JSP container before processing the client’s
request.
JSP pages are more advantageous than Servlet:
• They are easy to maintain.
• No recompilation or redeployment is required.
• JSP has access to entire API of JAVA.
• JSP are extended version of Servlet.
Features of JSP
• Coding in JSP is easy :- As it is just adding JAVA code to HTML/XML.
• Reduction in the length of Code :- In JSP we use action tags, custom tags etc.
• Connection to Database is easier :-It is easier to connect website to database
and allows to read or write data easily to the database.
• Make Interactive websites :- In this we can create dynamic web pages which
helps user to interact in real time environment.
• Portable, Powerful, flexible and easy to maintain :- as these are browser and
server independent.
• No Redeployment and No Re-Compilation :- It is dynamic, secure and
platform independent so no need to re-compilation.
• Extension to Servlet :- as it has all features of servlets, implicit objects and
custom tags.
JSP syntax:
• Declaration Tag: -It is used to declare variables.
Syntax: -
<%! Dec var %>
Example: -
<%! int var=10; %>
• Java Scriplets: - It allows us to add any number of JAVA code, variables and
expressions.
Syntax: -
<% java code %>
• JSP Expression: - It evaluates and convert the expression to a string.
Syntax: -
<%= expression %>
Example: -
<% num1 = num1+num2 %>
• JAVA Comments: - It contains the text that is added for information which has to
be ignored.
Syntax: -
<% -- JSP Comments %>
Advantages of using JSP
• It does not require advanced knowledge of JAVA
• It is capable of handling exceptions
• Easy to use and learn
• It can tags which are easy to use and understand
• Implicit objects are there which reduces the length of code
• It is suitable for both JAVA and non-JAVA programmer
Disadvantages of using JSP
• Difficult to debug for errors.
• First time access leads to wastage of time
• Its output is HTML which lacks features.
Life cycle of JSP:

Following steps are involved in the JSP life cycle:


• Translation of JSP page to Servlet
• Compilation of JSP page(Compilation of JSP into test.java)
• Classloading (test.java to test.class)
• Instantiation(Object of the generated Servlet is created)
• Initialization(jspInit() method is invoked by the container)
• Request processing(_jspService()is invoked by the container)
• JSP Cleanup (jspDestroy() method is invoked by the container)
Translation of JSP page to Servlet :
This is the first step of the JSP life cycle. This translation phase deals with the
Syntactic correctness of JSP. Here test.jsp file is translated to test.java.
Compilation of JSP page:
Here the generated java servlet file (test.java) is compiled to a class file (test.class).
Classloading:
Servlet class which has been loaded from the JSP source is now loaded into the
container.
Instantiation:
Here an instance of the class is generated. The container manages one or more
instances by providing responses to requests.
Initialization:
jspInit() method is called only once during the life cycle immediately after the
generation of Servlet instance from JSP.
Request processing:
_jspService() method is used to serve the raised requests by JSP. It takes request and
response objects as parameters. This method cannot be overridden.
JSP Cleanup:
In order to remove the JSP from the use by the container or to destroy the method for
servlets jspDestroy()method is used. This method is called once, if you need to perform any
cleanup task like closing open files, releasing database connections jspDestroy() can be
overridden.
Creating a simple JSP Page:

To create the first JSP page, write some HTML code as given below, and save it by .jsp
extension. We have saved this file as index.jsp. Put it in a folder and paste the folder in the
web-apps directory in apache tomcat to run the JSP page.

index.jsp

Let's see the simple example of JSP where we are using the scriptlet tag to put Java code in the
JSP page. We will learn scriptlet tag later.

1. <html>
2. <body>
3. <% out.print(2*5); %>
4. </body>
5. </html>

It will print 10 on the browser.

JSP Architecture:

• JSP architecture gives a high-level view of the working of JSP.


• JSP architecture is a 3-tier architecture. It has a Client, Web Server, and Database.
• The client is the web browser or application on the user side. Web Server uses a JSP
Engine i.e.; a container that processes JSP. For example, Apache Tomcat has a built-
in JSP Engine.
• JSP Engine intercepts the request for JSP and provides the runtime environment for
the understanding and processing of JSP files.
• It reads, parses, build Java Servlet, Compiles and Executes Java code, and returns the
HTML page to the client.
• The webserver has access to the Database.
• The following diagram shows the architecture of JSP.

JSP Processing:
Step 1: The client navigates to a file ending with the .jsp extension and the browser
initiates an HTTP request to the webserver. For example, the user enters the login details
and submits the button. The browser requests a status.jsp page from the webserver.
Step 2: If the compiled version of JSP exists in the web server, it returns the file.
Otherwise, the request is forwarded to the JSP Engine. This is done by recognizing the
URL ending with .jsp extension.
Step 3: The JSP Engine loads the JSP file and translates the JSP to Servlet(Java code). This
is done by converting all the template text into println() statements and JSP elements to
Java code. This process is called translation.
Step 4: The JSP engine compiles the Servlet to an executable .class file. It is forwarded to
the Servlet engine. This process is called compilation or request processing phase.
Step 5: The .class file is executed by the Servlet engine which is a part of the Web Server.
The output is an HTML file. The Servlet engine passes the output as an HTTP response to
the webserver.
Step 6: The web server forwards the HTML file to the client’s browser.

JSP Scripting elements:

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

o scriptlet tag
o expression tag
o 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
1. <html>
2. <body>
3. <% out.print("welcome to jsp"); %>
4. </body>
5. </html>
JSP expression tag

The code placed within JSP expression tag is written to the output stream of the response. So
you need not write out.print() to write data. It is mainly used to print the values of variable or
method.

Syntax of JSP expression tag


<%= statement %>
Example of JSP expression tag that prints current time
index.jsp
1. <html>
2. <body>
3. Current Time: <%= java.util.Calendar.getInstance().getTime() %>
4. </body>
5. </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.

Syntax of JSP declaration tag

<%! field or method declaration %>

Example of JSP declaration tag that declares field


index.jsp
1. <html>
2. <body>
3. <%! int data=50; %>
4. <%= "Value of the variable is:"+data %>
5. </body>
6. </html>
Example of JSP declaration tag that declares method
index.jsp
1. <html>
2. <body>
3. <%!
4. int cube(int n){
5. return n*n*n*;
6. }
7. %>
8. <%= "Cube of 3 is:"+cube(3) %>
9. </body>
10. </html>

JSP Implicit Objects:

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
1) JSP out implicit object

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();
Example of out implicit object
index.jsp
1. <html>
2. <body>
3. <% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
4. </body>
5. </html>
Output

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.

Example of JSP request implicit object


index.html
1. <form action="welcome.jsp">
2. <input type="text" name="uname">
3. <input type="submit" value="go"><br/>
4. </form>
welcome.jsp
1. <%
2. String name=request.getParameter("uname");
3. out.print("welcome "+name);
4. %>
Output

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.

Let's see the example of response implicit object where we are redirecting the response to the
Google.

Example of response implicit object


index.html

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

1. <%
2. response.sendRedirect("http://www.google.com");
3. %>
Output
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.

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

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.

Example of application 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. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>sonoojaiswal</servlet-name>
10. <url-pattern>/welcome</url-pattern>
11. </servlet-mapping>
12.
13. <context-param>
14. <param-name>dname</param-name>
15. <param-value>sun.jdbc.odbc.JdbcOdbcDriver</param-value>
16. </context-param>
17.
18. </web-app>
welcome.jsp

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

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
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. session.setAttribute("user",name);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)session.getAttribute("user");
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
Output

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:

o page
o request
o session
o application

In JSP, page scope is the default scope.


Example of pageContext implicit object
index.html
1. <html>
2. <body>
3. <form action="welcome.jsp">
4. <input type="text" name="uname">
5. <input type="submit" value="go"><br/>
6. </form>
7. </body>
8. </html>
welcome.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=request.getParameter("uname");
6. out.print("Welcome "+name);
7.
8. pageContext.setAttribute("user",name,PageContext.SESSION_SCOPE);
9.
10. <a href="second.jsp">second jsp page</a>
11.
12. %>
13. </body>
14. </html>
second.jsp
1. <html>
2. <body>
3. <%
4.
5. String name=(String)pageContext.getAttribute("user",PageContext.SESSION_SCOP
E);
6. out.print("Hello "+name);
7.
8. %>
9. </body>
10. </html>
Output

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


In JSP, exception is an implicit object of type java.lang.Throwable class. This object can be used to print the
exception. But it can only be used in error pages.It is better to learn it after page directive. Let's see a simple
example:

Example of exception implicit object:


error.jsp
1. <%@ page isErrorPage="true" %>
2. <html>
3. <body>
4.
5. Sorry following exception occured:<%= exception %>
6.
7. </body>
8. </html>
JSP directives

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:

o page directive
o include directive
o 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
o import
o contentType
o extends
o info
o buffer
o language
o isELIgnored
o isThreadSafe
o autoFlush
o session
o pageEncoding
o errorPage
o isErrorPage

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

1. <html>
2. <body>
3.
4. <%@ include file="header.html" %>
5.
6. Today is: <%= java.util.Calendar.getInstance().getTime() %>
7.
8. </body>
9. </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
1. <html>
2. <body>
3.
4. <%@ taglib uri="http://www.javatpoint.com/tags" prefix="mytag" %>
5.
6. <mytag:currentDate/>
7.
8. </body>
9. </html>
JSP Action Tags

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 Action Tags Description

jsp:forward forwards the request and response to another resource.

jsp:include includes another resource.

jsp:useBean creates or locates bean object.

jsp:setProperty sets the value of property in bean object.

jsp:getProperty prints the value of property of the bean.

jsp:plugin embeds another components such as applet.

jsp:param sets the parameter value. It is used in forward and include mostly.

jsp:fallback can be used to print the message if plugin is working. It is used in jsp:plugin.

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>
jsp:include action tag

The jsp:include action tag 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.

Difference between jsp include directive and include action


JSP include directive JSP include action

includes resource at translation time. includes resource at request time.

better for static pages. better for dynamic pages.

includes the original content in the generated servlet. calls the include method.

Syntax of jsp:include action tag without parameter


1. <jsp:include page="relativeURL | <%= expression %>" />
Syntax of jsp:include action tag with parameter
1. <jsp:include page="relativeURL | <%= expression %>">
2. <jsp:param name="parametername" value="parametervalue | <%=expression%>" />
3. </jsp:include>
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

1. <jsp:useBean id= "instanceName" scope= "page | request | session | application"


2. class= "packageName.className" type= "packageName.className"
3. beanName="packageName.className | <%= expression >" >
4. </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.
o page: specifies that you can use this bean within the JSP page. The default scope
is page.
o request: specifies that you can use this bean from any JSP page that processes
the same request. It has wider scope than page.
o 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.
o 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.

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

1. <jsp:setProperty name="instanceOfBean" property= "*" |


2. property="propertyName" param="parameterName" |
3. property="propertyName" value="{ string | <%= expression %>}"
4. />
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" />
Custom Tags in JSP

Custom tags are user-defined tags. They eliminates the possibility of scriptlet tag and separates
the business logic from the JSP page.

The same business logic can be used many times by the use of custom tag.

Advantages of Custom Tags

The key advantages of Custom tags are as follows:

1. Eliminates the need of scriptlet tag The custom tags eliminates the need of scriptlet
tag which is considered bad programming approach in JSP.
2. Separation of business logic from JSP The custom tags separate the the business logic
from the JSP page so that it may be easy to maintain.
3. Re-usability The custom tags makes the possibility to reuse the same business logic
again and again.

Syntax to use custom tag

There are two ways to use the custom tag. They are given below:

• <prefix:tagname attr1=value1....attrn=valuen />


• <prefix:tagname attr1=value1....attrn=valuen >
body code
</prefix:tagname>

You might also like