SlideShare a Scribd company logo
JSP TUTORIAL
US SEMESTER 4
• JSP technology is used to create web application
• A JSP page consists of HTML tags and JSP tags
JSP TUTORIAL for students M.Sc computer Science
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.
1.<html>
2.<body>
3.<% out.print(2*5); %>
4.</body>
5.</html>
index.jsp
How to run a simple JSP Page?
Follow the following steps to execute this JSP page:
•Start the server
•Put the JSP file in a folder and deploy on the server
•Visit the browser by the URL http://localhost:portno/contextRoot/jspfile,
for example, http://localhost:8888/myapplication/index.jsp
The Directory structure of JSP
A) JSP Scripting elements
JSP scriptlet tag
A scriptlet tag is used to execute java source code in JSP. Syntax is as follows:
<% java source code %>
Example of JSP scriptlet tag
In this example, we are displaying a welcome
message.
<html>
<body>
<% out.print("welcome to jsp"); %>
</body>
</html>
Example of JSP scriptlet tag that prints the user name
The index.html file gets the username from the user and the welcome.jsp file prints the username
with the welcome message.
File: index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
</form>
</body>
</html>
JSP TUTORIAL for students M.Sc computer Science
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.
1. Syntax of JSP expression tag
<%= statement %>
Example of JSP expression tag
<html>
<body>
<%= "welcome to jsp" %>
</body>
</html>
1. Example of JSP expression tag that prints current time
index.jsp
<html>
<body>
Current Time: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
2. Example of JSP expression tag that prints the user name
File: index.jsp
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname"><br/>
<input type="submit" value="go">
</form>
</body>
</html>
File: welcome.jsp
<html>
<body>
<%= "Welcome "+request.getParameter("uname") %>
</body>
</html>
JSP TUTORIAL for students M.Sc computer Science
JSP Declaration Tag
To declare variable or method in JSP declaration tag is used.
Syntax
<%! Scripting-language-declaration %>
Example
<!DOCTYPE html>
<html>
<head>
<title>Declaration tag</title>
</head>
<body>
<%! int a=100; %>
<%= "Value of the variable is:"+a %>
</body>
</html>
B) JSP implicit objects
1. JSP request implicit object with Example
• The JSP request is an implicit object of type HttpServletRequest.
• It is used to get request information such as parameter, header information, remote address, server
name, server port, content type, character coding etc.
• Request implicit object is used to get the data on a JSP page which has been entered by user on the
previous JSP or HTML page.
index.html
<!DOCTYPE html>
<html>
<head>
<title>Hello World</title>
</head>
<body>
<form action="home.jsp">
<input type="text" placeholder="first
name" name="fname"> <br><br>
<input type="text" placeholder="last
name" name="lname"> <br> <br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
home.jsp
<%@ page
language="java" contentType="text/html;
charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-
Type" content="text/html; charset=ISO-8859-1">
<title>JSP Request </title>
</head>
<body>
<%
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
out.print("First Name :"+fname);
out.println("<br>");
out.print("Last Name :"+lname);
%>
</body>
</html>
JSP TUTORIAL for students M.Sc computer Science
2. JSP response implicit object with example
• Response implicit object is mainly used for send response to the client browser after
processing the request.
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSP Session</title>
</head>
<body>
<form action="process.jsp">
<input type="text" placeholder="User id" name="userid"> <br><br>
<input type="text" placeholder="Password" name="password"> <br> <br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Session</title>
</head>
<body>
<%
String userid=request.getParameter("userid");
String password=request.getParameter("password");
if(userid.equals("admin") && password.equals("admin123"))
{
response.sendRedirect("success.jsp");
}
else {
response.sendRedirect("error.jsp");
}
%>
</body>
</html>
sucess.jsp
<!DOCTYPE html>
<html>
<head>
<title>you are Sucessfully logged In</title>
</head>
<body>
<p>Sucess</p>
</body>
</html>
error.jsp
<!DOCTYPE html>
<html>
<head>
<title>Error</title>
</head>
<body>
<p>Error</p>
</body>
</html>
3. JSP Config implicit object
• In JSP, config is an implicit object of type ServletConfig. Config Implicit object is used for getting
configuration information for a particular JSP page like get the driver name, servlet name etc.
• The config object is created by the web container for each jsp page. Generally, it is used to get
initialization parameter from the web.xml file.
web.xml
<web-app>
<servlet>
<servlet-name>StudentsTutorial</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>StudentsTutorial</servlet-name>
<url-pattern>/index</url-pattern>
</servlet-mapping>
</web-app>
index.jsp
<!DOCTYPE html>
<html>
<head>
<title> JSP Config</title>
</head>
<body>
<%
String name=config.getServletName();
out.print("Name of Servlet is: "+name);
%>
</body>
</html>
4. JSP Application implicit object
• In JSP, Application implicit object used for getting initialization parameters and for sharing the
attributes and their values across all JSP page.That means any attribute set by application implicit
object would be available to all the JSP pages.
• Application implicit object is an instance of javax.servlet.ServletContext.
index.jsp
<%@ page import="java.io.*,java.util.*" %>
<!DOCTYPE html>
<html>
<head>
<title> Application Implicit Object</title>
</head>
<body>
<h1>JSP Tutorial</h1> <%
Integer counter= (Integer)application.getAttribute("visit");
if( counter ==null || counter == 0 ){
counter = 1;
}
else{
counter = counter+ 1;
}
application.setAttribute("visit", counter);
%>
<h3>Total number of view to this Page is: <%= counter%></h3>
<p>Copyright © 2017 By <a href="//www.studentstutorial.com" target="_blank" style="text-
decoration:none"><b style="color:green">studentstutorial.com</b></a>. All Rights Reserved.</p>
</body>
</html>
5. JSP session implicit object
• In JSP session is a way to store information to be used across multiple pages till the user
session is active.
• Session variable hold information about one single user and available to all pages.
index.html
<!DOCTYPE html>
<html>
<head>
<title>JSP Session</title>
</head>
<body>
<form action="session-one.jsp">
<input type="text" placeholder="first name" name="fname"> <br><br>
<input type="text" placeholder="last name" name="lname"> <br> <br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
session-one.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Session</title>
</head>
<body>
<%
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
session.setAttribute("fname",fname);
session.setAttribute("lname",lname);
out.print("Hello"+fname);
out.print("<br>");
out.print("Session set sucessfully. Please click on the below link to check.");
%>
<br> <a href="session-two.jsp">Check</a>
</body>
</html>
session-two.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Session </title>
</head>
<body>
<%
String fname=(String)session.getAttribute("fname");
String lname=(String)session.getAttribute("lname");
out.print("First Name :"+fname);
out.print("<br>");
out.print("Last Name :"+lname);
%>
</body>
</html>
JSP TUTORIAL for students M.Sc computer Science
6. JSP pageContext Implicit Object with Example
• In JSP, pageContext is an instance of javax.servlet.jsp.PageContext.
• Using this object you can set,get or remove attribute from one of the following scopes:
 JSP Page Scope: PAGE_CONTEXT
 HTTP Request Scope: REQUEST_CONTEXT
 HTTP Session Scope: SESSION_CONTEXT
 Application Level Scope: APPLICATION_CONTEXT
index.html
<!DOCTYPE html>
<html>
<head>
<title>pageContext Implicit Object</title>
</head>
<body>
<form action="process.jsp">
<input type="text" placeholder="first name" name="userid"> <br><br>
<input type="text" placeholder="last name" name="password"> <br> <br>
<input type="submit" value="submit"><br>
</form>
</body>
</html>
process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP PagContext </title>
</head>
<body>
<%
String userid=request.getParameter("userid");
String password=request.getParameter("password");
out.println("Hello :"+userid);
pageContext.setAttribute("UserName", userid, PageContext.SESSION_SCOPE);
pageContext.setAttribute("UserPassword", password, PageContext.SESSION_SCOPE);
%>
<br> <a href=“display.jsp">Check</a>
</body>
</html>
display.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP PagContext </title>
</head>
<body>
<%
String username= (String) pageContext.getAttribute("UserName", PageContext.SESSION_SCOPE);
String userpassword= (String) pageContext.getAttribute("UserPassword", PageContext.SESSION_SCOPE);
out.println("Hi "+username+" you enter");
out.println("<br><br>");
out.println("Userid :"+username);
out.println("<br>");
out.println("Password :"+userpassword);
%>
</body>
</html>
JSP TUTORIAL for students M.Sc computer Science
7. JSP Exception Implicit Object
• In JSP, exception is a instance of java.lang.Throwable and used for Exception Handling.
• This object is only available for error pages and used for print Exception.
index.html
<html>
<head>
<title>Exception Implicit Object</title>
</head>
<body>
<form action="action.jsp">
First Number:<input type="text" name="fno" />
Second Number:<input type="text" name="sno" />
<input type="submit" value="submit"/>
</form>
</body>
</html>
action.jsp
<%@ page errorPage="exception.jsp" %>
<%
String num1=request.getParameter("fno");
String num2=request.getParameter("sno");
int s1= Integer.parseInt(num1);
int s2= Integer.parseInt(num2);
int exp= s1/s2;
out.print("Output is: "+ exp);
%>
exception.jsp
<%@ page isErrorPage="true" %>
Got this Exception: <%= exception %>
C) JSP Directive elements
• JSP directives are used to give messages that tells the web container how to translate a
JSP page into the corresponding servlet.
Syntax of JSP Directive
<%@ directive attribute="value" %>
There are three types of directives:
•page directive
•include directive
•taglib directive
1. Page Directive with Example
• The page directive is used to defines attributes that apply to an entire JSP page.
• You can code page directives anywhere in your JSP page.
Syntax of JSP page Directive
<%@ page attribute="value" %>
Attributes of JSP page directive
1. import
2. contentType
3. extends
4. info
5. buffer
6. language
7. isELIgnored
8. isThreadSafe
9. autoFlush
10.session
11.pageEncoding
12.errorPage
13.isErrorPage
2. JSP Include Directive
• The JSP include directive is used to takes all the JSP file, HTML file or text file that exists on
the specified file and copies into the file that include statement.
• Include directive is very useful when we want to include the same JSP, HTML or text
file on multiple pages of a web application.
<%@ include file="filename" %>
JSP Include Directive Example
Assume we have a standard footer file called "footer.html", that looks like this:
footer.html
<p>Copyright © 2017
www.studentstutorial.com</p>
To include it in a JSP file use include statement
Example
<!DOCTYPE html>
<html>
<head>
<title>JSP include</title>
</head>
<body>
<% out.print("Welcome to JSP Tutorial"); %>
<%@ include file="footer.html" %> </body>
</html>
Output
Welcome to JSP Tutorial
Copyright © 2017 www.studentstutorial.com
3. JSP Taglib Directive
To define a tag library that defines many tags, JSP taglib directive is used. We use the TLD
(Tag Library Descriptor) file to define the tags.
The URI is the unique name for Tag Library.
Syntax JSP Taglib directive
<%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %>
Example
For example, suppose the custlib tag library contains a tag called hello. If you wanted to
use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be
used in your JSP file as follows:
<%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %>
<!DOCTYPE html>
<html>
<body>
<mytag:hello/>
</body>
</html>
• The JS 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.
4. JSP Exception Handling with Example
Exception
• Any unwanted or unexpected event that interrupts the normal flow of program execution is known
as exception.
• Generally Exception occurs when a user enter wrong data. It is a object that is thrown at run time.
Example :
Suppose we want to divide a number by zero in a Java application then it give a exception message
that java.lang.AirthmeticException: / by zero
That means a number can’t be divide by Zero.
So to handle this type of problem exception handling process is used.
In JSP, there are two ways to perform exception handling:
1. By errorPage and isErrorPage attributes of page directive
2. By element in web.xml file
exception.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>JSP Exception</title>
</head>
<body>
<%
try{
int array[]={1,2,3,4,5};
int number=array[6];
out.println("7th element of array"+number);
} catch (Exception exp){
out.println("<h3>The number you try to access is not available :</h3> <br>" + exp);
}
%>
</body>
</html>
Exception Handling Example
JSP TUTORIAL for students M.Sc computer Science
C) JSP with Database
1. Create a Table
<%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<html>
<head>
<title>Creating a Table</title>
</head>
<body>
<h1>Creating a Table</h1>
<%
Connection connection = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement statement = connection.createStatement();
String query = "CREATE TABLE student (Id INTEGER, Name CHAR(50));";
statement.executeUpdate(query);
out.println("Table student create sucessfully.");
}
catch (Exception e)
{
out.println("An error occurred.");
}
%>
</body>
</html>
2. Insert Data JSP Source Code
index.html
<!DOCTYPE html>
<html>
<body>
<form method="post" action="process.jsp">
First name:<br>
<input type="text" name="first_name">
<br>
Last name:<br>
<input type="text" name="last_name">
<br>
City name:<br>
<input type="text" name="city_name">
<br>
Email Id:<br>
<input type="email" name="email">
<br><br>
<input type="submit" value="submit">
</form>
</body>
</html>
<%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into
users(first_name,last_name,city_name,email)values('"+first_name+"','"+last_name+"','"+city_name+"','"+email+"')");
out.println("Data is successfully inserted!");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>
process.jsp
retrieve.jsp
2. Retrieve Data from database JSP
<%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String id = request.getParameter("userid");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
%>
<!DOCTYPE html>
<html>
<body>
<h1>Retrieve data from database in jsp</h1>
<table border="1">
<tr>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
</tr>
<%
try{
Statement statement=connection.createStatement();
String sql ="select * from users";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("first_name") %></td>
<td><%=resultSet.getString("last_name") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
</tr>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
After retrieve the data from the data base the table look like this.
id first name last name City name Email Id
1 Divyasundar Sahu Mumbai divyasundar@g
mail.com
2 Hritika Sahu Pune hritika@gmail.
com
3 Milan Jena Chennai milanjena@gm
ail.com
3. Update Data in Database from JSP
Index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
String id = request.getParameter(“userid");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
%>
<html>
<body>
<h1>Retrieve data from database in jsp</h1>
<table border="1">
<tr>
<td>id</td>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
<td>update</td>
</tr>
<%
try{
Statement statement=connection.createStatement();
String sql ="select * from users";
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("first_name") %></td>
<td><%=resultSet.getString("last_name") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
<</tr>td><a href="update.jsp?id=<%=resultSet.getString("id")%>">update</a></td>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
id first name last name City name Email Id Action
1 Divyasundar Sahu Mumbai divyasundar
@gmail.com
Update
2 Hritika Sahu Pune hritika@gma
il.com
Update
3 Milan Jena Chennai milanjena@
gmail.com
Update
update.jsp
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
String id = request.getParameter("id");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
%>
<%
try{
Statement statement=connection.createStatement();
String sql ="select * from users where id="+id;
ResultSet resultSet = statement.executeQuery(sql);
while(resultSet.next()){
%>
<!DOCTYPE html>
<html>
<body>
<h1>Update data from database in jsp</h1>
<form method="post" action="update-process.jsp">
<input type="hidden" name="id" value="<%=resultSet.getString("id") %>">
<input type="text" name="id" value="<%=resultSet.getString("id") %>">
<br>
First name:<br>
<input type="text" name="first_name" value="<%=resultSet.getString("first_name") %>">
<br>
Last name:<br>
<input type="text" name="last_name" value="<%=resultSet.getString("last_name") %>">
<br>
City name:<br>
<input type="text" name="city_name" value="<%=resultSet.getString("city_name") %>">
<br>
Email Id:<br>
<input type="email" name="email" value="<%=resultSet.getString("email") %>">
<br><br>
<input type="submit" value="submit">
</form>
<%
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</body>
</html>
update-process.jsp
<%@ page language="java" contentType="text/html;
charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<%
String id = request.getParameter("id");
String first_name=request.getParameter("first_name");
String last_name=request.getParameter("last_name");
String city_name=request.getParameter("city_name");
String email=request.getParameter("email");
if(id != null)
{
int personID = Integer.parseInt(id);
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
String sql="Update users set id=?,first_name=?,last_name=?,city_name=?,email=? where id="+id;
PreparedStatement ps=con.prepareStatement(sql);
ps.setString(1,id);
ps.setString(2, first_name);
ps.setString(3, last_name);
ps.setString(4, city_name);
ps.setString(5, email);
int i = ps.executeUpdate();
if(i > 0)
{
out.print("Record Updated Successfully");
}
else
{
out.print("There is a problem in updating Record.");
}
}
catch(SQLException sql)
{
request.setAttribute("error", sql);
out.println(sql);
}
}
%> id first name last name City name Email Id Action
1 Divyasundar Sahu Delhi divyasundar
sahu@gmail.
com
Update
2 Hritika Sahu Pune hritika@gma
il.com
Update
3 Milan Jena Chennai milanjena@
gmail.com
Update
4. Delete Data From Oracle using JSP
Index.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
%>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<body>
<h1>Retrieve data from database in jsp</h1>
<table border="1">
<tr>
<td>id</td>
<td>first name</td>
<td>last name</td>
<td>City name</td>
<td>Email</td>
<td>update</td>
</tr>
<%
try{
String sql ="select * from users";
ResultSet resultSet = statement.executeQuery(sql);
int i=0;
while(resultSet.next()){
%>
<tr>
<td><%=resultSet.getString("first_name") %></td>
<td><%=resultSet.getString("last_name") %></td>
<td><%=resultSet.getString("city_name") %></td>
<td><%=resultSet.getString("email") %></td>
<td><a href="delete.jsp?id=<%=resultSet.getString("id") %>">
<button type="button" class="delete">Delete</button> </a>
</td></tr>
<%
i++;
}
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
</table>
</body>
</html>
delete.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String id=request.getParameter("id");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement st=conn.createStatement();
int i=st.executeUpdate("DELETE FROM users WHERE id="+id);
out.println("Data Deleted Successfully!");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>
5. JSP login And Sign Up Form With Session
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>login</title>
</head>
<body>
<form action="login.jsp" method="post">
User name :<input type="text" name="usr" /><br>
password :<input type="password" name="password" /><br>
<input type="submit" />
</form>
<p>New user. <a href="register.html">Login Here</a>. </body>
</html>
login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String userid=request.getParameter("userid");
session.putValue("userid",userid);
String password=request.getParameter("password");
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from users where userid='"+userid+"' and password='"+password+"'");
try{
rs.next();
if(rs.getString("password").equals(password)&&rs.getString("
userid").equals(userid))
{
out.println("Welcome " +userid);
}
else{
out.println("Invalid password or username.");
}
}
catch (Exception e) {
e.printStackTrace();
}
%>
register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>new registration</title>
</head>
<body>
<form action="reg-process.jsp" method="post">
First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
Email ID :<input type="text" name="email" />
User name :<input type="text" name="userid" />
password :<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>
reg-process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*,java.util.*"%>
<%
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
String userid=request.getParameter("userid");
String password=request.getParameter("password");
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement st=conn.createStatement();
int i=st.executeUpdate("insert into
users(fname,lname,email,userid,password)values('"+fname+"','"+lname+"','"+email+"','"+userid+"','"+password+"')");
out.println("Thank you for register ! Please <a href='index.html'>Login</a> to continue.");
}
catch(Exception e)
{
System.out.print(e);
e.printStackTrace();
}
%>
6.Check duplicate userid or email ID before register JSP
register.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>new registration</title>
</head>
<body>
<form action="reg-process.jsp" method="post">
First name :<input type="text" name="fname" />
Last name :<input type="text" name="lname" />
Email ID :<input type="text" name="email" />
User name :<input type="text" name="userid" />
password
:<input type="password" name="password" />
<input type="submit" />
</form>
</body>
</html>
reg-process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Count Rows JSP</title>
</head>
<body>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement st=con.createStatement();
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
String userid=request.getParameter("userid");
String password=request.getParameter("password");
String strQuery = "SELECT COUNT(*) FROM users where email='"+email+"'";
ResultSet rs = st.executeQuery(strQuery);
rs.next();
String Countrow = rs.getString(1);out.println(Countrow);
if(Countrow.equals("0")){
int i=st.executeUpdate("insert into users(fname,lname,email,userid,password)values('"+fname+"','"+lname+"','"+email+"','"+userid+"','"+password+"')");
}
else{
out.println("User name or Email already exists !");
}
}
catch (Exception e){
e.printStackTrace();
}
%>
</body>
</html>
7. Change password in JSP
In this example my current password is "Admin@123" and i am going to change
into as "Admin@12345".
login.sql
CREATE TABLE `login` (
`id` int(10) NOT NULL,
`currentPassword` varchar(10) DEFAULT NULL,
`Newpass` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1
index.html
<html>
<form action="changePassword.jsp" method="post">
<table>
<tr><td>Current Password</td><td><input type="password" name="current" ></td></tr>
<tr><td>New Password</td><td><input type="password" name="new"></td></tr>
<tr><td>Confirm Password</td><td><input type="password" name="confirm"></td></tr>
<tr><td><input type="submit" value="Change Password"></td></tr>
</table>
</form>
</html>
changePassword.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@page import="java.sql.*"%>
<%@page import="java.io.*"%>
<%
String currentPassword=request.getParameter("current");
String Newpass=request.getParameter("new");
String conpass=request.getParameter("confirm");
int id=0;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from login where password='"+currentPassword+"'");
while(rs.next()){
id=rs.getInt(1);
pass=rs.getString(3);
} System.out.println(id+ " "+pass);
if(pass.equals(currentPassword)){
Statement st1=con.createStatement();
int i=st1.executeUpdate("update login set password='"+Newpass+"' where id='"+id+"'");
out.println("Password changed successfully");
st1.close();
con.close();
}
else{
out.println("Invalid Current Password");
}
}
catch(Exception e){
out.println(e);
}
%>
8. Forgot password JSP
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Forgot Password JSP</title>
</head>
<body>
<h1>Forgot Password</h1>
<form action="forgot-process.jsp" method="post"><br><br>
Enter Email ID:<input type="text" name="email" /><br><br>
<input type="submit" />
</form>
</body>
</html>
forgot-process.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Count Rows JSP</title>
</head>
<body>
<%
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle");
Statement st=con.createStatement();
String email=request.getParameter("email");
String strQuery = "SELECT password FROM users where email='"+email+"'";
ResultSet rs = st.executeQuery(strQuery);
rs.next();
String Countrow = rs.getString(1);
if(Countrow.equals("1")){
/*mail code
paste your mail code here
------------------
Mail code*/
out.println("Password send to your email id successfully !");
}
else{
out.println("Invalid Email Id !");
}
}
catch (Exception e){
e.printStackTrace();
}
%>
</body>
9. How to insert image in Oracle database using JSP
JSP TUTORIAL for students M.Sc computer Science
JSP TUTORIAL for students M.Sc computer Science
References
1. https://www.studentstutorial.com/jsp/jsp-tutorial.php

More Related Content

PPTX
Implicit objects advance Java
PPT
PPTX
Introduction to JSP.pptx
DOC
Jsp advance part i
PPTX
Web programming-Introduction to JSP.pptx
PPTX
Java server pages
Implicit objects advance Java
Introduction to JSP.pptx
Jsp advance part i
Web programming-Introduction to JSP.pptx
Java server pages

Similar to JSP TUTORIAL for students M.Sc computer Science (20)

PPT
Server side development on java server pages
PPTX
JSP AND XML USING JAVA WITH GET AND POST METHODS
PPTX
Jsp Introduction Tutorial
PPTX
jsp unit 3byudoue8euwuuutrttttyyii90oigyu7
PPTX
JSP.pptx programming guide for beginners and experts
DOC
DOC
PPTX
JavaServer Pages
PPTX
Learning jsp
PPTX
Jsp session 3
PPTX
JSP_Complete_Guide_With_Step_By_Step_solution
PPTX
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
PPSX
Java server pages
PPTX
PDF
JavaServer Pages
PDF
Lap trinh web [Slide jsp]
DOCX
PPTX
Advance java session 11
PPTX
JSP - Java Server Page
PPTX
Session 36 - JSP - Part 1
Server side development on java server pages
JSP AND XML USING JAVA WITH GET AND POST METHODS
Jsp Introduction Tutorial
jsp unit 3byudoue8euwuuutrttttyyii90oigyu7
JSP.pptx programming guide for beginners and experts
JavaServer Pages
Learning jsp
Jsp session 3
JSP_Complete_Guide_With_Step_By_Step_solution
Internet and Web Technology (CLASS-14) [JSP] | NIC/NIELIT Web Technology
Java server pages
JavaServer Pages
Lap trinh web [Slide jsp]
Advance java session 11
JSP - Java Server Page
Session 36 - JSP - Part 1
Ad

Recently uploaded (20)

PDF
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
PPTX
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
PDF
01-Introduction-to-Information-Management.pdf
PDF
RMMM.pdf make it easy to upload and study
PPTX
Renaissance Architecture: A Journey from Faith to Humanism
PPTX
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
PDF
102 student loan defaulters named and shamed – Is someone you know on the list?
PPTX
Cell Types and Its function , kingdom of life
PDF
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
PDF
Basic Mud Logging Guide for educational purpose
PDF
O7-L3 Supply Chain Operations - ICLT Program
PDF
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
PDF
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPTX
PPH.pptx obstetrics and gynecology in nursing
PPTX
Pharmacology of Heart Failure /Pharmacotherapy of CHF
PDF
STATICS OF THE RIGID BODIES Hibbelers.pdf
PPTX
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
PDF
Classroom Observation Tools for Teachers
PPTX
Microbial diseases, their pathogenesis and prophylaxis
PPTX
Lesson notes of climatology university.
Chapter 2 Heredity, Prenatal Development, and Birth.pdf
BOWEL ELIMINATION FACTORS AFFECTING AND TYPES
01-Introduction-to-Information-Management.pdf
RMMM.pdf make it easy to upload and study
Renaissance Architecture: A Journey from Faith to Humanism
1st Inaugural Professorial Lecture held on 19th February 2020 (Governance and...
102 student loan defaulters named and shamed – Is someone you know on the list?
Cell Types and Its function , kingdom of life
Physiotherapy_for_Respiratory_and_Cardiac_Problems WEBBER.pdf
Basic Mud Logging Guide for educational purpose
O7-L3 Supply Chain Operations - ICLT Program
grade 11-chemistry_fetena_net_5883.pdf teacher guide for all student
BÀI TẬP BỔ TRỢ 4 KỸ NĂNG TIẾNG ANH 9 GLOBAL SUCCESS - CẢ NĂM - BÁM SÁT FORM Đ...
PPH.pptx obstetrics and gynecology in nursing
Pharmacology of Heart Failure /Pharmacotherapy of CHF
STATICS OF THE RIGID BODIES Hibbelers.pdf
IMMUNITY IMMUNITY refers to protection against infection, and the immune syst...
Classroom Observation Tools for Teachers
Microbial diseases, their pathogenesis and prophylaxis
Lesson notes of climatology university.
Ad

JSP TUTORIAL for students M.Sc computer Science

  • 2. • JSP technology is used to create web application • A JSP page consists of HTML tags and JSP tags
  • 4. 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. 1.<html> 2.<body> 3.<% out.print(2*5); %> 4.</body> 5.</html> index.jsp
  • 5. How to run a simple JSP Page? Follow the following steps to execute this JSP page: •Start the server •Put the JSP file in a folder and deploy on the server •Visit the browser by the URL http://localhost:portno/contextRoot/jspfile, for example, http://localhost:8888/myapplication/index.jsp
  • 7. A) JSP Scripting elements
  • 8. JSP scriptlet tag A scriptlet tag is used to execute java source code in JSP. Syntax is as follows: <% java source code %> Example of JSP scriptlet tag In this example, we are displaying a welcome message. <html> <body> <% out.print("welcome to jsp"); %> </body> </html>
  • 9. Example of JSP scriptlet tag that prints the user name The index.html file gets the username from the user and the welcome.jsp file prints the username with the welcome message. File: index.html <html> <body> <form action="welcome.jsp"> <input type="text" name="uname"> <input type="submit" value="go"><br/> </form> </body> </html> File: welcome.jsp <html> <body> <% String name=request.getParameter("uname"); out.print("welcome "+name); %> </form> </body> </html>
  • 11. 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. 1. Syntax of JSP expression tag <%= statement %> Example of JSP expression tag <html> <body> <%= "welcome to jsp" %> </body> </html>
  • 12. 1. Example of JSP expression tag that prints current time index.jsp <html> <body> Current Time: <%= java.util.Calendar.getInstance().getTime() %> </body> </html> 2. Example of JSP expression tag that prints the user name File: index.jsp <html> <body> <form action="welcome.jsp"> <input type="text" name="uname"><br/> <input type="submit" value="go"> </form> </body> </html> File: welcome.jsp <html> <body> <%= "Welcome "+request.getParameter("uname") %> </body> </html>
  • 14. JSP Declaration Tag To declare variable or method in JSP declaration tag is used. Syntax <%! Scripting-language-declaration %> Example <!DOCTYPE html> <html> <head> <title>Declaration tag</title> </head> <body> <%! int a=100; %> <%= "Value of the variable is:"+a %> </body> </html>
  • 15. B) JSP implicit objects
  • 16. 1. JSP request implicit object with Example • The JSP request is an implicit object of type HttpServletRequest. • It is used to get request information such as parameter, header information, remote address, server name, server port, content type, character coding etc. • Request implicit object is used to get the data on a JSP page which has been entered by user on the previous JSP or HTML page.
  • 17. index.html <!DOCTYPE html> <html> <head> <title>Hello World</title> </head> <body> <form action="home.jsp"> <input type="text" placeholder="first name" name="fname"> <br><br> <input type="text" placeholder="last name" name="lname"> <br> <br> <input type="submit" value="submit"><br> </form> </body> </html> home.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content- Type" content="text/html; charset=ISO-8859-1"> <title>JSP Request </title> </head> <body> <% String fname=request.getParameter("fname"); String lname=request.getParameter("lname"); out.print("First Name :"+fname); out.println("<br>"); out.print("Last Name :"+lname); %> </body> </html>
  • 19. 2. JSP response implicit object with example • Response implicit object is mainly used for send response to the client browser after processing the request. index.html <!DOCTYPE html> <html> <head> <title>JSP Session</title> </head> <body> <form action="process.jsp"> <input type="text" placeholder="User id" name="userid"> <br><br> <input type="text" placeholder="Password" name="password"> <br> <br> <input type="submit" value="submit"><br> </form> </body> </html>
  • 20. process.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP Session</title> </head> <body> <% String userid=request.getParameter("userid"); String password=request.getParameter("password"); if(userid.equals("admin") && password.equals("admin123")) { response.sendRedirect("success.jsp"); } else { response.sendRedirect("error.jsp"); } %> </body> </html> sucess.jsp <!DOCTYPE html> <html> <head> <title>you are Sucessfully logged In</title> </head> <body> <p>Sucess</p> </body> </html> error.jsp <!DOCTYPE html> <html> <head> <title>Error</title> </head> <body> <p>Error</p> </body> </html>
  • 21. 3. JSP Config implicit object • In JSP, config is an implicit object of type ServletConfig. Config Implicit object is used for getting configuration information for a particular JSP page like get the driver name, servlet name etc. • The config object is created by the web container for each jsp page. Generally, it is used to get initialization parameter from the web.xml file. web.xml <web-app> <servlet> <servlet-name>StudentsTutorial</servlet-name> <jsp-file>/index.jsp</jsp-file> </servlet> <servlet-mapping> <servlet-name>StudentsTutorial</servlet-name> <url-pattern>/index</url-pattern> </servlet-mapping> </web-app> index.jsp <!DOCTYPE html> <html> <head> <title> JSP Config</title> </head> <body> <% String name=config.getServletName(); out.print("Name of Servlet is: "+name); %> </body> </html>
  • 22. 4. JSP Application implicit object • In JSP, Application implicit object used for getting initialization parameters and for sharing the attributes and their values across all JSP page.That means any attribute set by application implicit object would be available to all the JSP pages. • Application implicit object is an instance of javax.servlet.ServletContext. index.jsp <%@ page import="java.io.*,java.util.*" %> <!DOCTYPE html> <html> <head> <title> Application Implicit Object</title> </head> <body> <h1>JSP Tutorial</h1> <% Integer counter= (Integer)application.getAttribute("visit"); if( counter ==null || counter == 0 ){ counter = 1; } else{ counter = counter+ 1; } application.setAttribute("visit", counter); %> <h3>Total number of view to this Page is: <%= counter%></h3> <p>Copyright © 2017 By <a href="//www.studentstutorial.com" target="_blank" style="text- decoration:none"><b style="color:green">studentstutorial.com</b></a>. All Rights Reserved.</p> </body> </html>
  • 23. 5. JSP session implicit object • In JSP session is a way to store information to be used across multiple pages till the user session is active. • Session variable hold information about one single user and available to all pages. index.html <!DOCTYPE html> <html> <head> <title>JSP Session</title> </head> <body> <form action="session-one.jsp"> <input type="text" placeholder="first name" name="fname"> <br><br> <input type="text" placeholder="last name" name="lname"> <br> <br> <input type="submit" value="submit"><br> </form> </body> </html>
  • 24. session-one.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP Session</title> </head> <body> <% String fname=request.getParameter("fname"); String lname=request.getParameter("lname"); session.setAttribute("fname",fname); session.setAttribute("lname",lname); out.print("Hello"+fname); out.print("<br>"); out.print("Session set sucessfully. Please click on the below link to check."); %> <br> <a href="session-two.jsp">Check</a> </body> </html>
  • 25. session-two.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP Session </title> </head> <body> <% String fname=(String)session.getAttribute("fname"); String lname=(String)session.getAttribute("lname"); out.print("First Name :"+fname); out.print("<br>"); out.print("Last Name :"+lname); %> </body> </html>
  • 27. 6. JSP pageContext Implicit Object with Example • In JSP, pageContext is an instance of javax.servlet.jsp.PageContext. • Using this object you can set,get or remove attribute from one of the following scopes:  JSP Page Scope: PAGE_CONTEXT  HTTP Request Scope: REQUEST_CONTEXT  HTTP Session Scope: SESSION_CONTEXT  Application Level Scope: APPLICATION_CONTEXT
  • 28. index.html <!DOCTYPE html> <html> <head> <title>pageContext Implicit Object</title> </head> <body> <form action="process.jsp"> <input type="text" placeholder="first name" name="userid"> <br><br> <input type="text" placeholder="last name" name="password"> <br> <br> <input type="submit" value="submit"><br> </form> </body> </html> process.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP PagContext </title> </head> <body> <% String userid=request.getParameter("userid"); String password=request.getParameter("password"); out.println("Hello :"+userid); pageContext.setAttribute("UserName", userid, PageContext.SESSION_SCOPE); pageContext.setAttribute("UserPassword", password, PageContext.SESSION_SCOPE); %> <br> <a href=“display.jsp">Check</a> </body> </html>
  • 29. display.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP PagContext </title> </head> <body> <% String username= (String) pageContext.getAttribute("UserName", PageContext.SESSION_SCOPE); String userpassword= (String) pageContext.getAttribute("UserPassword", PageContext.SESSION_SCOPE); out.println("Hi "+username+" you enter"); out.println("<br><br>"); out.println("Userid :"+username); out.println("<br>"); out.println("Password :"+userpassword); %> </body> </html>
  • 31. 7. JSP Exception Implicit Object • In JSP, exception is a instance of java.lang.Throwable and used for Exception Handling. • This object is only available for error pages and used for print Exception. index.html <html> <head> <title>Exception Implicit Object</title> </head> <body> <form action="action.jsp"> First Number:<input type="text" name="fno" /> Second Number:<input type="text" name="sno" /> <input type="submit" value="submit"/> </form> </body> </html> action.jsp <%@ page errorPage="exception.jsp" %> <% String num1=request.getParameter("fno"); String num2=request.getParameter("sno"); int s1= Integer.parseInt(num1); int s2= Integer.parseInt(num2); int exp= s1/s2; out.print("Output is: "+ exp); %> exception.jsp <%@ page isErrorPage="true" %> Got this Exception: <%= exception %>
  • 32. C) JSP Directive elements
  • 33. • JSP directives are used to give messages that tells the web container how to translate a JSP page into the corresponding servlet. Syntax of JSP Directive <%@ directive attribute="value" %> There are three types of directives: •page directive •include directive •taglib directive
  • 34. 1. Page Directive with Example • The page directive is used to defines attributes that apply to an entire JSP page. • You can code page directives anywhere in your JSP page. Syntax of JSP page Directive <%@ page attribute="value" %> Attributes of JSP page directive 1. import 2. contentType 3. extends 4. info 5. buffer 6. language 7. isELIgnored 8. isThreadSafe 9. autoFlush 10.session 11.pageEncoding 12.errorPage 13.isErrorPage
  • 35. 2. JSP Include Directive • The JSP include directive is used to takes all the JSP file, HTML file or text file that exists on the specified file and copies into the file that include statement. • Include directive is very useful when we want to include the same JSP, HTML or text file on multiple pages of a web application. <%@ include file="filename" %> JSP Include Directive Example Assume we have a standard footer file called "footer.html", that looks like this: footer.html <p>Copyright © 2017 www.studentstutorial.com</p>
  • 36. To include it in a JSP file use include statement Example <!DOCTYPE html> <html> <head> <title>JSP include</title> </head> <body> <% out.print("Welcome to JSP Tutorial"); %> <%@ include file="footer.html" %> </body> </html> Output Welcome to JSP Tutorial Copyright © 2017 www.studentstutorial.com
  • 37. 3. JSP Taglib Directive To define a tag library that defines many tags, JSP taglib directive is used. We use the TLD (Tag Library Descriptor) file to define the tags. The URI is the unique name for Tag Library. Syntax JSP Taglib directive <%@ taglib uri="uriofthetaglibrary" prefix="prefixoftaglibrary" %> Example For example, suppose the custlib tag library contains a tag called hello. If you wanted to use the hello tag with a prefix of mytag, your tag would be <mytag:hello> and it will be used in your JSP file as follows: <%@ taglib uri="http://www.example.com/custlib" prefix="mytag" %>
  • 38. <!DOCTYPE html> <html> <body> <mytag:hello/> </body> </html> • The JS 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.
  • 39. 4. JSP Exception Handling with Example Exception • Any unwanted or unexpected event that interrupts the normal flow of program execution is known as exception. • Generally Exception occurs when a user enter wrong data. It is a object that is thrown at run time. Example : Suppose we want to divide a number by zero in a Java application then it give a exception message that java.lang.AirthmeticException: / by zero That means a number can’t be divide by Zero. So to handle this type of problem exception handling process is used. In JSP, there are two ways to perform exception handling: 1. By errorPage and isErrorPage attributes of page directive 2. By element in web.xml file
  • 40. exception.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%> <!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>JSP Exception</title> </head> <body> <% try{ int array[]={1,2,3,4,5}; int number=array[6]; out.println("7th element of array"+number); } catch (Exception exp){ out.println("<h3>The number you try to access is not available :</h3> <br>" + exp); } %> </body> </html> Exception Handling Example
  • 42. C) JSP with Database
  • 43. 1. Create a Table <%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%> <%@ page import="java.sql.*" %> <html> <head> <title>Creating a Table</title> </head> <body> <h1>Creating a Table</h1> <% Connection connection = null; try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement statement = connection.createStatement(); String query = "CREATE TABLE student (Id INTEGER, Name CHAR(50));"; statement.executeUpdate(query); out.println("Table student create sucessfully."); } catch (Exception e) { out.println("An error occurred."); } %> </body> </html>
  • 44. 2. Insert Data JSP Source Code index.html <!DOCTYPE html> <html> <body> <form method="post" action="process.jsp"> First name:<br> <input type="text" name="first_name"> <br> Last name:<br> <input type="text" name="last_name"> <br> City name:<br> <input type="text" name="city_name"> <br> Email Id:<br> <input type="email" name="email"> <br><br> <input type="submit" value="submit"> </form> </body> </html>
  • 45. <%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*,java.util.*"%> <% String first_name=request.getParameter("first_name"); String last_name=request.getParameter("last_name"); String city_name=request.getParameter("city_name"); String email=request.getParameter("email"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection con=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement st=conn.createStatement(); int i=st.executeUpdate("insert into users(first_name,last_name,city_name,email)values('"+first_name+"','"+last_name+"','"+city_name+"','"+email+"')"); out.println("Data is successfully inserted!"); } catch(Exception e) { System.out.print(e); e.printStackTrace(); } %> process.jsp
  • 46. retrieve.jsp 2. Retrieve Data from database JSP <%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*,java.util.*"%> <% String id = request.getParameter("userid"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); } catch (ClassNotFoundException e) { e.printStackTrace(); } %> <!DOCTYPE html> <html> <body> <h1>Retrieve data from database in jsp</h1> <table border="1"> <tr> <td>first name</td> <td>last name</td> <td>City name</td> <td>Email</td> </tr>
  • 47. <% try{ Statement statement=connection.createStatement(); String sql ="select * from users"; ResultSet resultSet = statement.executeQuery(sql); while(resultSet.next()){ %> <tr> <td><%=resultSet.getString("first_name") %></td> <td><%=resultSet.getString("last_name") %></td> <td><%=resultSet.getString("city_name") %></td> <td><%=resultSet.getString("email") %></td> </tr> <% } connection.close(); } catch (Exception e) { e.printStackTrace(); } %> </table> </body> </html> After retrieve the data from the data base the table look like this.
  • 48. id first name last name City name Email Id 1 Divyasundar Sahu Mumbai divyasundar@g mail.com 2 Hritika Sahu Pune hritika@gmail. com 3 Milan Jena Chennai milanjena@gm ail.com
  • 49. 3. Update Data in Database from JSP Index.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <% String id = request.getParameter(“userid"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); } catch (ClassNotFoundException e) { e.printStackTrace(); } %> <html> <body> <h1>Retrieve data from database in jsp</h1> <table border="1"> <tr> <td>id</td> <td>first name</td> <td>last name</td> <td>City name</td> <td>Email</td> <td>update</td> </tr>
  • 50. <% try{ Statement statement=connection.createStatement(); String sql ="select * from users"; ResultSet resultSet = statement.executeQuery(sql); while(resultSet.next()){ %> <tr> <td><%=resultSet.getString("first_name") %></td> <td><%=resultSet.getString("last_name") %></td> <td><%=resultSet.getString("city_name") %></td> <td><%=resultSet.getString("email") %></td> <</tr>td><a href="update.jsp?id=<%=resultSet.getString("id")%>">update</a></td> <% } connection.close(); } catch (Exception e) { e.printStackTrace(); } %> </table> </body> </html> id first name last name City name Email Id Action 1 Divyasundar Sahu Mumbai divyasundar @gmail.com Update 2 Hritika Sahu Pune hritika@gma il.com Update 3 Milan Jena Chennai milanjena@ gmail.com Update
  • 51. update.jsp <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <% String id = request.getParameter("id"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); } catch (ClassNotFoundException e) { e.printStackTrace(); } %> <% try{ Statement statement=connection.createStatement(); String sql ="select * from users where id="+id; ResultSet resultSet = statement.executeQuery(sql); while(resultSet.next()){ %>
  • 52. <!DOCTYPE html> <html> <body> <h1>Update data from database in jsp</h1> <form method="post" action="update-process.jsp"> <input type="hidden" name="id" value="<%=resultSet.getString("id") %>"> <input type="text" name="id" value="<%=resultSet.getString("id") %>"> <br> First name:<br> <input type="text" name="first_name" value="<%=resultSet.getString("first_name") %>"> <br> Last name:<br> <input type="text" name="last_name" value="<%=resultSet.getString("last_name") %>"> <br> City name:<br> <input type="text" name="city_name" value="<%=resultSet.getString("city_name") %>"> <br> Email Id:<br> <input type="email" name="email" value="<%=resultSet.getString("email") %>"> <br><br> <input type="submit" value="submit"> </form> <% } connection.close(); } catch (Exception e) { e.printStackTrace(); } %> </body> </html>
  • 53. update-process.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@ page import="java.sql.*" %> <% String id = request.getParameter("id"); String first_name=request.getParameter("first_name"); String last_name=request.getParameter("last_name"); String city_name=request.getParameter("city_name"); String email=request.getParameter("email"); if(id != null) { int personID = Integer.parseInt(id); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); String sql="Update users set id=?,first_name=?,last_name=?,city_name=?,email=? where id="+id; PreparedStatement ps=con.prepareStatement(sql); ps.setString(1,id); ps.setString(2, first_name); ps.setString(3, last_name); ps.setString(4, city_name); ps.setString(5, email); int i = ps.executeUpdate();
  • 54. if(i > 0) { out.print("Record Updated Successfully"); } else { out.print("There is a problem in updating Record."); } } catch(SQLException sql) { request.setAttribute("error", sql); out.println(sql); } } %> id first name last name City name Email Id Action 1 Divyasundar Sahu Delhi divyasundar sahu@gmail. com Update 2 Hritika Sahu Pune hritika@gma il.com Update 3 Milan Jena Chennai milanjena@ gmail.com Update
  • 55. 4. Delete Data From Oracle using JSP Index.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <%@ page import="java.sql.*" %> <%@ page import="java.io.*" %> <% try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); } catch (ClassNotFoundException e) { e.printStackTrace(); } %> <html> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <body> <h1>Retrieve data from database in jsp</h1> <table border="1"> <tr> <td>id</td> <td>first name</td> <td>last name</td> <td>City name</td> <td>Email</td> <td>update</td> </tr>
  • 56. <% try{ String sql ="select * from users"; ResultSet resultSet = statement.executeQuery(sql); int i=0; while(resultSet.next()){ %> <tr> <td><%=resultSet.getString("first_name") %></td> <td><%=resultSet.getString("last_name") %></td> <td><%=resultSet.getString("city_name") %></td> <td><%=resultSet.getString("email") %></td> <td><a href="delete.jsp?id=<%=resultSet.getString("id") %>"> <button type="button" class="delete">Delete</button> </a> </td></tr> <% i++; } connection.close(); } catch (Exception e) { e.printStackTrace(); } %> </table> </body> </html>
  • 57. delete.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*,java.util.*"%> <% String id=request.getParameter("id"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement st=conn.createStatement(); int i=st.executeUpdate("DELETE FROM users WHERE id="+id); out.println("Data Deleted Successfully!"); } catch(Exception e) { System.out.print(e); e.printStackTrace(); } %>
  • 58. 5. JSP login And Sign Up Form With Session index.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>login</title> </head> <body> <form action="login.jsp" method="post"> User name :<input type="text" name="usr" /><br> password :<input type="password" name="password" /><br> <input type="submit" /> </form> <p>New user. <a href="register.html">Login Here</a>. </body> </html>
  • 59. login.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*,java.util.*"%> <% String userid=request.getParameter("userid"); session.putValue("userid",userid); String password=request.getParameter("password"); Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement st= con.createStatement(); ResultSet rs=st.executeQuery("select * from users where userid='"+userid+"' and password='"+password+"'"); try{ rs.next(); if(rs.getString("password").equals(password)&&rs.getString(" userid").equals(userid)) { out.println("Welcome " +userid); } else{ out.println("Invalid password or username."); } } catch (Exception e) { e.printStackTrace(); } %>
  • 60. register.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>new registration</title> </head> <body> <form action="reg-process.jsp" method="post"> First name :<input type="text" name="fname" /> Last name :<input type="text" name="lname" /> Email ID :<input type="text" name="email" /> User name :<input type="text" name="userid" /> password :<input type="password" name="password" /> <input type="submit" /> </form> </body> </html>
  • 61. reg-process.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*,java.util.*"%> <% String fname=request.getParameter("fname"); String lname=request.getParameter("lname"); String email=request.getParameter("email"); String userid=request.getParameter("userid"); String password=request.getParameter("password"); try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement st=conn.createStatement(); int i=st.executeUpdate("insert into users(fname,lname,email,userid,password)values('"+fname+"','"+lname+"','"+email+"','"+userid+"','"+password+"')"); out.println("Thank you for register ! Please <a href='index.html'>Login</a> to continue."); } catch(Exception e) { System.out.print(e); e.printStackTrace(); } %>
  • 62. 6.Check duplicate userid or email ID before register JSP register.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>new registration</title> </head> <body> <form action="reg-process.jsp" method="post"> First name :<input type="text" name="fname" /> Last name :<input type="text" name="lname" /> Email ID :<input type="text" name="email" /> User name :<input type="text" name="userid" /> password :<input type="password" name="password" /> <input type="submit" /> </form> </body> </html>
  • 63. reg-process.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1“ pageEncoding="ISO-8859-1"%> <%@ page import="java.sql.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Count Rows JSP</title> </head> <body> <% try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement st=con.createStatement(); String fname=request.getParameter("fname"); String lname=request.getParameter("lname"); String email=request.getParameter("email"); String userid=request.getParameter("userid"); String password=request.getParameter("password"); String strQuery = "SELECT COUNT(*) FROM users where email='"+email+"'"; ResultSet rs = st.executeQuery(strQuery); rs.next(); String Countrow = rs.getString(1);out.println(Countrow); if(Countrow.equals("0")){ int i=st.executeUpdate("insert into users(fname,lname,email,userid,password)values('"+fname+"','"+lname+"','"+email+"','"+userid+"','"+password+"')"); } else{ out.println("User name or Email already exists !"); } } catch (Exception e){ e.printStackTrace(); } %> </body> </html>
  • 64. 7. Change password in JSP In this example my current password is "Admin@123" and i am going to change into as "Admin@12345". login.sql CREATE TABLE `login` ( `id` int(10) NOT NULL, `currentPassword` varchar(10) DEFAULT NULL, `Newpass` varchar(10) DEFAULT NULL, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1
  • 65. index.html <html> <form action="changePassword.jsp" method="post"> <table> <tr><td>Current Password</td><td><input type="password" name="current" ></td></tr> <tr><td>New Password</td><td><input type="password" name="new"></td></tr> <tr><td>Confirm Password</td><td><input type="password" name="confirm"></td></tr> <tr><td><input type="submit" value="Change Password"></td></tr> </table> </form> </html>
  • 66. changePassword.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <%@page import="java.sql.*"%> <%@page import="java.io.*"%> <% String currentPassword=request.getParameter("current"); String Newpass=request.getParameter("new"); String conpass=request.getParameter("confirm"); int id=0; try{ Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement st=con.createStatement(); ResultSet rs=st.executeQuery("select * from login where password='"+currentPassword+"'"); while(rs.next()){ id=rs.getInt(1); pass=rs.getString(3); } System.out.println(id+ " "+pass); if(pass.equals(currentPassword)){ Statement st1=con.createStatement(); int i=st1.executeUpdate("update login set password='"+Newpass+"' where id='"+id+"'"); out.println("Password changed successfully"); st1.close(); con.close(); } else{ out.println("Invalid Current Password"); } } catch(Exception e){ out.println(e); } %>
  • 67. 8. Forgot password JSP index.html <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Forgot Password JSP</title> </head> <body> <h1>Forgot Password</h1> <form action="forgot-process.jsp" method="post"><br><br> Enter Email ID:<input type="text" name="email" /><br><br> <input type="submit" /> </form> </body> </html>
  • 68. forgot-process.jsp <%@ page language="java" contentType="text/html; charset=ISO-8859-1"pageEncoding="ISO-8859-1"%> <%@ page import="java.sql.*" %> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Count Rows JSP</title> </head> <body> <% try { Class.forName("oracle.jdbc.driver.OracleDriver"); Connection connection=DriverManager.getConnection( “jdbc:oracle:thin:@localhost:1521:xe","system",“oracle"); Statement st=con.createStatement(); String email=request.getParameter("email"); String strQuery = "SELECT password FROM users where email='"+email+"'"; ResultSet rs = st.executeQuery(strQuery); rs.next(); String Countrow = rs.getString(1); if(Countrow.equals("1")){ /*mail code paste your mail code here ------------------ Mail code*/ out.println("Password send to your email id successfully !"); } else{ out.println("Invalid Email Id !"); } } catch (Exception e){ e.printStackTrace(); } %> </body>
  • 69. 9. How to insert image in Oracle database using JSP