Chapter-10(JSPJSTL)
Chapter-10(JSPJSTL)
©https://blogs.ashrithgn.com/
What is JSP Page?
• Java Server Pages (JSP) is a server side technology that does all the processing
at server.
• JSP have access to the entire family of Java APIs, including the JDBC API to
access enterprise databases.
• JSP is used for creating dynamic java web applications.
• Dynamic webpages are usually a mix of static and dynamic content.
• Static content can have text-based formats such as HTML, XML, etc .
• Dynamic content is generated by JSP tags using java code inside HTML .
• Static contents
• Typically static HTML page
• Same display for everyone
• Dynamic contents
• Contents is dynamically generated based on conditions
• Conditions could be
• User identity
• Time of the day
• User entered values through forms and selections
• Examples
• E-Trade webpage customized just for you, my Yahoo
<html>
<head>
<title>Sample JSP</title>
</head>
<% int sampleVar=0; %>
<body>
Count is:
<% out.println(++sampleVar); %>
</body>
</html>
• JSP • Servlet
1. JSP program is a HTML 1. Servlet is a Java program
code which supports java which supports HTML
statements too. To be more tags too.
precise, JSP embed java in 2. Generally used for
html using JSP tags. developing business
2. Used for developing layer(the complex
presentation layer of an computational code) of an
enterprise application enterprise application.
3. Frequently used for 3. Servlets are created and
designing websites and maintained by
used by web developers. Java developers.
Faculty of Computer Science
A Java Servlet : Looks like a regular Java program
https://javabeat.net/jsp-architecture-lifecycle/
Faculty of Computer Science
JSP Page Lifecycle
Destroy –
jspDestroy()
• Directives
• Actions
• Tag libraries
• JSP scripting elements are one of the most vital elements of a JSP code
<html>
<body>
<%--
Using JSP language, create a system that calculates Body Mass
Index (BMI) of users who entered their weight(lb) and height(in).
Current formula: BMI = 703*weight(lb)/height(in)^2
--%>
<form name="form" method="get" action="CommentBMI.jsp">
<pre>
Enter Weight: <input type="text" name="Weight"> lb <br>
Enter Height: <input type="text" name="Height"> in <br>
<input type="submit" value="Find BMI"> <br>
</pre> </form>
</body> Faculty of Computer Science
</html>
JSP Scriptlet
from jsp.
• A Scriptlet contains java code that is executed every time JSP is invoked.
• Expression tag is used to insert the result of a java expression directly into the
output
• It allows create expressions like arithmetic and logical.
• It can use instead of out.print() method but must not use a semicolon to end an
expression
• Syntax:
<%= expression %>
• Declaration tag allows to initialize variables or define procedures for use later in
the JSP
• It does not generate output, and is used with JSP expressions or scriptlets.
• Syntax
<%
else{
for(int i=1; i<=num; i++){
Scriptlet Tag
%>
<br>
<%=
i+"! = "+ factorial(i)
%>
Expression Tag
<%
}
}
%>
Faculty of Computer Science
FactorialFormJSP.jsp
</body>
</html>
page
directive
<%@ page attribute=“value” %>
include
directive
<%@ include file=“relative URL” %>
taglib
directive
<%@ taglib uri=“uri" prefix=“value" %>
Attributes used by page directive
No Attribute Description
1 language The scripting language used in the JSP. Currently, the only valid
(java) value is java.
2 extends Specifies the class from which the translated JSP will be inherited.
This attribute must be a fully qualified class name.
No Attribute Description
4 session Specifies whether the page participates in a session.
(true) When the page is part of a session, implicit object session is
available for use in the page.
Otherwise, using session in the scripting code results in a
translation-time error.
5 buffer Specify the size of output buffer to store servlet output before
(8kB) directed to the response object.
Set value of "none" to immediately directed servlet output to the
response object.
6 autoFlush Specifies whether to automatically flush buffered output when the
(true) buffer is full.
No Attribute Description
7 isThreadSafe Specifies whether the page can process multiple request at the
(true) same time.
8 errorPage Specifies the page to sent exception if any exceptions in the
current page are not caught.
9 isErrorPage Specifies if the current page is an error page that will be invoked
(false) in response to an error on another page.
Only the error page can use implicit object exception which
references the occurred exception.
10 contentType Specifies the MIME type of the data in the response to the client.
(text/html;
charset=ISO-
8859-1)
Faculty of Computer Science
Attributes used by page directive Con’t
No Attribute Description
11 info Simply sets the information of the JSP page which is
retrieved later by using getServletInfo() method of Servlet
interface.
12 isELIgnored Determines if Expression Language (EL) is ignored and
(false) treated as static text.
13 isScriptingEnabled Determines if the scripting elements are allowed for use.
(true) If the attribute's value is set to false, a translation-time error
will be raised if the JSP uses any scriptlets, JSP expressions
(non-EL), or JSP declarations
• <%@ page
extends=“package1.HttpJspBase” %>
• java.util.Date class and java.sql package are imported
• <%@ page import="java.util.Date, java.sql.*” %>
• JSP page participates in HTTP sessions
• <%@ page session=“true" %>
• It is used to insert the content, either static or dynamic, contained from another file to
current JSP during the translation phase
• The included content will replace the include directive statement and get translated.
• The file attribute’s value should be the relative URL of the resource from the current
JSP page
• The taglib directive declares that your JSP page uses a set of custom tags.
• When you use a custom tag, it is typically of the form <prefix:tagname> and the
prefix is the same as the prefix you specify in the taglib directive
• Basic syntax
• <%@ taglib uri=“uri" prefix=“value" %>
• Example: Using custom tag, defined with uri /my-tags, with a prefix of mtag; your
tag would be <mtag:tagName>
• <%@ taglib uri = “/my-tags" prefix = “mtag" %>
Faculty of Computer Science
Practice Application Design
main.jsp
header.jsp
h1 and green
color
create date
object and
print
footer.jsp
h3 and blue
color
Faculty of Computer Science
Practice Application: To do List
Without Parameter:
< jsp:action_name attribute=“value”/>
With Parameter:
< jsp:action_name attribute=“value”>
..... Parameter(s) .....
<jsp:acation_name/>
Faculty of Computer Science
Action tags to access JavaBean
Attribute Description
id The case sensitive name used to manipulate the Java bean with actions
<jsp:setProperty> and <jsp:getProperty>.
scope The scope in which the Java bean is accessible—page, request, session or
application. The default scope is page.
class The fully qualified class name. Java bean of this class is to be created.
Attribute Description
name The name of bean instance whose property’s value is to be set.
(id of jsp:useBean)
property Name of the property that is being set
This attribute is particularly useful for setting bean properties with specified
value value that can’t be set using request parameter. This attribute is optional.
param This attribute is useful for setting bean properties with value of request
parameter whose name is not same with property’s name.
If value and param attributes are omitted, there must be a request
parameter whose name matches with bean property name.
Attribute Description
name The name of the object instance from which the property is
obtained.
Action Description
<jsp:include> Dynamically includes another resource in a JSP. When the JSP
executes, the referenced resource is included and processed.
It allows to include both static and dynamic resource.
<jsp:forward> Forwards request processing to another JSP or servlet page.
This action terminates the current JSP’s execution.
<jsp:param> To pass additional parameter, name/value pairs of information,
to other actions for use by these actions.
Used with the include, forward and plugin actions.
<jsp:plugin> To provide support for including a Java applet in a JSP page if
you have java applets that are part of your application.
Register
Student.java
form.jsp
52
Faculty of Computer Science
register.jsp
53
Faculty of Computer Science
display.jsp
54
Faculty of Computer Science
Deployment
55
Implicit Objects
• Implicit objects are created by container during the translation phase and there is
no need for the JSP author to declare first to access these objects.
• They are made available as standard variables to scripting languages as well as to
expression language.
• Each implicit object corresponds to classes defined in Servlet
• There are nine implicit objects and created in four JSP Scopes:
page
request
session
application
Faculty of Computer Science
JSP Scopes
• Page scope
• Objects that exist only in page in which they are defined
• Each JSPh has its own instance of implicit object with page scope
• Request scope
• Objects exist for duration of client request
• Objects go out of scope after response sent to client
• Session scope
• Objects exist for duration of client’s browsing session
• Objects go out of scope when client terminates session or when
session timeout occurs
• Application scope
• Objects owned by the container application
• Any servlet or JSP can manipulate these objects
Faculty of Computer Science
Faculty of Computer Science
JSP Scopes
Demonstration
request scope
session scope
application scope
58
Page Scope Implicit Objects
No Implicit Description
Object
1 page This object is simply a synonym for the this reference for the current
JSP instance.
2 pageContext This object can be used to set, get or remove attribute to/from one of
the four scopes.
3 response This object represents the response to the client. It can be used to add
or manipulate response such as redirect response to another resource,
send error, etc.,
No Implicit Description
Object
4 out This object writes text as part of the response to a request.
This object is used implicitly with JSP expressions and JSP actions and
inserts string content in a response
5 exception This object represents the exception that is passed to the JSP error page.
This object can be used to print the exception and available only in a
JSP error page.
6 config This object represents the JSP configuration options. This object can be
used to get initialization parameter for a particular JSP page.
The config object is created by the web container for each JSP page.
pages pages
form.jsp getInfo.jsp display.jsp
63
Faculty of Computer Science
web.xml
<context-param>
<param-name>university</param-name>
<param-value>CU</param-value>
</context-param>
<welcome-file-list>
<welcome-file> form.jsp </welcome-file>
</welcome-file-list>
</web-app>
64
Faculty of Computer Science
getInfo.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1” %>
<html>
<body>
<%
String sinfo=request.getParameter("rno")+"-"+request.getParameter("name");
session.setAttribute("stuinfo",info);
//pageContext.setAttribute("stuinfo", info,pageContext.SESSION_SCOPE);
%>
<jsp:include file=“display.jsp”/>
</body> </html>
65
Faculty of Computer Science
display.jsp
out.println("Student Info:"+session.getAttribute("stuinfo")+"<br>");
out.println("Univrsity:"+application.getInitParameter("university")+"<br>");
66
Faculty of Computer Science
Deployment
67
What is Expression Language (EL) ?
Student
rno
name
uni
Student
- rno: int
- name: String
- uni: String
+ Student( )
+ Getters
+ Setters
<jsp:forward page=“display.jsp”/>
</body> </html>
</body>
</html>
index.jsp
example.jsp
Cookie(sid: session ID)
Page_Attribute(inPage:example.jsp)
Session_Attribute(subject:General)
Application_Attribute(title:Lesson One $$@@##
include $$@@@@###
Host name: 8080
Title:Lesson One
Subject: General
examples.jsp
<jsp:include page=“${inPage}”/>
</body></html>
80 Faculty of Computer Science
Practice 2: examples.jsp
• Exception is an run-time error which arises during the execution of java program.
• These are some conditions where an exception occurs:
• A user has entered invalid data.
• The file requested to be accessed does not exist in the system.
• A file that needs to be opened cannot be found.
• When the Java Virtual Machine (JVM) runs out of memory.
• Network drops in the middle of communication.
• There are mainly two types of exceptions: checked and unchecked. Here, an error
is considered as the unchecked exception.
1. IOException or Checked Exception
2. Runtime Exception or Unchecked Exception
3. Error
(3) Error
• Errors are not normally trapped form the Java programs.
• These conditions normally happen in case of severe failures, which are not handled
by the java programs.
• Errors are generated to indicate errors generated by the runtime environment.
• Example : JVM is out of Memory. Normally programs cannot recover from errors.
• The page directive in JSP provides two attributes to be used in exception handling.
They’re:
• errorPage: Used to site which page to be displayed when exception occurred.
Syntax :
<%@page errorPage="url of the error page"%>
<form action="process.jsp">
No1:<input type="text" name="n1" /><br/><br/>
No1:<input type="text" name="n2" /><br/><br/>
<input type="submit" value="divide"/> Output
</form>
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
• index.jsp and error.jsp are the same the elements of page directive
process.jsp
<%@ page errorPage="error.jsp" %>
<%
String num1=request.getParameter("n1");
String num2=request.getParameter("n2");
int a=Integer.parseInt(num1);
int b=Integer.parseInt(num2);
int c=a/b;
out.print("division of numbers is: "+c);
%>
• The JSP Standard Tag Library (JSTL) is a collection of custom tag libraries .
• Core Tag Library – looping, expression evaluation, basic input/output
• Formatting/Internationalization Tag Library – parsing data, such as dates.
• Database Tag Library – tags that can be used to access SQL databases
• XML Tag Library – tags can be used to access XML elements
• To use any of these libraries in a JSP, need to declare using the taglib directive in
the JSP page, specifying the URI and the Prefix
Core <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/core %>
XML <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/xml %>
Formatting <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/fmt %>
Database <@tablib prefix=“c” uri=“http://java.sun.com/jsp/jstl/sql %>
• A URI is a string that tells the container how to locate the TLD file for the library,
where it finds the tag file name or java class for all actions in the library
• when the web server is started
• it locates all TLD files,
• for each of them gets the default URI
• create a mapping between the URI and the TLD
• a default URI must be a globally unique string
• The JSTL <c:forEach> Core Tag is used when a block of statements is executed
again and again.
• It works same as for loop in java.
Syntax:
<c:forEach var="counterVar" begin="startValue" end="endValue">
//Block of statements
</c:forEach>
<body>
<c:forEach var = "i" begin = "1" end = "5">
Item <c:out value = "${i}"/><p>
</c:forEach>
</body>
</html>
JSTL Tag Examples
104 Faculty of Computer Science
Output Tags : <c:out>
</c:out>
<c:set> tag
• c:set allows to set the result of an expression in a variable within a given scope.
• Using this tag helps to set the property of 'JavaBean' and the values of the
'java.util.Map' object.
• JSTL <c:set> tag is similar to the <jsp:setProperty> JSP action tag
• but this JSP action tag only allows setting the bean property and cannot set the
value of a map key or create a scope variable.
Syntax
<c:set attributes />
• an example where this <c:remove> tag removes a variable from the session's scope, but first, this
variable must exist within the session. So here we are going to set a session variable using the
<c:set> tag.
Example :<c:set>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<html>
<head>
<title>Core Tag Example</title>
</head>
<body>
<c:set var="Income" scope="session" value="${4000*4}"/>
<c:out value="${Income}"/>
</body>
</html>
<c:url>
applies encoding and conversion rules for a relative or absolute URL
Rules:
URL encoding of parameters specified in <c:param> tags
context-relative path to server-relative path
add session Id path parameter for context- or page-relative path
Syntax:
<c:urlurl=“url” [context=“externalContextPath”]
[var=“var”]
scope=“page|request|session|application” >
<c:param> actions
</c:url>
• It is used for Catches any Throwable exceptions that occurs in the body and
optionally exposes it.
• In general it is used for error handling and to deal more easily with the problem
occur in program.
Syntax:
<c:catch var="<string>">
...
</c:catch>
©https://blogs.ashrithgn.com/