0% found this document useful (0 votes)
38 views82 pages

20cs4104 Ip Unit III

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
38 views82 pages

20cs4104 Ip Unit III

Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 82

20CS4104

INTERNET PROGRAMMING
UNIT III SERVER SIDE PROGRAMMING
Servlets: Java Servlet Architecture- Servlet Life Cycle- Form GET and POST
actions- Session Handling- Understanding Cookies Installing and Configuring
Apache Tomcat Web Server
DATABASE CONNECTIVITY: JDBC perspectives, JDBC program example
JSP: Understanding Java Server Pages Creating HTML forms by embedding JSP
code.
COURSE OBJECTIVES
1. To learn Server-side programs using Servlets and JSP with
Database connection.

COURSE OUTCOMES (CO)


Students will be able to construct a basic website using HTML and
CO 1
Cascading Style Sheets.
Students will be able to build dynamic web page with validation using Java
CO 2
Script objects and by applying different event handling mechanisms.
To learn Server-side programs using Servlets and JSP with Database
CO 3
connection.
To implement server-side programming and build web applications using
CO 4
PHP.
To understand the concept of server-side framework Node JS and Angular
CO 5
JS
Course Delivery Plan
UNIT III SERVER SIDE PROGRAMMING

Session # Topic

1 Installing and Configuring Apache Tomcat Web Server

2 Java Servlet Architecture


3 Servlet Life Cycle
4 Form GET and POST actions
5 Session Handling- Understanding Cookies
6 DATABASE CONNECTIVITY: JDBC perspectives
7 JDBC program example
8 JSP: Understanding Java Server Pages
9 Creating HTML forms by embedding JSP code.
Installing and Configuring Apache
Tomcat Web Server
• Install JDK
• Download from http://tomcat.apache.org/
• Run the installation file
• Remember port
• Check the installation by typing
http://localhost:8080/ in the browser
• Move web pages to D:\Program Files\Apache
Software Foundation\Tomcat 7.0\webapps\
folder
Servlets
• Java Servlet Architecture
• Servlet Life Cycle
• Form GET and POST actions
• Session Handling
• Understanding Cookies
Servlets
• Servlet is a Java Class File or a Java Program that
runs on a Web server
• Servlets are used for creating dynamic web applications
by extending the capability of a server
• The javax.servlet and javax.servlet.http are packages
which provides interfaces and classes for creating
servlets
• All the servlets must implement the Servlet interface,
which defines life-cycle methods
Java Servlet Architecture
Servlet Life Cycle
• Servlet lifecycle describes how the servlet container manages the
servlet object
• init() :- Initialization of servlet instance using the init() method.

• service() :- Servicing a client request using the service() method.

• destroy() :- Destroying a servlet instance using the destroy()


method.

8
Servlet Life Cycle
Servlet Syntax
public class ServletDemo extends HttpServlet
{
public void init()
{
/* used to initialize resources */
}
public void service()
{
/* used to fulfill client request */
}
public void destroy()
{
/* Release the resources */
}
}
Servlet Example1
public class HelloWorld extends GenericServlet
{
public void service(ServletRequest request, ServletResponse response )
throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1> Hello World </h1>");
out.close();
}
}
Servlet Example2
public class HelloWorld extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response )
throws IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1> Hello World </h1>");
out.close();
}
}
Servlet Container
• It is known as servlet engine which manages Java
Servlet components on top of a web server to the
request send by the client.
• Servlet Container provides the following services:
– It manages the servlet life cycle
– The resources like servlets, JSP pages and HTML
files are managed by servlet container
– It appends session ID to the URL path to maintain
session.
– Provides security service
– It loads a servlet class from network services, file
systems like remote file system and local file system
How web container handles the servlet
request?
1. Maps the request with the servlet in the web.xml file
2. Creates request and response objects for this request
3. Calls the service method on the thread
4. The public service method internally calls the protected
service method
5. The protected service method calls the doGet method
depending on the type of request.
6. The doGet method generates the response and it is passed
to the client.
7. After sending the response, the web container deletes the
request and response objects. The thread is contained in the
thread pool or deleted depends on the server
implementation.
How Servlet Works?
How Servlet Works?
1. When the web server (e.g. Apache Tomcat) starts up,
the servlet container deploy and loads all the servlets
2. Once the servlet is loaded, the servlet container creates
the instance of servlet class.
– For each instantiated servlet, its init() method is
invoked.
3. Client (user browser) sends an Http request to web
server on a certain port.
– Each time the web server receives a request, the
servlet container creates HttpServletRequest and
HttpServletResponse objects.
4. When servlet container shuts down, it unloads all the
servlets and calls destroy() method for each initialized
servlets.
Hierarchy of Packages

java.lang.Object

|_extended by javax.servlet.GenericServlet |

_extended by javax.servlet.http.HttpServlet
Interfaces in javax.servlet Classes in javax.servlet
package package

• Servlet • GenericServlet
• ServletRequest
• ServletInputStream
• ServletResponse
• ServletConfig • ServletOutputStream
• ServletContext
• ServletException
• SingleThreadModel
• RequestDispatcher • ServletRequestWrapper
• ServletRequestListener • ServletRequestEvent
• ServletRequestAttributeListener
• ServletContextListener • ServletResponseWrapper
• ServletContextAttributeListener • ServletContextEvent
• Filter
• ServletRequestAttributeEvent
• FilterConfig
• FilterChain • ServletContextAttributeEvent

• UnavailableException
Interfaces in javax.servlet.http Classes in javax.servlet.http
package package
• HttpServlet
• HttpSession
• Cookie
• HttpServletRequest • HttpSessionEvent
• HttpSessionBindingEvent
• HttpServletResponse
• HttpServletRequestWrapper
• HttpSessionAttributeListener • HttpServletResponseWrapper
• HttpSessionListener • HttpUtils

• HttpSessionBindingListener
• HttpSessionActivationListener
• HttpSessionContext
Form GET Actions
<!DOCTYPE html>
<html>
<head>
<title>doGet Example</title>
</head>
<body>
<form name="myform" action=“MyServlet" method=“get">
Enter Name:<input type="text" name="uname"><br><br>
Enter Age:<input type=“text" name=“uage"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Form GET Actions
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String age=request.getParameter(“uage");
out.println("<h3>Welcome to doGet Method</h3> ");
out.println("<br>Name:"+name);
out.println("<br>Age:"+age);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
21
Form POST Actions
<!DOCTYPE html>
<html>
<head>
<title>doPost Example</title>
</head>
<body>
<form name="myform" action=“MyServlet" method=“post">
Enter Name:<input type="text" name="uname"><br><br>
Enter Password:<input type="password" name="pwd"><br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
Form POST Actions
import javax.servlet.*;
import javax.servlet.http.*;
public class MySerlvet extends HttpServlet
{
public void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name=request.getParameter("uname");
String pwd=request.getParameter("pwd");
out.println("<h3>Welcome to doPost Method</h3> ");
out.println("<br>Name:"+name);
out.println("<br>Password:"+pwd);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
}
23
Session Handling
• Session tracking is a mechanism that servlets use to maintain state
about a series of requests from the same user (that is, requests
originating from the same browser) across some period of time.
• Sessions are shared among the servlets accessed by a client.

• Techniques

– Cookies

– Hidden Form Field

– URL Rewriting

– HttpSession
1. Session Handling using Cookies

• Cookies are small pieces of information that are sent in


response from the web server to the client.
• 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.
• Types of Cookie
1. Non-persistent cookie - valid for single session
2. Persistent cookie - valid for multiple session
How cookies works?
• By default, each request is considered as a new request.
• Servlet adds cookie in response
• Then cookie is stored in the cache of the browser
• If request is sent by the same user, cookie is added with
request by default. Thus, server recognizes the user as
the old user.
Methods of Cookie Class
Method Description

Sets the maximum age of the cookie in


public void setMaxAge(int expiry)
seconds.

Returns the name of the cookie. The name


public String getName()
cannot be changed after creation.

public String getValue() Returns the value of the cookie.

public void setName(String name) changes the name of the cookie.

public void setValue(String value) changes the value of the cookie.

Other Methods
method of HttpServletResponse interface is
public void addCookie(Cookie ck)
used to add cookie in response object
method of HttpServletRequest interface is
public Cookie[] getCookies()
used to return all the cookies from the browser
Example using cookies
login.html
<html>
<body>
<form method="post" action=“Validate1">
Name:<input type="text" name="user" /><br/>
Password:<input type=“password" name="pass" ><br/>
<input type="submit" value="submit">
</form>
</body>
</html>

28
login.htmlValidate1
//Session Handling using Cookies
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate1 extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType(“text/html”);
String name = request.getParameter(“user”);
String pass = request.getParameter(“pass”);
if(name.equals(“abc”)&&pass.equals(“1234”))
{
Cookie ck = new Cookie(“username”,name);
response.addCookie(ck);
response.sendRedirect(“Welcome”);
}
}
}`
29
login.html Validate1Welcome
//Session Handling using Cookies
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("text/html");
PrintWriter out = res.getWriter();

Cookie[] cks = request.getCookies();


out.println("Welcome "+cks[1].getValue());
}
}

30
2. URL Rewriting for Session Management

• If the client has disabled cookies in the browser then session


management using cookie wont work.
• In that case URL Rewriting can be used as a backup

31
login.html Validate
//Session Handlig using URL Rewriting
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
String name = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
response.sendRedirect(“Welcome?uname="+name);
}
}
}

32
login.html ValidateWelcome
//Session Handlig using URL Rewriting
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("uname");
out.println("Welcome "+user);
}
}

33
3. Hidden Form Fields for Session Management

index.html

<html>
<body>
<form method="post" action="Validate">
User: <input type="text" name="user" /><br/>
Password: <input type=“password" name="pass" ><br/>
<input type="submit" value=“Submit">
</form>
</body>
</html>

34
login.htmlValidate
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Validate extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
PrintWriter out=response.getWriter();
String uname = request.getParameter("user");
String pass = request.getParameter("pass");
if(pass.equals("1234"))
{
out.println(“<form action=‘Welcome’ method=‘post’>”);
out.println(“<input type=‘hidden’ name=‘uname’ value=“+uname+”>”);
out.println(“<input type=‘submit’ value=‘Go’>”);
}
}
}

35
ValidateWelcome
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Welcome extends HttpServlet
{
protected void doGet(HttpServletRequest request,HttpServletResponse response)

throws ServletException, IOException


{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String user=request.getParameter(“uname”);
out.println("Hello "+user);
}
}

36
4. HttpSession for Session Management

• HttpSession object is used to store entire session with a


specific client
• On client's first request, the Web Container generates a
unique session ID and gives it back to the client with
response. This is a temporary session created by web
container.
• The client sends back the session ID with each request.
Making it easier for the web container to identify where the
request is coming from.
• The Web Container uses this ID, finds the matching session
with the ID and associates the session with the request.

37
4. HttpSession for Session Management

38
Methods of HttpSession
Methods Description

returns the time when the session was


long getCreationTime() created, measured in milliseconds since
midnight January 1, 1970 GMT.

returns a string containing the unique


String getId()
identifier assigned to the session.

returns the last time the client sent a request


long getLastAccessedTime()
associated with the session

returns the maximum time interval, in


int getMaxInactiveInterval()
seconds.

void invalidate() destroy the session

boolean isNew() returns true if the session is new else false

Specifies the time, in seconds,after servlet


void setMaxInactiveInterval(int interval)
container will invalidate the session. 39
//Session Handling using HttpSession
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class FirstServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("uname");
out.print("Welcome "+n);
HttpSession session=request.getSession();
session.setAttribute("uname",n);
out.print("<a href=‘SecondServlet'>visit</a>");
out.close();
}
catch(Exception e) { System.out.println(e); }
}
}
40
//Session Handling using HttpSession
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SecondServlet extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response)
{
try
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
HttpSession session=request.getSession(false);
String n=(String)session.getAttribute("uname");
out.print("Hello "+n);
out.close();
}
catch(Exception e)
{
System.out.println(e);
}
}
} 41
DATABASE CONNECTIVITY
• JDBC perspectives
• JDBC program example
JDBC
• Java Database Connectivity (JDBC) is
an application programming interface (API)
for the programming language Java, which
defines how a client may access
a database

• It is Java based data access technology


and used for Java database connectivity

• JDBC allows multiple implementations to


exist and be used by the same application

• The JVM uses a JDBC driver to translate


generalized JDBC calls into vendor
specific database calls
JDBC Architecture
JDBC Architecture

• JDBC API
– JDBC API provides universal data access from the
Java programming language
– Using the JDBC API, you can access virtually any
data source, from relational databases to
spreadsheets and flat files
– The JDBC API is comprised of two packages:
• java.sql
• javax.sql
JDBC Architecture

• JDBC Driver Manager


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

• JDBC Driver
– A JDBC driver is a software component enabling
a Java application to interact with a database
– JDBC drivers are analogous to ODBC drivers, ADO.NET
data providers, and OLE DB providers
– To connect with individual databases, JDBC (the Java
Database Connectivity API) requires drivers for each
database
– The JDBC driver gives out the connection to the
database and implements the protocol for transferring
the query and result between client and database.
Drivers Types
• Type 1 - JDBC-ODBC Bridge
• Type 2 - Native API Driver
• Type 3 – Network-Protocol Driver
• Type 4 – Database-Protocol Driver

48
Drivers Types
• Type 1 that calls native code of the locally
available ODBC driver.
• Type 2 that calls database vendor native library
on a client side. This code then talks to database
over the network.
• Type 3, the pure-java driver that talks with the
server-side middleware that then talks to the
database.
• Type 4, the pure-java driver that uses database
native protocol.

49
Drivers Types
• Type 1 - JDBC-ODBC Bridge
• Uses a bridging technology to access a database. JDBC-ODBC
bridge is an example. It provides a gateway to the ODBC.
• Type 2 - Native API Driver
• Native API drivers.
• Driver contains Java code that calls native C/C++ methods
provided by the database vendors.
• Type 3 – Network-Protocol Driver
• Generic network API that is then translated into database-specific
access at the server level.
• The JDBC driver on the client uses sockets to call a middleware
application on the server that translates the client requests into an
API specific to the desired driver. Extremely flexible.
• Type 4 – Database-Protocol Driver
• Using network protocols built into the database engine talk directly
to the database using Java sockets. Almost always comes only
from database vendors. 50
Type-1 JDBC-ODBC Bridge

51
Type-1 JDBC-ODBC Bridge
• Converts JDBC method calls into ODBC function calls
• Platform-dependent
• ODBC must be installed on the computer having the driver
• Sun (now Oracle) provided a JDBC-ODBC Bridge
river: sun.jdbc.odbc.JdbcOdbcDriver.
• Advantages
– Almost any database for which an ODBC driver is installed can be
accessed, and data can be retrieved.
• Disadvantages
– Performance overhead
– The ODBC driver needs to be installed on the client machine.
– Not suitable for applets
– Specific ODBC drivers are not always available on all platforms
– No support from JDK 1.8 (Java 8) onwards.

52
Type 2 - Native API Driver

53
Type 2 - Native API Driver
• It is a database driver implementation that uses the client-side
libraries of the database
• converts JDBC method calls into native calls of the database
API
• Advantages
– As there is no implementation of JDBC-ODBC bridge, it may
be considerably faster than a Type 1 driver.
• Disadvantages
– The vendor client library needs to be installed on the client
machine.
– Not all databases have a client-side library.
– This driver is platform dependent.
– No Applets support

54
Type 3 – Network-Protocol Driver

55
Type 3 – Network-Protocol Driver
• Pure Java driver for database middleware
• It is a database driver implementation which makes use of a middle
tier between the calling program and the database
• The middle-tier (application server) converts JDBC calls directly or
indirectly into a vendor-specific database protocol.
• platform-independent
• Advantages
– Since the communication between client and the middleware server is
database independent, there is no need for the database vendor library on
the client.
– The middleware server can provide typical middleware services like
caching, load balancing, logging, and auditing.
– A single driver can handle any database, provided the middleware supports
it.
• Disadvantages
– Requires database-specific coding to be done in the middle tier.
– The middleware layer added may result in additional latency, but is typically
overcome by using better middleware services.
56
Type-4 Database-Protocol driver
(Pure Java driver)

57
Type-4 Database-Protocol driver
(Pure Java driver)
• a database driver implementation that converts JDBC calls directly into
a vendor-specific database protocol
• Written completely in Java
• Platform independent
• Advantages
– These drivers don't translate the requests into an intermediary
format (such as ODBC).
– The client application connects directly to the database server.
– The JVM can manage all aspects of the application-to-database
connection
• Disadvantages
– Drivers are database specific, as different database vendors use
widely different network protocols.

58
Which Driver should be Used?
• Type is 4: If you are accessing one type of database,
such as Oracle, Sybase, or IBM
• Type 3: If your Java application is accessing multiple
types of databases at the same time
• Type 2: When a type 3 or type 4 driver is not available
• Type 1: It is typically used for development and testing
purposes only.
Basic steps to use a database in Java

1. Register the Driver class


2. Create connection
3. Create statement
4. Execute queries
5. Close connection

60
JDBC program example-1
import java.sql.*;
public class DatabaseAccess
{
public static void main(String args[]) throws IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/test","root","root");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM student");
while(rs.next())
{
System.out.println("Roll No: " + rs.getInt(1) + "<br>");
System.out.println("Name: " + rs.getString(2) + "<br>");
}
stmt.close(); conn.close();
}
catch(SQLException se) { se.printStackTrace(); }
}
} 61
JDBC program example-2
import java.sql.*;
class DatabaseInsert
{
public static void main(String args[])
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection
con=DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:testdb","system","oracle");
PreparedStatement stmt=con.prepareStatement("insert into Emp values(?,?)");
stmt.setInt(1,101);
stmt.setString(2,"Ratan");
int i=stmt.executeUpdate();
System.out.println(i+" records inserted");
con.close();
}
catch(Exception e){System.out.println(e);}
}
}
62
• Class.forName()
– The forName() method of Class class is used to register the driver class.
This method is used to dynamically load the driver class.
• DriverManager class
– The DriverManager class maintains a list of Driver classes that have
registered themselves by calling the method DriverManager.registerDriver().
1. public static Connection getConnection(String url,String
userName,String password):establish the connection with the specified
url, username and password.
• Connection interface
– A Connection is the session between java application and database.
1. public Statement createStatement():creates a statement object that can
be used to execute SQL queries.
2. public void close(): closes the connection and Releases a JDBC
resources immediately.
• Statement interface
– provides methods to execute queries with the database.
1. public ResultSet executeQuery(String sql): is used to execute SELECT
query. It returns the object of ResultSet.
2. public int executeUpdate(String sql): is used to execute specified query,
it may be create, drop, insert, update, delete etc.
• ResultSet interface
– maintains a cursor pointing to a row of a table. Initially, cursor points
to before the first row.
1. public boolean next():is used to move the cursor to the one row
next from the current position.
2. public int getInt(int columnIndex):return the data of specified column
index of the current row as int.
3. public int getInt(String columnName):return the data of specified
column name of the current row as int.
4. public String getString(int columnIndex):return the data of
specified column index of the current row as String.
5. public String getString(String columnName):return the data of
specified column name of the current row as String.
• PreparedStatement interface
– a subinterface of Statement
– It is used to execute parameterized query.
– Eg.: String sql="insert into emp values(?,?,?)";
JSP
• Java Server Pages (JSP) is a server-side programming
technology that enables the creation of dynamic,
platform-independent method for building Web-based
applications.
• JSP have access to the entire family of Java APIs,
including the JDBC API to access enterprise databases.
• JSP technology enables rapid development of web-
based applications
• JSP pages are easier to maintain then a Servlet
• JSP pages are opposite of Servlets as a servlet adds
HTML code inside Java code, while JSP adds Java code
inside HTML using JSP tags
JSP Architecture

66
JSP Life Cycle

67
JSP Syntax
• JSP Scriptlet
– Scriptlet tag allows to write Java code into JSP file.
– JSP container moves statements in _jspservice() method while
generating servlet from jsp.
– Syntax:
<% ... %>
• JSP Declaration Tag
– for declaring variables, methods and classes
– declaration is made outside the service method
– Syntax:
<%! Datatype varname; %>
• JSP Expression
– evaluates the expression placed in it
<%= ... %>
• JSP Directives
<%@ ... %> 68
JSP Scriptlet Example

<!DOCTYPE html>
<html>
<head><title>JSP Example</title></head>
<body>
<% out.println(“Hello World”); %>
</body>
</html>
JSP Declaration Example

<!DOCTYPE html>
<html>
<head><title>JSP Example</title></head>
<body>
<%! int num=10; %>
<% out.println(“This number is ”+num); %>
</body>
</html>
JSP Expression Example

date.jsp

<html>
<body>
Hello! The time is now <%= new java.util.Date() %>
</body>
</html>

71
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:


– page directive
<%@ page attribute="value" %>

– include directive
<%@ include file="resourceName" %>

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

72
page directive

• Attributes of JSP page directive


– import
– contentType
– extends
– info
– buffer
– language
– isELIgnored
– isThreadSafe
– autoFlush
– session
– pageEncoding
– errorPage
– isErrorPage
73
include directive
header.html
<html>
<head>
<title>K.Ramakrishnan College of Technology</title>
</head>
<body>
<h1>K.Ramakrishnan College of Technology</h1>

footer.html
</body>
</html>

main.jsp
<%@ include file="header.html" %>
<p>Main content</p>
<%@ include file="footer.html" %> 74
taglib directive
• The JavaServer Pages API allows you to define
custom JSP tags that look like HTML or XML tags
and a tag library is a set of user-defined tags that
implement custom behavior.
• Syntax:
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>

75
JSP Action Tags
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.

76
jsp:forward & jsp:param
page1.jsp

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

<jsp:forward page="page2.jsp" >


<jsp:param name=“email" value=“[email protected]" />
</jsp:forward>
page2.jsp
</body>
</html>
<html>
<body>

<%= request.getParameter(“email") %>

</body>
77
</html>
jsp:include
<html>
<body>
<h2>this is index page</h2>
<jsp:include page=“page2.jsp" />
<h2>end section of index page</h2>
</body>
</html>

78
Creating HTML forms by embedding JSP
code.
<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>
<body>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Grade program
index.html
• <!DOCTYPE html>
• <html>
• <head>
• <title> Marks </title>
• <meta charset="UTF-8">
• <meta name="viewport" content="width=device-width, initial-scale=1.0">
• </head>
• <body>
• <p> Enter Marks </p>
• <form action="result.jsp" method="get">
• Enter Marks in Advanced Java: <input type="text" name="java"><br><br>
• Enter NMA Marks: <input type="text" name="NMA"><br><br>
• Enter MCAD Marks: <input type="text" name="MCAD"><br><br>
• Enter PPUD Marks: <input type="text" name="PPUD"><br><br>
• Enter Project Marks: <input type="text" name="pro"><br><br>
• <input type="submit">
• </form>
• </body>
• </html>
Result.jsp
• <%@page contentType="text/html" pageEncoding="UTF-8"%>
• <!DOCTYPE html>
• <html>
• <head>
• <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
• <title> Result </title>
• </head>
• <body>
• <%
• int java = Integer.parseInt(request.getParameter("java"));
• int NMA = Integer.parseInt(request.getParameter("NMA"));
• int MCAD = Integer.parseInt(request.getParameter("MCAD"));
• int PPUD = Integer.parseInt(request.getParameter("PPUD"));
• int Project = Integer.parseInt(request.getParameter("pro"));
• int totalMarks = java + NMA + MCAD + PPUD + Project;
• double average = totalMarks / 5.0;
• out.print("Your grade is ");
• if (average > 90) {
• out.print("A");
• } else if (average >= 80) {
• out.print("B");
• } else if (average >= 70) {
• out.print("C");
• } else if (average >= 60) {
• out.print("D");
• } else {
• out.print("E");
• }
• %>
• </body>
• </html>

You might also like