U-4 JSP
U-4 JSP
• #02 (Practical) Exception Handling in JSP with Arithmetic Operations | Error Page
• https://youtu.be/M42Rk-xOVMQ
• #06 Implementation of Session as JSP Implicit Object | Session Object in JSP | NetBeans Demo | RK
• https://youtu.be/eWZzltU4tpI
• #07 Create, Read and Delete Cookies in JSP | NetBeans Implementation | RK KEYNOTES
• https://youtu.be/h0zdRaFrkAk
• #08 JSP Expression Language (EL) | Implementation of Param and Cookie Implicit Object | RK KEYNOTES
• https://youtu.be/rHoAjUNV1F0
Video Content
• #09 (Practical) JSTL Core and Function Tags
• https://youtu.be/mi8eXmlhEB4
• #11 Demonstration of JSTL SQL Tags in JSP | sql:setDataSource, sql:query, c:forEach tags | MYSQL DB
• https://youtu.be/uxfU5Zu1aYs
• #12 How to Create Own Tags in JSP? | Custom Tags | Tag Handler Class | TLD File | doTag() | Taglib
• https://youtu.be/tox6mq8e8KA
• #13 (MiniProject) CRUD Operations in JSP | Action Tags, JSTL, MYSQL|Create, Retrieve, Update, Delete
• https://youtu.be/yNA04mr9sRg
Introduction to JSP
Acceptance of request
Process the request
Handling the business logic
Generation of response
2)Easy to maintain
JSP can be easily managed because we can easily separate our
business logic with presentation logic. In servlet technology, we mix
our business logic with the presentation logic.
Advantage of
JSP over
Servlet
3)Fast Development: No need to recompile and redeploy
If JSP page is modified, we don't need to recompile and redeploy
the project. The servlet code needs to be updated and recompiled
if we have to change the look and feel of the application.
2 JSP runs slower than servlet Servlet runs faster than JSP
</body>
</html>
contentType
<html>
<body>
</body>
</html>
Buffer
<html>
<body>
</body>
</html>
Example
If you want to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.
If you make it false, the web container will serialise the multiple
requests, i.e. it will wait until the JSP finishes responding to a
request before passing another request to it.
<html>
<body>
</body>
</html>
errorPage
The errorPage attribute is used to define the error page, if
exception occurs in the current page, it will be redirected to
the error page.
index.jsp
<html>
<body>
</body>
</html>
isErrorPage
The isErrorPage attribute is used to declare that the
current page is the error page.
myerrorpage.jsp
<html>
<body>
</body>
</html>
isELIgnored
We can ignore the Expression Language (EL) in jsp by the
isELIgnored attribute.
Syntax:
Extends
<html>
<body>
<%@ include file="index.html" %>
</body>
</html>
3. JSP Taglib
directive
This directive allows user to use custom tags in JSP.
The
custom tags are those that are created by user.
1. scriptlet tag
2. expression tag
3. declaration tag
1. scriptlet
tag
In JSP, java code can be written inside the jsp page using the scriptlet
tag.
Syntax:
<%
………………………………
……………………..………
%>
Example
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go">
<br/> welcome.jsp
</form> <html>
</body> <body>
</html> <%
String name=request.getParameter ("uname");
out.print("welcome "+name);
%>
</body>
</html>
2. JSP expression tag
<html>
<body>
Expression: <%= java.util.Calendar.getInstance().getTime() %>
</body>
</html>
Example
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name=“uname">
<input type="submit" value="go">
<br/>
</form>
</body> welcome.jsp
</html> <html>
<body>
</body>
</html>
3. JSP Declaration Tag
Example: index.jsp
<html>
<body>
<%! int data=50; %>
<%= "Value of the variable is:"+data %>
</body>
</html>
JSP Action Tag
The action tags are used to control the flow between pages and to
use Java Bean.
JavaBean are classes that encapsulate many objects into a single
s
object.
The JSP action tags are given
below:
FORWARD ACTION
AND PARAM TAG:
The jsp:forward action tag is used to forward the request to
another resource it may be jsp, html or another resource.
OR
<jsp:forward page="relativeURL“/>
Example
second.html
<html>
index.jsp <head>
<%@page <title>TODO supply a title</title>
contentType="text/html" </head>
pageEncoding="UTF-8"%>
<!DOCTYPE html> <body>
<html> <h1>You are in a forwarded page</h1>
<head> </body>
<title>JSP Page</title> </html>
</head>
<h1>This page contains forward</h1>
<body>
<jsp:forward page="second.html"/>
</body>
</html>
INCLUDE
ACTION
Using the <jsp:include> action we can include different files in current
jsp page. Good for dynamic pages.
index.jsp
<%@page contentType="text/html" pageEncoding="UTF-
8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type"
content="text/html; charset=UTF-8">
<title>JSP Include Tag Demo</title>
</head>
<body>
<h2>This is a index page</h2>
<jsp:include page="ShowDate.jsp"
/>
Example
ShowDate.jsp
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;
charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h3>The date and time of today is shown
below</h3>
<% out.print("Today is " + new java.util.Date()); %>
</body>
</html>
jsp:useBean action tag
Example:
index.html
<form action="useBean.jsp" method="post">
Name:<input type="text" name="name"><br>
Password:<input type="password"
name="password"><br>
Email:<input type="text" name="email"><br>
Record:<br>
<jsp:getProperty property="name" name="u"/><br>
<jsp:getProperty property="password" name="u"/><br>
<jsp:getProperty property="email" name="u" /><br>
Exampl
e
package rk;
User.jav public class User {
a private String name; private String password; private String email;
Called as
POJO // Getter method for name
class public String getName() {
return name; }
// Setter method for name
public void setName(String name) {
this.name = name; }
public String getPassword() {
return password; }
public void setPassword(String password) {
this.password = password; }
public String getEmail() {
return email; }
public void setEmail(String email) {
this.email = email; }
}
JSP implicit
Objects
The implicit objects are pre-defined variable used to
access request and application data. JSP implicit objects
are:
JSP Session
Objects
Session is an implicit object of type HttpSession. The Java developer
can use this object to set, get or remove attribute or to get session
information.
Example files required index.html, welcome.jsp , second.jsp
index.html
<html>
<body>
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go">
<br/>
</form>
</body>
</html>
JSP Session
Example
welcome.jsp
<html>
<body>
<%
String name=request.getParameter("uname");
out.print("Welcome "+name);
session.setAttribute("user",name);
%>
</body>
</html>
JSP Session
Example
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
JSP Cookie
Handling
By default, each request is considered as a new request. In cookies
technique, we add cookie with response from the Server. So cookie is
stored in the cache of the browser.
After that if request is sent by the user, cookie is added with request by
default. Thus, we recognize the user as the old user.
JSP Cookie
Handling
Cookies are small text file that are stored in the client computer. These are
basically used to keep track of user who browse the web.
The info stored in the cookie are generally name, age , id, city and so on.
The servlet container sends a set of cookies to the web browser. The browser
stores the cookies on the local machine and makes use of this information next
time when the browser is browsing the web.
Advantage of Cookies:
Simplest technique of maintaining the state.
Cookies are maintained at client side.
Disadvantage of Cookies:
It will not work if cookie is disabled from the browser.
Example: to create,
delete and read
cookies
Files needed index.html, createcookie.jsp, readcookie.jsp, deletecookie.jsp
index.html
<html>
<head>
<title>TODO supply a title</title>
</head>
<body>
</body>
</html>
Cookie in
JSP
createCookie.jsp
<body>
<%
String name = request.getParameter("name");
String city = request.getParameter("city");
readCookie.jsp
<body>
request.getCookies(); for(int i
=0;i<cookies.length;i++) //printing name and value of cookie
{ out.println("Cookie_name"+cookies[i].getName()+"<br>");
out.println("Cookie_value"+cookies[i].getValue()+"<br>");
}
%>
<a href="deletecookies.jsp">Click here</a>To delete the
cookie..!!
</body>
Example
deleteCookie.jsp
<body>
<%
Cookie nameCookie = new Cookie("name", "");
nameCookie.setMaxAge(0);
nameCookie.setValue("");
response.addCookie(nameCookie);
Syntax:
${ expression }
JSP Expression
Language
Implicit Objects Usage
pageScope it maps the given attribute name with the value set in the page scope
requestScope it maps the given attribute name with the value set in the request
scope
sessionScope it maps the given attribute name with the value set in the session
scope
applicationScope it maps the given attribute name with the value set in the application
scope
param it maps the request parameter to the single value
paramValues it maps the request parameter to an array of values
header it maps the request header name to the single value
headerValues it maps the request header name to an array of values
cookie it maps the given cookie name to the cookie value
initParam it maps the initialization parameter
pageContext it provides access to many objects request, session etc.
EL Param
Example
In this example, we have created two files index.jsp and process.jsp.
The index.jsp file gets input from the user and sends the request to
the process.jsp which in turn prints the name of the user using EL.
index.jsp
<form action="process.jsp">
Enter Name:<input type="text" name="name" />
<br/><br/>
<input type="submit" value="go"/>
</form>
process.jsp
Welcome, ${ param.name }
EL
sessionScop
e example
In this example, we printing the data stored in the session scope using
EL. For this purpose, we have used sessionScope object.
index.jsp
<a href="process.jsp">visit</a>
process.jsp
Value is ${ sessionScope.user }
EL cookie example
index.jsp
<h1>First JSP</h1>
<%
Cookie ck=new Cookie(“name”,”RK
Keynotes!”);
response.addCookie(ck);
%>
<a href="process.jsp">click</a>
process.jsp
Hello, ${cookie.name.value }
JSP DATABASE
ACCESS
index.html newjsp.jsp
……………
Database
…………..
……………
………….
Web
Browser
Example : JSP-
JDBC Files needed index.html, newjsp.jsp
<h1>STUDENT FORM:</h1>
<form action="newjsp.jsp" index.html
method="GET">
<table>
<tr>
<td>ROLL No:</td><td><input type="text" name="rollno" ></td>
</tr>
<tr>
<td>FIRST NAME:</td><td><input type="text" name="fname" ></td>
</tr>
<tr>
<td>LAST NAME:</td><td><input type="text" name="lname" ></td>
</tr>
<tr>
<td>ADDRESS:</td><td><input type="text" name="addr" ></td>
</tr>
<tr>
<td></td><td><input type="submit" value="REGISTER" ></td>
</tr>
</table>
</form>
Exampl
e
newjsp_1.jsp
String driverClassName="com.mysql.jdbc.Driver";
String url="jdbc:mysql://localhost:3306/mu";
String user="root";
String pwd="";
//Open connection
Connection con=DriverManager.getConnection(url,user,pwd);
ps.setString(1, rollno);
ps.setString(2, fname);
ps.setString(3, lname);
ps.setString(4, addr);
int p =
ps.executeUpdate();
PreparedStatement st = con.prepareStatement("select * from
student");
Example
Advantage of JSTL:
Tags Description
c:out It display the result of an expression, similar to the way <%=...%> tag work.
c:import It Retrives relative or an absolute URL and display the contents to either a String in
'var',a Reader in 'varReader' or the page.
c:set It sets the result of an expression under evaluation in a 'scope' variable.
c:remove It is used for removing the specified scoped variable from a particular scope.
c:catch It is used for Catches any Throwable exceptions that occurs in the body.
c:if It is conditional tag used for testing the condition and display the body content only if
the expression evaluates is true.
c:choose, c:when, It is the simple conditional tag that includes its body content if the evaluated
condition is true.
c:otherwise
c:forEach It is the basic iteration tag. It repeats the nested body content for fixed number of
times or over collection.
c:forTokens It iterates over tokens which is separated by the supplied delimeters.
c:param It adds a parameter in a containing 'import' tag's URL.
c:redirect It redirects the browser to a new URL and supports the context-relative URLs.
c:url It creates a URL with optional query parameters.
JSTL Core <c:out> Tag
It is used to set the result of an expression evaluated in a 'scope'. The <c:set> tag is
helpful because it evaluates theexpression anduse the result to set a value of
JavaBean.
The < c:if > tag is used for testing the condition and it display the
body
content, if the expression evaluated is true.
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<body>
<c:set var="income" scope="session" value="${4000*4}"/>
The <c:when > is subtag of <choose > that will include its body if the
condition evaluated be 'true'.
The < c:otherwise > is also subtag of < choose > it follows & <when >
tags and runs only if all the prior condition evaluated is 'false'.
The c:when and c:otherwise works like if-else statement. But it must be
placed inside c:choose tag.
Example
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:forEach var="j" begin="1" end="3">
Item <c:out value="${j}"/><p>
</c:forEach>
</body>
</html>
JSTL Core <c:redirect>
Tag
The < c:redirect > tag redirects the browser to a new URL.
The syntax used for including JSTL function library in your JSP is:
fn:containsIgnoreCase() It is used to test if an input string contains the specified substring as a case
insensitive way.
fn:endsWith() It is used to test if an input string ends with the specified suffix.
fn:escapeXml() It escapes the characters that would be interpreted as XML markup.
fn:indexOf() It returns an index within a string of first occurrence of a specified substring.
fn:trim() It removes the blank spaces from both the ends of a string.
fn:startsWith() It is used for checking whether the given string is started with a particular string
value.
fn:split() It splits the string into an array of substrings.
fn:toLowerCase() It converts all the characters of a string to lower case.
fn:toUpperCase() It converts all the characters of a string to upper case.
fn:substring() It returns the subset of a string according to the given start and end position.
fn:length() It returns the number of characters inside a string, or the number of items in a
collection.
fn:replace() It replaces all the occurrence of a string with another string sequence.
Example
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
The syntax used for including JSTL XML tags library in your JSP is:
x:when It is a subtag of that will include its body if the condition evaluated be 'true'.
x:otherwise It is subtag of that follows tags and runs only if all the prior conditions
evaluated be 'false'.
x:if It is used for evaluating the test XPath expression and if it is true, it will
processes its body content.
x:transform It is used in a XML document for providing the XSL(Extensible Stylesheet
Language) transformation.
x:param It is used along with the transform tag for setting the parameter in the XSLT
style sheet.
Formattin
g
Formatting Tags Descriptions
fmt:bundle It is used for creating the ResourceBundle objects which will be used by their tag
body.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:setBundle It loads the resource bundle and stores it in a bundle configuration variable or
the named scoped variable.
fmt:message It display an internationalized message.
fmt:formatDate It formats the time and/or date using the supplied pattern and styles.
Missing
JSTL
Library??
JSP Custom Tags
Custom tags are user-defined action tags that can be used within
Java Server Pages. A tag handler is associated with each tag to
implement the operations. Therefore, it separates the business logic
from JSP and helps avoid the use of scriptlet tags.
The key advantages of Custom tags are as follows:
1.Eliminates the need of scriptlet tag The custom tags eliminates
the need of scriptlet tag which is considered bad programming
approach in JSP.
2.Separation of business logic from JSP The custom tags separate
the the business logic from the JSP page so that it may be easy to
maintain.
3. Re-usability The custom tags makes the possibility to reuse the
same business logic again and again.
JSP Custom Tags
Custom Tags are made available within a JSP page via the taglib
directive:
<%@ taglib uri=”uri” prefix=”prefix” %>
1. Create the Tag handler class and perform action at the start or
at the end of the tag.
2. Create the Tag Library Descriptor (TLD) file and define tags
3.Create the JSP file that uses the Custom taglib defined in the
TLD file
JSP Custom Tag
Example: Create
"Hello" Tag
To write a custom tag you can simply extends SimpleTagSupport
class and override the doTag() method, where you can place
your code to generate content for the tag.
To create a custom JSP tag, you must first create a Java class
that acts as a tag handler.
JSP Custom Tag
Example: Create
"Hello" Tag
So let us create HelloTag class as //SETP
follows: 1
package myTags;
import javax.servlet.jsp.tagext.*;
import javax.servlet.jsp.*; import java.io.*;
public class HelloTag extends SimpleTagSupport {
<taglib>
<tlib-version>1.0</tlib-version>
<jsp-version>2.0</jsp-version>
<short-name>Example TLD</short-name>
<tag>
<name>Hello</name>
<tag-class>myTags.HelloTag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
JSP Custom Tag
Example: Create
"Hello" Tag
Now it's time to use above defined custom tag Hello in our JSP program(Hello.jsp)
as follows: (Note : Hello.jsp should also be saved in WEB-INF folder)
customDemo.jsp //STEP 3
<%@ taglib prefix="ex" uri="WEB-INF/custom.tld"%>
<html>
<head>
<title>A sample custom tag</title>
</head>
<body>
<ex:Hello/>
</body>
</html>
This should produce following result:
Hello Custom Tag!
Summary
• Introduction to JSP
• Comparison with Servlet
• JSP Architecture
• JSP: Life Cycle
• Scripting Elements
• Directives
• Action Tags
• Implicit Object
• Expression Language(EL)
• JSP Standard Tag Libraries(JSTL)
• Custom Tag
• Session Management
• Exception Handling
• CRUD Application
Up Next??
• Introduction to Hibernate
• Exploring Architecture of Hibernate
• Object Relation Mapping(ORM) with Hibernate
• Hibernate Annotation
• Hibernate Query Language (HQL)
• CRUD Operation using Hibernate API
END OF UNIT -
4