0% found this document useful (0 votes)
2 views101 pages

Unit-4 - Java Server Pages

The document provides an overview of Java Server Pages (JSP), detailing its role in developing dynamic web content by embedding Java code within HTML. It compares JSP with servlets, highlighting advantages such as automatic recompilation and separation of logic and presentation. Additionally, it outlines the JSP lifecycle, processing steps, scripting elements, directives, and implicit objects available in JSP.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views101 pages

Unit-4 - Java Server Pages

The document provides an overview of Java Server Pages (JSP), detailing its role in developing dynamic web content by embedding Java code within HTML. It compares JSP with servlets, highlighting advantages such as automatic recompilation and separation of logic and presentation. Additionally, it outlines the JSP lifecycle, processing steps, scripting elements, directives, and implicit objects available in JSP.
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Advanced java Programming

GTU #3160707

Unit-4
Java Server Pages
Subject Overview
Sr. No. Unit % Weightage
1 Java Networking 5
2 JDBC Programming 10
3 Servlet API and Overview 25
4 Java Server Pages 25
5 Java Server Faces 10
6 Hibernate 15
7 Java Web Frameworks: Spring MVC 10

Reference Book:
Professional Java Server Programming by Subrahmanyam Allamaraju, Cedric
Buest Wiley Publication

# 3160707  Unit 4 – Java Server Pages 2


What is Java Server Pages (JSP)?
 Java Server Pages (JSP) is a technology for developing web pages that support dynamic
content.
 It helps to insert java code in HTML pages by making use of special JSP tags.
Example
<% …JSP Tag… %>

 JSP is a server-side program that is similar in design and functionality to java servlet.
 A JSP page consists of HTML tags and JSP tags.
 JSP pages are saved with .jsp extension

# 3160707  Unit 4 – Java Server Pages 3


Comparing JSP with Servlet
JSP Servlet
JSP is a webpage scripting language that generates Servlets are Java programs that are already compiled which
dynamic content. also creates dynamic web content.
A JSP technically gets converted to a servlet We embed the A servlet is a java class.
java code into HTML. We can put HTML into print statements.
E.g. <html> <% java code %> </html> E.g. [Link](“<html code>”);
JSPs are extension of servlets which minimizes the effort A servlet is a server-side program and written purely on
of developers to write User Interfaces using Java Java.
programming.
JSP runs slower than servlet. Servlets run faster than JSP
As, it has the transition phase for converting from JSP to a
Servlet. Once it is converted to a Servlet then it will start
the compilation
In MVC architecture JSP acts as view. In MVC architecture Servlet acts as controller.
We can build custom tags using JSP API We cannot build any custom tags in servlet.

# 3160707  Unit 4 – Java Server Pages 4


Advantages of JSP over Servlets
 JSP needs no compilation. There is automatic deployment of a JSP, recompilation is done
automatically when changes are made to JSP pages.
 In a JSP page visual content and logic are separated, which is not possible in a servlet.
 i.e. JSP separates business logic from the presentation logic.
 Servlets use println statements for printing an HTML document which is usually very difficult to
use. JSP has no such tedious task to maintain.

# 3160707  Unit 4 – Java Server Pages 5


Life Cycle of JSP
 A JSP life cycle can be defined as the entire process from its creation till the destruction.
 It is similar to a servlet life cycle with an additional step which is required to compile a JSP into
servlet.
 A JSP page is converted into Servlet in order to service requests.
 The translation of a JSP page to a Servlet is called Lifecycle of JSP.

# 3160707  Unit 4 – Java Server Pages 6


Life Cycle of JSP
Called only
once

jspInit()

Request
_jspService() Handles multiple
request/response
Response

jspDestroy()
Called only
once

# 3160707  Unit 4 – Java Server Pages 7


Life Cycle of JSP
 JSP Lifecycle steps
1. Translation of JSP to Servlet code.
2. Compilation of Servlet to bytecode.
3. Loading Servlet class.
4. Creating servlet instance.
5. Initialization by calling jspInit() method
6. Request Processing by calling _jspService() method
7. Destroying by calling jspDestroy() method

# 3160707  Unit 4 – Java Server Pages 8


Life Cycle of JSP
1. Web Container translates JSP code into a servlet source(.java) file.
2. Then compiles that into a java servlet class (bytecode).
3. In the third step, the servlet class bytecode is loaded using classloader in web container.
4. The Container then creates an instance of that servlet class.
5. The initialized servlet can now service request.
6. For each request the Web Container call the _jspService() method.
7. When the Container removes the servlet instance from service, it calls
the jspDestroy() method to perform any required clean up.

# 3160707  Unit 4 – Java Server Pages 9


JSP Processing
Web Server

Step:1
[Link] hello_jsp.java
Translation Step:2
from .jsp to Compilation of
servlet(.java) Servlet to bytecode
Web Container
Loading Servlet Class Step:3

Creating Servlet Step:4


Instance
Step:5
jspInit() hello_jsp.class
Step:6
_jspService()

Step:7
jspDestroy()

# 3160707  Unit 4 – Java Server Pages 10


JSP Processing
 The following steps explain how the web server creates the web page using JSP:
 Web browser sends an HTTP request to the web server requesting JSP page. E.g. [Link]
 Web server recognizes that the HTTP request by web browser is for JSP page by checking the extension of
the file (i.e .jsp)
 Web server forwards HTTP Request to JSP engine.
 The JSP engine loads the JSP page from disk and converts it into a servlet content.
 The JSP engine compiles the servlet into an executable class and forwards the original request to a servlet
engine.
 Servlet engine loads and executes the Servlet class.
 Servlet produces an output in HTML format.
 Output produced by servlet engine is then passes to the web server inside an HTTP response.
 Web server sends the HTTP response to Web browser in the form of static HTML content.
 Web browser loads the static page into the browser and thus user can view the dynamically generated page.

# 3160707  Unit 4 – Java Server Pages 11


JSP Processing
 Translation Time
 Time taken to generate Java Servlet (.java) from .jsp file is termed as Translation Time.

 Request Time
 Time taken to invoke a Servlet to handle an HTTP request is termed as Request Time.

# 3160707  Unit 4 – Java Server Pages 12


JSP Elements
JSP Element

JSP Directives JSP Scripting Elements Actions


page <jsp:param>
include <jsp:include>
Traditional Modern <jsp:forward>
scriptlet <jsp:plugin>
EL Scripting
expression
declaration
comments
(html, jsp,java)

# 3160707  Unit 4 – Java Server Pages 13


JSP Scripting Elements
 The scripting elements provides the ability to insert java code inside the jsp.
 There are three types of traditional scripting elements:
 scriptlet tag
 expression tag
 declaration tag JSP Scripting Elements

Traditional Modern
scriptlet
EL Scripting
expression
declaration
comments
(html, jsp,java)

# 3160707  Unit 4 – Java Server Pages 14


scriptlet
 A scriptlet tag is used to execute java source code in JSP.
 A scriptlet can contain
 Any number of JAVA language statements
 Variable
 Method declarations
 Expressions that are valid in the page scripting language

Syntax
<% // java source code %>

Example
<% [Link]("welcome to jsp"); %>
<% int a=10; %>

# 3160707  Unit 4 – Java Server Pages 15


scriptlet
 Everything written inside the scriptlet tag is compiled as java code.
 JSP code is translated to Servlet code, in which _jspService() method is executed which has
HttpServletRequest and HttpServletResponse as argument.
 JSP page can have any number of scriptlets, and each scriptlets are appended in _jspService ().
[Link]
1 <html>
2 <body>
3 <%[Link]("Hello World! My First JSP Page");%>
4 </body>
5 </html>

# 3160707  Unit 4 – Java Server Pages 16


expression
 The code placed within JSP expression tag is written to the output stream of the response.
 So you need not write [Link]() to write data.
 It is mainly used to print the values of variable or method.
Syntax
<%=statement %>

Example turns out as


<%= (2*5) %> [Link]((2*5));

 Do not end the statement with semicolon in case of expression tag.

# 3160707  Unit 4 – Java Server Pages 17


declaration
 The JSP declaration tag is used to declare variables and methods
 The declaration of jsp declaration tag is placed outside the _jspService() method.
Syntax
<%! variable or method declaration %>

Example
<%! int a = 10; %>
<%! int a, b, c; %>
<%! Circle a = new Circle(2.0); %>

# 3160707  Unit 4 – Java Server Pages 18


comments
 The comments can be used for documentation.
 This JSP comment tag tells the JSP container to ignore the comment part from compilation.
Syntax
<%-- comments --%>

JSP comment <%-- jsp comment --%>


Java comment /* java comment */ or
// for single line
Html comment <!-- html comment -->

# 3160707  Unit 4 – Java Server Pages 19


Scripting Elements: Example
[Link]
1 <html>
2 <body>
3 <%-- comment:JSP Scipting elements --%>
4 <%! int i=0; %> declaration
5 <% i++; %> scriptlet
6 Welcome to world of JSP!
7 <%= "This page has been accessed " + i + " times" %> expression
8 </body>
9 </html>

# 3160707  Unit 4 – Java Server Pages 20


JSP Elements
JSP Element

JSP Directives JSP Scripting Elements Actions


page <jsp:param>
include <jsp:include>
Traditional Modern <jsp:forward>
scriptlet <jsp:plugin>
EL Scripting
expression
declaration
comments
(html, jsp,java)

# 3160707  Unit 4 – Java Server Pages 21


page directive
 The page directive defines attributes that apply to an entire JSP page.
 You may code page directives anywhere in your JSP page.
 By convention, page directives are coded at the top of the JSP page.

Syntax
<%@page attribute="value" %>

Example
<%@page import="[Link],[Link],[Link].*" %>
<%@page contentType="text/html; charset=US-ASCII" %>

# 3160707  Unit 4 – Java Server Pages 22


Attributes of JSP page directive
 import Used to import class, interface or all the
 contentType members of a package
<%@ page import="[Link]" %>
 extends Today is: <%= new Date() %>
The contentType attribute defines the MIME type of
 Info the HTTP response. The default value is
"text/html;charset=ISO-8859-1".
<%@ page contentType=application/msword %>

The extends attribute defines the parent class that


will be inherited by the generated servlet
This
<%@ attribute simply sets the information of the
page extends="[Link]" %> JSP
page which is retrieved later by using
getServletInfo() .
<%@ page info=“Authored by : AuthorName" %>

# 3160707  Unit 4 – Java Server Pages 23


page directive
 buffer The buffer attribute sets the buffer size in kb to
 language handle output generated by the JSP page.
The default size of the buffer is 8Kb.
 isELIgnored <%@ page buffer="16kb" %>
 autoFlush
The language attribute specifies the scripting
language used in the JSP page. The default value is
"java".
<%@ page language="java" %>
We can ignore the Expression Language (EL) in jsp
by the isELIgnored attribute. By default its value is
false i.e. EL is enabled by default.
<%@ page isELIgnored="true" %>//Now EL will be ignored
The autoFlush attribute specifies whether buffered
output should be flushed automatically when the
buffer is [Link] it is true.
<%@ page autoFlush="true" %>
# 3160707  Unit 4 – Java Server Pages 24
page directive
 isThreadSafe This option marks a page as being thread-safe. By default,
all JSPs are considered thread-safe(true). If you set the
 session
isThreadSafe = false, the JSP engine makes sure that only
 pageEncoding one thread at a time is executing your JSP.
<%@ page isThreadSafe ="false" %>
 errorPage
The session attribute indicates whether or not the JSP page
 isErrorPage uses HTTP sessions.
<%@ page session="true" %>//Bydefault it is true
We can set response encoding type with this page directive
attribute, its default value is “ISO-8859-1”.
<%@ page pageEncoding ="US-ASCII" %>
It is used to define the error page, if exception occurs in the current
page, it will be redirected to the error page.
<%@ page errorPage="[Link]" %>
The isErrorPage attribute is used to declare that the current page is
the error page.
<%@ page isErrorPage="true" %>

# 3160707  Unit 4 – Java Server Pages 25


JSP Elements
JSP Element

JSP Directives JSP Scripting Elements Actions


page <jsp:param>
include <jsp:include>
Traditional Modern <jsp:forward>
scriptlet <jsp:plugin>
EL Scripting
expression
declaration
comments
(html, jsp,java)

# 3160707  Unit 4 – Java Server Pages 26


include directive
 JSP include directive is used to include the contents of another file to the current JSP page
during translation time.
 The included file can be HTML, JSP, text files etc.
 Advantage of Include directive
 Code Reusability
Syntax
<%@ include attribute= "value" %>

Example
<%@ include file="[Link]" %>

# 3160707  Unit 4 – Java Server Pages 27


Jsp Implicit Objects
 There are 9 jsp implicit objects.
 These objects are created by the web container that are available to all the jsp pages.
Implicit Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
session HttpSession
pageContext PageContext
page Object
application ServletContext
exception Throwable

# 3160707  Unit 4 – Java Server Pages 28


Jsp Implicit Objects: out
 For writing any data to the buffer, JSP provides an implicit object named out.
 It is an object of JspWriter.

Servlet
PrintWriter out= [Link]();
[Link](“text/html”);
[Link](“DIET”);

JSP
<html>
<body>
<% [Link](“DIET”); %>
</body>
</html>

# 3160707  Unit 4 – Java Server Pages 29


Jsp Implicit Objects: request
 Instance of [Link] object associated with the request.
 Each time a client requests a page the JSP engine creates a new object to represent that
request.
 The request object provides methods to get HTTP header information including from data,
cookies, HTTP methods etc.
[Link]
1 <form action=”[Link]">
2 Login:<input type="text" name="login">
3 <input type="submit" value="next">
4 </form>

[Link]
1 hello,
2 <%
3 [Link]([Link]("login"));
4 %>

# 3160707  Unit 4 – Java Server Pages 30


Jsp Implicit Objects: response
 The response object is an instance of a [Link] object.
 Through this object the JSP programmer can add new cookies or date stamps, HTTP status
codes, redirect response to another resource, send error etc.
[Link]
1 <form action="[Link]">
2 <input type="text" name="login">
3 <input type="submit" value="next">
4 </form>

[Link]
1 <%
2 [Link]("[Link]");
3 %>

# 3160707  Unit 4 – Java Server Pages 31


Jsp Implicit Objects: config
 The config is an implicit object of type [Link].
 This object can be used to get initialization parameter for a particular JSP page.
[Link]
1 <form action="MyConfig">
2 Login:<input type="text" name="login">
3 <input type="submit" value="sign_in">
4 </form>
[Link]
1 <servlet>
2 <servlet-name>MyConfig</servlet-name>
3 <jsp-file>/[Link]</jsp-file>
4 <init-param>
5 <param-name>College</param-name>
6 <param-value>DIET</param-value>
7 </init-param>
8 </servlet>
9 <servlet-mapping>
10 <servlet-name>MyConfig</servlet-name>
11 <url-pattern>/MyConfig</url-pattern>
12 </servlet-mapping>

# 3160707  Unit 4 – Java Server Pages 32


Jsp Implicit Objects: config
[Link]
1 <%
2 [Link]("Welcome "+[Link]("login"));
3 String c_name=[Link]("College");
4 [Link]("<p>College name is="+c_name+"</p>");
5 %>

# 3160707  Unit 4 – Java Server Pages 33


Jsp Implicit Objects: session
 In JSP, session is an implicit object of type [Link] .
 The Java developer can use this object to set, get or remove attribute or to get session
information.
[Link]
1 <form action="[Link]">
2 <input type="text" name="uname">
3 <input type="submit" value="go"><br/>
4 </form>

# 3160707  Unit 4 – Java Server Pages 34


Jsp Implicit Objects: session
[Link]
1 <html>
2 <body>
3 <%
4 String name=[Link]("uname");
5 [Link]("Welcome "+name);
6 [Link]("user",name);
7 %>
8 <a href="[Link]">next page</a>
9 </body>
10 </html>

[Link]
1 <html>
2 <body>
3 <%
4 String name = (String)[Link]("user");
5 [Link]("Hello "+name);
6 %>
7 </body>
8 </html>

# 3160707  Unit 4 – Java Server Pages 35


Jsp Implicit Objects: pageContext
 The pagecontect object is Instance of [Link]
 The pageContext object can be used to set, get or remove attribute.
 The PageContext class defines several fields, including PAGE_SCOPE, REQUEST_SCOPE,
SESSION_SCOPE, and APPLICATION_SCOPE, which identify the four scopes.
[Link]
1 <%
2 [Link]("user","name",PageContext.APPLICATION_SCOPE);
3 %>
4 <a href="[Link]">next page</a>

[Link]
1 <%
2 String name= (String)[Link]("user",PageContext.APPLICATION_SCOPE);
3 [Link]("Hello "+name); %>

# 3160707  Unit 4 – Java Server Pages 36


Jsp Implicit Objects: page
 This object is an actual reference to the instance of the page.
 It is an instance of [Link]
 Direct synonym for the this object.
returns the name of generated servlet file
<%= [Link]().getName() %>

# 3160707  Unit 4 – Java Server Pages 37


Jsp Implicit Objects: application
 Instance of [Link]
 The instance of ServletContext is created only once by the web container when application or
project is deployed on the server.
 This object can be used to get initialization parameter from configuration file ([Link]).
 This initialization parameter can be used by all jsp pages.
[Link]
1 <%
2 //refers to context parameter of [Link]
3 String driver=[Link]("name");
4 [Link]("name is="+driver);
5 %>

# 3160707  Unit 4 – Java Server Pages 38


Jsp Implicit Objects: exception
 exception is an implicit object of type [Link] class.
 This object can be used to print the exception.
 But it can only be used in error pages.

[Link]
1 <%@ page isErrorPage="true" %>
2 <html>
3 <body>
4 Sorry following exception occured:<%=exception %>
5 </body>
6 </html>

# 3160707  Unit 4 – Java Server Pages 39


JSP Elements
JSP Element

JSP Directives JSP Scripting Elements Actions


page <jsp:param>
include <jsp:include>
Traditional Modern <jsp:forward>
scriptlet <jsp:plugin>
EL Scripting
expression
declaration
comments
(html, jsp,java)

# 3160707  Unit 4 – Java Server Pages 40


Actions
 JSP actions use constructs in XML syntax to control the behavior of the servlet engine.
 We can dynamically insert a file, reuse JavaBeans components, forward the user to another
page, or generate HTML for the Java plugin.

Syntax
<jsp:action_name attribute="value" />

# 3160707  Unit 4 – Java Server Pages 41


<jsp:param>
 This action is useful for passing the parameters to other JSP action tags such as JSP include &
JSP forward tag.
 This way new JSP pages can have access to those parameters using request object itself.
Syntax
<jsp:param name ="name" value="value" />

Example
<jsp:param name ="date" value="12-02-2018" />
<jsp:param name ="time" value="10:15AM" />
<jsp:param name ="data" value="ABC" />

# 3160707  Unit 4 – Java Server Pages 42


<jsp:include>
 The jsp:include action tag is used to include the content of another resource it may be jsp, html
or servlet.
 The jsp:include tag can be used to include static as well as dynamic pages
Attribute Description
page The relative URL of the page to be included.
flush The boolean attribute determines whether the included resource has its buffer flushed before it
is included. By default value is false.

Syntax
<jsp:include page="relative URL" flush="true" />

Example
<jsp:include page="[Link]" flush="true">
<jsp:param name="roll_no1" value="401" />
</jsp:include>

# 3160707  Unit 4 – Java Server Pages 43


<jsp:forward>
 Forwards the request and response to another resource.

Syntax
<jsp:forward page="Relative URL" />

Example
<jsp:forward page="[Link]">
<jsp:param name="roll_no" value="301" />
</jsp:forward>

# 3160707  Unit 4 – Java Server Pages 44


<jsp:plugin>
 This tag is used when there is a need of a plugin to run a Bean class or an Applet.
 The <jsp:plugin> action tag is used to embed applet in the jsp file.
 The <jsp:plugin> action tag downloads plugin at client side to execute an applet or bean.
Syntax
<jsp:plugin type="applet|bean" code="nameOfClassFile" codebase= "URL" />

[Link]
import [Link].*; [Link]
import [Link].*; <html> <body>
public class MyApplet extends Applet { <jsp:plugin
type="applet"
public void paint(Graphics g) {
code="[Link]"
[Link]("Welcome in Java Applet.",40,20); codebase="/JSPClass/MyApplet"/>
}} </body></html>

# 3160707  Unit 4 – Java Server Pages 45


JSP Element

JSP Directives JSP Scripting Elements Actions


page <jsp:param>
include <jsp:include>
Traditional Modern <jsp:forward>
scriptlet <jsp:plugin>
EL Scripting
expression
declaration
comments
(html, jsp,java)

# 3160707  Unit 4 – Java Server Pages 46


EL Scripting
 Expression Language(EL) Scripting.
 It is the newly added feature in JSP technology version 2.0.
 The purpose of EL is to produce script less JSP pages.
Syntax
${expr}

Example

EL output
${a=10} 10
${10+20} 30
${20*2} 40
${10==20} false
${'a'<'b'} true

# 3160707  Unit 4 – Java Server Pages 47


EL Implicit Object
pageScope It is used to access the value of any variable which is set in the Page scope
requestScope It is used to access the value of any variable which is set in the Request scope.
sessionScope It is used to access the value of any variable which is set in the Session scope
applicationScope It is used to access the value of any variable which is set in the Application
scope.
pageContext It represents the PageContext object.
param Map a request parameter name to a single value
paramValues Map a request parameter name to corresponding array of string values.
header Map containing header names and single string values.
headerValues Map containing header names to corresponding array of string values.
cookie Map containing cookie names and single string values.

# 3160707  Unit 4 – Java Server Pages 48


EL Implicit Object
 An expression can be mixed with static text/values and can also be combined with other
expressions
Example
${[Link]}
${[Link]}

# 3160707  Unit 4 – Java Server Pages 49


EL Implicit Object: Example
[Link]
<form action="[Link]">
Enter Name:<input type="text" name="name" >
<input type="submit” value="go">
</form>

[Link]
Welcome, ${ [Link] }

# 3160707  Unit 4 – Java Server Pages 50


EL Implicit Object: Example
[Link]
1 <form action="[Link]">
2 <% Cookie ck=new Cookie("c1","abc");
3 [Link](ck);
4 [Link]("sid","054"); //for session
5 %>
6 Enter Name:<input type="text" name="name" >
7 Enter Address:<input type="text" name="address" >
8 <input type="submit" value="submit">
9 </form>

[Link]
1 <p>Name is : ${[Link]}</p>
2 <p>Address is : ${[Link]}</p>
3 <p>Cookie Name : ${[Link]}</p>
4 <p>Cookie value : ${[Link]}</p>
5 <p>Session id : ${[Link]}</p>

# 3160707  Unit 4 – Java Server Pages 51


EL Implicit Object: Example
[Link]
[Link]

# 3160707  Unit 4 – Java Server Pages 52


JSP EL Operator
 JSP EL Arithmetic Operators
 Arithmetic operators are provided for simple calculations in EL expressions. They are +, -, *, / or div, % or
mod.
 JSP EL Logical Operators
 They are && (and), || (or) and ! (not).
 JSP EL Relational Operators
 They are == (eq), != (ne), < (lt), > (gt), <= (le) and >= (ge).

# 3160707  Unit 4 – Java Server Pages 53


JSP EL Important Points
 EL expressions are always within curly braces prefixed with $ sign, for example ${expr}
 We can disable EL expression in JSP by setting JSP page directive isELIgnored attribute value
to TRUE.
<%@ page isELIgnored="true" %>
 JSP EL can be used to get attributes, header, cookies, init params etc, but we can’t set the
values.
 JSP EL implicit objects are different from JSP implicit objects except pageContext
 JSP EL is NULL friendly, if given attribute is not found or expression returns null, it doesn’t
throw any exception.

# 3160707  Unit 4 – Java Server Pages 54


Exception Handling in JSP
JSP provide 3 different ways to perform exception handling:
1. Using simple try...catch block.
2. Using isErrorPage and errorPage attribute of page directive.
3. Using <error-page> tag in Deployment Descriptor.

# 3160707  Unit 4 – Java Server Pages 55


Exception Handling: try/catch block
 Using try...catch block is just like how it is used in Core Java.
[Link]
1 <html>
2 <body>
3 <%
4 try{
5 int i = 100;
6 i = i / 0;
7 [Link]("The answer is " + i);
8 }
9 catch (Exception e){
10 [Link]("An exception occurred: " + [Link]());
11 }
12 %>
13 </body>
14 </html>

# 3160707  Unit 4 – Java Server Pages 56


Exception Handling: Error Page
 Exception Handling using isErrorPage and errorPage attribute of page directive.
[Link] [Link]
<%@page errorPage= [Link]"%> <%@page isErrorPage="true" %>

[Link] [Link]
<%@page errorPage= "[Link]" %> <%@page isErrorPage="true" %>
<% int i=10; <html> <body>
i=i/0; %> An Exception had occured
<%
[Link]([Link]());%>
</body> </html>

If Exception occurs in [Link]


then forward req to [Link] This attribute designates
.jsp page as ERROR PAGE

# 3160707  Unit 4 – Java Server Pages 57


Exception Handling in JSP: [Link]
 Declaring error page in Deployment Descriptor for entire web application.
 Specify Exception inside <error-page> tag in the Deployment Descriptor.
 We can even configure different error pages for different exception types, or HTTP error code
type(503, 500 etc).
 This approach is better because we don't need to specify the errorPage attribute in each jsp
page.
 Specifying the single entry in the [Link] file will handle the exception.
 In this case, either specify exception-type or error-code with the location element.

# 3160707  Unit 4 – Java Server Pages 58


Exception Handling in JSP: [Link]
Declaring an error page for all type of exception Declaring an error page for more detailed exception
<error-page> <error-page>
<exception-type> <exception-type>
[Link] [Link]
</exception-type> </exception-type>
<location>/[Link]</location> <location>/[Link]</location>
</error-page> </error-page>

For error code


<error-page>
<error-code>404</error-code>
<location>/[Link]</location>
</error-page>

<error-page>
<error-code>500</error-code>
<location>/[Link]</location>
</error-page>

# 3160707  Unit 4 – Java Server Pages 59


JSP with JDBC
[Link]
1 <%@page import="[Link].*" %>
2 <%
3 [Link]("[Link]");
4 Connection con=[Link](
5 "jdbc:mysql://localhost:3306/GTU","root","root");
6 Statement stmt=[Link]();
7 ResultSet rs=[Link]("select * from diet");
8 while([Link]()) {
9 [Link]("<p>"+[Link](1));
10 [Link]([Link](2));
11 [Link]([Link](3)+"</p>");
12 }
13 [Link]();
14 %>

# 3160707  Unit 4 – Java Server Pages 60


JSP Session and Cookies Handling
 JSP Cookie Handling
 Cookies are text files stored on the client computer and they are kept for various information tracking
purpose.
 JSP transparently supports HTTP cookies using underlying servlet technology.

[Link] [Link]
<% Cookie cookie = new <% Cookie[] c2 = [Link]();
Cookie("c1","MyCookie1"); for(int i = 0; i < [Link]; i++) {
[Link](60 * 60); [Link]("<p>"+c2[i].getName()+"
"+ c2[i].getValue()+"</p>");
[Link](cookie);
}
%> %>
<html><body>
<a href="[Link]">Click here</a>
</body></html>

# 3160707  Unit 4 – Java Server Pages 61


JSP Session Handling
 In JSP, session is an implicit object of type HttpSession.
 The Java developer can use this object to set, get or remove attribute or to get session
information.
 In Page Directive, session attribute indicates whether or not the JSP page uses HTTP sessions.
[Link] [Link]
<%@page session="true" %> <%@page session="true" %>
<% [Link]("s1","DIET");%> <% String
<html> str=(String)[Link]("s1");
<body> [Link]("session="+str);%>
<a href="[Link]">nextPage</a>
</body>
</html>

# 3160707  Unit 4 – Java Server Pages 62


JSP - Standard Tag Library (JSTL)
 The JSP Standard Tag Library (JSTL) represents a set of tags to simplify the JSP development.
 Advantages of JSTL
 Fast Development: JSTL provides many tags that simplifies the JSP.
 Code Reusability: We can use the JSTL tags in various pages.
 No need to use scriptlet tag: It avoids the use of scriptlet tag.

For creating JSTL application, you need to load [Link] file.

# 3160707  Unit 4 – Java Server Pages 63


JSP - Standard Tag Library (JSTL)
Tag Library Function URI prefix
Core tag library Variable support [Link] c
Flow Control
Iterator
URL management
Miscellaneous
Functions Collection length [Link] fn
Library String manipulation s
Internationaliza Message formatting [Link] fmt
tion tag library Number and date
formatting
SQL tag library Database manipulation [Link] sql

XML tag library Flow control [Link] x


Transformation

# 3160707  Unit 4 – Java Server Pages 64


JSTL: Core tag library
 The core group of tags are the most frequently used JSTL tags.
 The JSTL core tag provides variable support, URL management, flow control etc.
Syntax
<%@ taglib prefix="c" uri="[Link] %>

# 3160707  Unit 4 – Java Server Pages 65


JSTL: Core tag library
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, It is the simple conditional tag that includes its body content if the evaluated condition is true.
c:when,
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.

# 3160707  Unit 4 – Java Server Pages 66


JSTL: Core tag library
1 c:out It display the result of an expression, similar to the way <%=...%> tag work.

[Link]
<%@ taglib uri= "[Link] prefix="c" %>
<html>
<body>
<c:out value="${'Welcome to JSTL'}"/>
</body>
</html>

# 3160707  Unit 4 – Java Server Pages 67


JSTL: Core tag library
2 c:import It is similar to jsp 'include', with an additional feature of including the content of any
resource either within server or outside the server.

[Link]
<%@ taglib uri= "[Link] prefix="c" %>
<html>
<body>
<c:import var="data" url="[Link]
<c:out value="${data}"/>
</body>
</html>

# 3160707  Unit 4 – Java Server Pages 68


JSTL: Core tag library
3 c:set It is used to set the result of an expression evaluated in a 'scope'. This tag is similar to
jsp:setProperty action tag.

[Link]
<%@ taglib uri= "[Link] prefix="c" %>
<html>
<body>
<c:set var="Income" scope="session" value="${4000*4}"/>
<c:out value="${Income}"/>
</body>
</html>

# 3160707  Unit 4 – Java Server Pages 69


JSTL: Core tag library
4 c:remove It is used for removing the specified scoped variable from a particular scope

[Link]
<%@ taglib uri="[Link] prefix="c" %>
<c:set var="income" scope="session" value="${4000*4}"/>
<p>Before Remove Value is: <c:out value="${income}"/></p>
<c:remove var="income"/>
<p>After Remove Value is: <c:out value="${income}"/></p>

# 3160707  Unit 4 – Java Server Pages 70


JSTL: Core tag library
5 c:if It is conditional tag used for testing the condition and display the body content only if the
expression evaluates is true.

[Link]
<%@ taglib uri="[Link] prefix="c" %>

<c:set var="income" scope="session" value="${4000*4}"/>


<c:if test="${income > 8000}">
<p>My income is: <c:out value="${income}"/></p>
</c:if>

# 3160707  Unit 4 – Java Server Pages 71


JSTL: Core tag library
6 c:catch It is used for catching any Throwable exceptions that occurs in the body and optionally exposes it.

[Link]
<%@ taglib uri="[Link] prefix="c" %>
<c:catch var ="MyException">
<% int x = 2/0;%>
</c:catch>
<c:if test = "${MyException != null}">
<p>The type of exception is : ${MyException}<br />
There is an exception: ${[Link]}</p>
</c:if>

# 3160707  Unit 4 – Java Server Pages 72


JSTL: Core tag library
7 c:choose It is a conditional tag that establish a context for mutually exclusive conditional
operations. It works like a Java switch statement in which we choose between a
numbers of alternatives.
c:when It is subtag of <choose > that will include its body if the condition evaluated be
'true'.
c:otherwise It 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>.

# 3160707  Unit 4 – Java Server Pages 73


JSTL: Core tag library
[Link]
<%@ taglib uri="[Link] prefix="c" %>

<c:set var="marks" scope="session" value="${80}"/>


<p>Your marks are: <c:out value="${marks}"/></p>
<c:choose>
<c:when test="${marks <= 35}">
Sorry! you are fail.
</c:when>
<c:when test="${marks > 75}">
Congratulations! you hold Distinction
</c:when>
<c:otherwise>
Sorry! Result is unavailable.
</c:otherwise>
</c:choose>

# 3160707  Unit 4 – Java Server Pages 74


JSTL: Core tag library
8 c:forEach It is an iteration tag used for repeating the nested body content for fixed number of times. The
< c:for each > tag is most commonly used tag because it iterates over a collection of object.

[Link]
<%@ taglib uri= "[Link] prefix="c" %>
<html> <body>

<c:forEach var="i" begin="0" end="5">


count <c:out value="${i}"/><p>
</c:forEach>

</body> </html>

# 3160707  Unit 4 – Java Server Pages 75


JSTL: Core tag library
9 c:forTokens It iterates over tokens which is separated by the supplied delimeters.

[Link]
<%@ taglib uri= "[Link] prefix="c" %>

<c:forTokens items="DIET-CE-Department" delims="-" var="name">


<c:out value="${name}"/><p>
</c:forTokens>

# 3160707  Unit 4 – Java Server Pages 76


JSTL: Core tag library
10 c:url This tag creates a URL with optional query parameter. It is used for url encoding or url
formatting. This tag automatically performs the URL rewriting operation.

[Link]
<%@ taglib uri= "[Link] prefix="c" %>
<c:url value="/[Link]"/>

# 3160707  Unit 4 – Java Server Pages 77


JSTL: Core tag library
11 c:param It allow the proper URL request parameter to be specified within URL and it automatically
perform any necessary URL encoding.

[Link]
<%@ taglib uri= "[Link] prefix="c" %>

<c:url value="/[Link]" var="completeURL">


<c:param name="CollegeCode" value="054"/>
<c:param name="Name" value="DIET"/>
</c:url>

${completeURL}

# 3160707  Unit 4 – Java Server Pages 78


JSTL: Core tag library
12 c:redirect tag redirects the browser to a new URL. It is used for redirecting the browser to an alternate URL
by using automatic URL rewriting.

[Link]
<%@ taglib uri="[Link] prefix="c" %>
<c:redirect url="[Link]

# 3160707  Unit 4 – Java Server Pages 79


JSP - Standard Tag Library (JSTL)
Tag Library Function URI prefix
Core tag library Variable support [Link] c
Flow Control
Iterator
URL management
Miscellaneous
Functions Collection length [Link] fn
Library String manipulation s
Internationalizat Message formatting [Link] fmt
ion tag library Number and date
formatting
SQL tag library Database manipulation [Link] sql

XML tag library Flow control [Link] x


Transformation
# 3160707  Unit 4 – Java Server Pages 80
JSTL -Function Tags List
 The JSTL function provides a number of standard functions, most of these functions are
common string manipulation functions.

Syntax
<%@ taglib uri="[Link] prefix="fn" %>

# 3160707  Unit 4 – Java Server Pages 81


JSTL - Function Tags List
fn:contains It is used to test if an input string containing the specified substring in a
program.
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:startsWith It is used for checking whether the given string is started with a particular
string value.
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:length It returns the number of characters inside a string, or the number of items
in a collection.
fn:indexOf It returns an index within a string of first occurrence of a specified
substring.
fn:substring It returns the subset of a string according to the given start and end
position.
fn:replace It replaces all the occurrence of a string with another string sequence.
fn:trim It removes the blank spaces from both the ends of a string.

# 3160707  Unit 4 – Java Server Pages 82


Function Tags - Example
[Link]
1 <%@ taglib uri="[Link] prefix="c" %>
2 <%@ taglib uri="[Link] prefix="fn" %>
3 <c:set var="String1" value=" Welcome to diet CE Department "/>
4
5 <c:if test="${fn:contains(String1, 'diet')}">
6 <p>Found diet string<p>
7 <p>Index of DIET : ${fn:indexOf(String1, "diet")}</p>
8 <c:set var="str2" value="${fn:trim(String1)}" />
9 <p>trim : ${str2}</p>
10 The string starts with "Welcome": ${fn:startsWith(String1, 'Welcome')}
11 <p>To UPPER CASE: ${fn:toUpperCase(String1)}</p>
12 <p>To lower case: ${fn:toLowerCase(String1)}</p>
13 </c:if>

# 3160707  Unit 4 – Java Server Pages 83


Function Tags – Example Output

# 3160707  Unit 4 – Java Server Pages 84


JSP - Standard Tag Library (JSTL)
Tag Library Function URI prefix
Core tag library Variable support [Link] c
Flow Control
Iterator
URL management
Miscellaneous
Functions Collection length [Link] fn
Library String manipulation s
Internationalizat Message formatting [Link] fmt
ion tag library Number and date
formatting
SQL tag library Database manipulation [Link] sql

XML tag library Flow control [Link] x


Transformation
# 3160707  Unit 4 – Java Server Pages 85
JSTL-Formatting tags
 The formatting tags provide support for message formatting, number and date formatting etc.
Syntax
<%@ taglib uri="[Link] prefix="fmt"%>

Formatting Tags Descriptions


fmt:parseNumber It is used to Parses the string representation of a currency, percentage or number.
fmt:formatNumber It is used to format the numerical value with specific format or precision.
fmt:formatDate It formats the time and/or date using the supplied pattern and styles.
fmt:parseDate It parses the string representation of a time and date.
fmt:setTimeZone It stores the time zone inside a time zone configuration variable.
fmt:timeZone It specifies a parsing action nested in its body or the time zone for any time formatting.

fmt:message It display an internationalized message.

# 3160707  Unit 4 – Java Server Pages 86


JSTL-Formatting tags – Example1
[Link]
1 <%@ taglib prefix="c" uri="[Link] %>
2 <%@ taglib prefix="fmt" uri="[Link]
3 %>
4 <c:set var="Amount" value="123123.456789" />
5 <h3>Parsing Number from String:</h3>
6 <fmt:parseNumber var="j" type="number" value="${Amount}" />
7 <p>Amount in parsed integer is: <c:out value="${j}" /></p>
8 <h3>Formatting of Number:</h3>
9 <p> Currency: <fmt:formatNumber value="${Amount}"
type="currency" /></p>
10 <p>maxIntegerDigits_3: <fmt:formatNumber type="number"
maxIntegerDigits="3" value="${Amount}” /></p>
11 <p>maxFractionDigits_5: <fmt:formatNumber type="number"
maxFractionDigits="6” value="${Amount}" /></p>
12 <p>pattern###.###$: <fmt:formatNumber type="number"
pattern="###.###$" value="${Amount}" /></p>

# 3160707  Unit 4 – Java Server Pages 87


JSTL-Formatting tags – Example2
[Link]
1 <%@ taglib prefix="c" uri="[Link] %>
2 <%@ taglib prefix="fmt" uri="[Link] %>
3 <c:set var="date" value="01-01-2019" />
4 <fmt:parseDate value="${date}" var="parsedDate" pattern="dd-MM-yyyy" />
5 <p>Date:<c:out value="${parsedDate}" /></p>
6 <c:set var="Date" value="<%=new [Link]()%>" />
7 <p> Formatted Time :
8 <fmt:formatDate type="time" value="${Date}" /> </p>
9 <p> Formatted Date :
10 <fmt:formatDate type="date" value="${Date}" /> </p>
11 <%-- for setting time zone --%>
12 <fmt:setTimeZone value="IST" />
13 <c:set var="date" value="<%=new [Link]()%>" />
14 <p><b>Date and Time in Indian Standard Time(IST) Zone:</b> <fmt:formatDate value="${date}"
15 type="both" timeStyle="long" dateStyle="long" /> </p>
<fmt:setTimeZone value="GMT-10" />
16 <p><b>Date and Time in GMT-10 time Zone: </b><fmt:formatDate value="${date}"
17 type="both" timeStyle="long" dateStyle="long" /> </p>

# 3160707  Unit 4 – Java Server Pages 88


JSTL-Formatting tags – Example2 - Output

# 3160707  Unit 4 – Java Server Pages 89


JSP - Standard Tag Library (JSTL)
Tag Library Function URI prefix
Core tag library Variable support [Link] c
Flow Control
Iterator
URL management
Miscellaneous
Functions Collection length [Link] fn
Library String manipulation s
Internationalizat Message formatting [Link] fmt
ion tag library Number and date
formatting
SQL tag library Database manipulation [Link] sql

XML tag library Flow control [Link] x


Transformation
# 3160707  Unit 4 – Java Server Pages 90
JSTL SQL Tags List
 The JSTL sql tags provide SQL support.
Syntax
<%@ taglib uri="[Link] prefix="sql" %>

SQL Tags Descriptions


sql:query It is used for executing the SQL query defined in its sql attribute or the body.

sql:setDataSource It is used for creating a simple data source suitable only for prototyping.

sql:update It is used for executing the SQL update defined in its sql attribute or in the tag
body.
sql:param It is used to set the parameter in an SQL statement to the specified value.
sql:dateParam It is used to set the parameter in an SQL statement to a specified
[Link] value.
sql:transaction It is used to provide the nested database action with a common connection.

# 3160707  Unit 4 – Java Server Pages 91


JSTL SQL Tags List
[Link]
1 <%@ taglib uri="[Link] prefix="c" %>
2 <%@ taglib uri="[Link] prefix="sql"%>
3 <sql:setDataSource var="db" driver="[Link]"
url="jdbc:mysql://localhost:3306/gtu" user="root" password="root"/>
4 <sql:query dataSource="${db}" var="rs">
5 SELECT * from diet;
6 </sql:query>
7 <table border="1" width="100%">
8 <tr>
9 <td>Enr_no</td> <td>Name</td> <td>Branch</td>
10 </tr>
11 <c:forEach var="table" items="${[Link]}">
12 <tr>
13 <td><c:out value="${table.Enr_no}"/></td>
14 <td><c:out value="${[Link]}"/></td>
15 <td><c:out value="${[Link]}"/></td>
16 </tr>
17 </c:forEach>
18 </table>

# 3160707  Unit 4 – Java Server Pages 92


JSP - Standard Tag Library (JSTL)
Tag Library Function URI prefix
Core tag library Variable support [Link] c
Flow Control
Iterator
URL management
Miscellaneous
Functions Collection length [Link] fn
Library String manipulation s
Internationalizat Message formatting [Link] fmt
ion tag library Number and date
formatting
SQL tag library Database manipulation [Link] sql

XML tag library Flow control [Link] x


Transformation
# 3160707  Unit 4 – Java Server Pages 93
JSTL-XML tag library
 The JSTL XML tags are used for providing a JSP-centric way of manipulating and creating XML
documents.
 The xml tags provide flow control, transformation etc.
Syntax
<%@ taglib uri="[Link] prefix="x" %>

# 3160707  Unit 4 – Java Server Pages 94


JSTL-XML tag library
XML Tags Descriptions
x:out Similar to <%= ... > tag, but for XPath expressions.
x:parse It is used for parse the XML data specified either in the tag body or an attribute.

x:set It is used to sets a variable to the value of an XPath expression.


x:choose It is a conditional tag that establish a context for mutually exclusive conditional operations.

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.

# 3160707  Unit 4 – Java Server Pages 95


JSTL-XML tag library
[Link] [Link]
1 <%@ taglib prefix="c" 15 <x:parse xml="${myBook}" var="output"/>
uri="[Link] 16 <b>Name of the Book is</b>:
ore" %> 17 <x:out
2 <%@ taglib prefix="x" select="$output/books/myBook[1]/title" />
uri="[Link] 18
ml" %> 19 <p><b>Author of the Meluha is</b>:
3 <c:set var="myBook"> 20 <x:out
4 <books> select="$output/books/myBook[2]/author" />
5 <myBook> 21 </p>
6 <title>TheSecret</title> 22 <x:set var="myTitle"
7 <author>RhondaByrne</author> select="$output/books/myBook[2]/title"/>
8 </myBook> 23
9 <myBook> 24 <p>x:set:<x:out select="$myTitle" /></p>
10 <title>Meluha</title>
11 <author>Amish</author>
12 </myBook>
13 </books>
14 </c:set>

# 3160707  Unit 4 – Java Server Pages 96


JSP Custom Tag
 A custom tag is a user-defined JSP language element.
 When a JSP page containing a custom tag is translated into a servlet, the tag is converted to
operations on an object called a tag handler.
 The Web container then invokes those operations when the JSP page's servlet is executed.
 JSP tag extensions let you create new tags that you can insert directly into a JavaServer Page
just as you would the built-in tags

# 3160707  Unit 4 – Java Server Pages 97


How to create Custom Tag?
 To create a custom tag we need three things:
 Tag handler class: In this class we specify what our custom tag will do, when it is used in a JSP
page.
 TLD file: Tag descriptor file where we will specify our tag name, tag handler class and tag
attributes.
 JSP page: A JSP page where we will be using our custom tag

JSP page TLD file Tag handler class

Defining
-Tag Name Business Logic of
Using Custom Tag -Tag handler class Tag

# 3160707  Unit 4 – Java Server Pages 98


Create the Tag handler class
 Define a custom tag named <ex:Hello>
 To create a custom JSP tag, you must first create a Java class that acts as a tag handler.
 So let us create HelloTag class.
[Link]
1 import [Link].*;
2 import [Link].*;
3 import [Link].*;
4 public class HelloTag extends SimpleTagSupport
5 {
6 public void doTag() throws JspException, IOException
7 {
8 JspWriter out = getJspContext().getOut();
9 [Link]("Hello Custom Tag!");
10 }
11 }

# 3160707  Unit 4 – Java Server Pages 99


Create TLD file
 Tag Library Descriptor (TLD) file contains information of tag and Tag Hander classes.
 It must be contained inside the WEB-INF directory.
[Link]
1 <taglib>
2 <tlib-version>1.0</tlib-version>
3 <jsp-version>2.0</jsp-version>
4 <uri>WEB-INF/tlds/[Link]</uri>
5 <tag>
6 <name>Hello</name>
7 <tag-class>[Link]</tag-class>
8 <body-content>empty</body-content>
9 </tag>
10 </taglib>

# 3160707  Unit 4 – Java Server Pages 100


JSP page
[Link]
1 <%@taglib prefix="ex" uri="WEB-INF/tlds/[Link]"%>
2 <html>
3 <body>
4 <ex:Hello/>
5 </body>
6 </html>

# 3160707  Unit 4 – Java Server Pages 101

You might also like