Advanced Java
JSP
JSP Scripting Element
JSP Scripting element are written inside <% %> tags. These code inside <% %> tags are
processed by the JSP engine during translation of the JSP page. Any other text in the JSP
page is considered as HTML code or plain text.
Example:
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body
There are five different types of scripting elements
Scripting Element Example
Comment <%-- comment --%>
Directive <%@ directive %>
Declaration <%! declarations %>
Scriptlet <% scriplets %>
Expression <%= expression %>
JSP Comment
JSP Comment is used when you are creating a JSP page and want to put in comments about
what you are doing. JSP comments are only seen in the JSP page. These comments are not
included in servlet source code during translation phase, nor they appear in the HTTP
response. Syntax of JSP comment is as follow
<%-- JSP comment --%>
Simple Example of JSP Comment
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
<%-- Code to show page count --%>
Page Count is <% out.println(++count); %>
</body
Scriptlet Tag
Scriptlet Tag allows you to write java code inside JSP page. Syntax of Scriptlet Tag is as
follows :
<% java code %>
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 1
www.vertexitservices.com
Advanced Java
Example of Scriptlet
In this example, we will show number of page visit.
<html>
<head>
<title>My First JSP Page</title>
</head>
<%
int count = 0;
%>
<body>
Page Count is <% out.println(++count); %>
</body>
</html>
Example of JSP Scriptlet Tag
In this example, we will create a simple JSP page which retrieves the name of the user from
the request parameter. The index.html page will get the username from the user.
index.html
<form method="post" action="welcome.jsp">
Name <input type="text" name="user" >
<input type="submit" value="submit">
</form>
welcome.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome Page</title>
</head>
<%
String user = request.getParameter("user");
%>
<body>
Hello, <% out.println(user); %>
</body>
</html>
Declaration Tag
Declaration tag is a block of java code for declaring class wide variables, methods and
classes. Whatever placed inside these tags gets initialized during JSP initialization phase and
has class scope. JSP container keeps this code outside of the service method (_jspService())
to make them class level variables and methods.
As we know that variables can be initialized using scriptlet too but those declaration being
placed inside _jspService() method which doesn’t make them class wide declarations. On the
other side, declaration tag can be used for defining class level variables, methods and
classes.
Syntax of declaration tag:
<%! Declaration %>
Example 1: Variables declaration
In this example we have declared two variables inside declaration tag and displayed them on
client using expressin tag.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 2
www.vertexitservices.com
Advanced Java
<html>
<head>
<title>Declaration tag Example1</title>
</head>
<body>
<%! String name="Chaitanya"; %>
<%! int age=27; %>
<%= "Name is: "+ name %><br>
<%= "AGE: "+ age %>
</body>
</html>
Output:
Example 2: Methods declaration
In this example we have declared a method sum using JSP declaration tag.
<html>
<head>
<title>Methods Declaration</title>
</head>
<body>
<%!
int sum(int num1, int num2, int num3){
return num1+num2+num3;
}
%>
<%= "Result is: " + sum(10,40,50) %>
</body>
</html>
Output:
Sum of all three integers gets displayed on the browser.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 3
www.vertexitservices.com
Advanced Java
JSP Directives – Page, Include and TagLib
Directives control the processing of an entire JSP page. It gives directions to the server
regarding processing of a page.
Syntax of Directives:
<%@ directive name *attribute name=“value” attribute name=“value” ........+%>
There are three types of Directives in JSP:
1) Page Directive
2) Include Directive
3) TagLib Directive
1) Page Directive
There are several attributes, which are used along with Page Directives and these are –
1. import
2. session
3. isErrorPage
4. errorPage
5. ContentType
6. isThreadSafe
7. extends
8. info
9. language
10. autoflush
11. buffer
1. import:
This attribute is used to import packages. While doing coding you may need to include more
than one packages, In such scenarios this page directive’s attribute is very useful as it allows
you to mention more than one packages at the same place separated by commas (,).
Alternatively you can have multiple instances of page element each one with different
package.
Syntax of import attribute –
<%@page import="value"%>
Here value is package name.
Example of import- The following is an example of how to import more than one package
using import attribute of page directive.
<%@page import="java.io.*%>
<%@page import="java.lang.*%>
<%--Comment: OR Below Statement: Both are Same--%>
<%@page import="java.io.*, java.lang.*"%>
2. session:
Generally while building a user interactive JSP application, we make sure to give access to
the user to get hold of his/her personal data till the session is active. Consider an example of
logging in into your bank account, we can access all of your data till we signout (or session
expires). In order to maintain session for a page the session attribute should be true.
This attribute is to handle HTTP sessions for JSP pages. It can have two values: true or false.
Default value for session attribute is true, which means if you do not mention this attribute,
server may assume that HTTP session is required for this page.
Default value for this attribute: true
Syntax of session attribute:
<%@ page session="value"%>
here value is either true OR false
Examples of session:
<%@ page session="true"%>
Contact:
[email protected] Call:9763 9763 33, 020-65009763 | 4
www.vertexitservices.com
Advanced Java
The above code would allow a page to have session implicit objects.
<%@ page session="false"%>
If this code is specified in a JSP page, it means session objects will not be available for that
page. Hence session cannot be maintained for that page.
3. isErrorPage:
This attribute is used to specify whether the current JSP page can be used as an error page
for another JSP page. If value of isErrorPage is true it means that the page can be used for
exception handling for another page. Generally these pages has error/warning messages OR
exception handling codes and being called by another JSP page when there is an exception
occurred there.
There is another use of isErrorPage attribute – The exception implicit objectcan only be
available to those pages which has isErrorPage set to true. If the value is false, the page
cannot use exception implicit object.
Default value: false
Syntax of isErrorPage attribute:
<%@ page isErrorPage="value"%>
Here value is either true OR false.
Example of isErrorPage:
<%@ page isErrorPage="true"%>
This makes a JSP page, a exception handling page.
4. errorPage:
As I stated above, when isErrorPage attribute is true for a particular page then it means that
the page can be called by another page in case of an exception. errorPage attribute is used
to specify the URL of a JSP page which has isErrorPage attrbute set to true. It handles the
un-handled exceptions in the page.
Syntax of errorPage attribute:
<%@ page errorPage="value"%>
Here value is a JSP page name which has exception handling code (and isErrorPage set to
true).
Example of errorPage:
<%@ page errorPage="ExceptionHandling.jsp"%>
This means if any exception occurs on the JSP page where this code has been placed, the
ExceptionHandling.jsp (this page should have isErrorPage true) page needs to be called.
5. contentType:
This attribute is used to set the content type of a JSP page.
Default value: text/html
Syntax of contentType attribute:
<%@ page contentType="value"%>
here value of content type can be anything such as: text/html, text/xml etc.
Example of contentType:
Below code can be used for text/html pages.
<%@ page contentType="text/html"%>
for text/xml based pages:
<%@ page contentType="text/xml"%>
6. isThreadSafe:
Lets understand this with an example. Suppose you have created a JSP page and mentioned
isThreadSafe as true, it means that the JSP page supports multithreading (more than one
thread can execute the JSP page simultaneously). On the other hand if it is set to false then
JSP engine won’t allow multithreading which means only single thread will execute the page
code.
Default value for isThreadSafe attribute: true.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 5
www.vertexitservices.com
Advanced Java
Syntax of isThreadSafe attribute:
<%@ page isThreadSafe="value"%>
here value can be true OR false.
Example of isThreadSafe:
<%@ page isThreadSafe="false"%>
Only one thread will be responsible for JSP page execution.
7. buffer:
This attribute is used to specify the buffer size. If you specify this to none during coding then
the output would directly written to Response object by JSPWriter. And, if you specify a
buffer size then the output first written to buffer then it will be available for response
object.
Syntax of buffer attribute:
<%@ page buffer="value"%>
value is size in kb or none.
Example of buffer:
No buffer for this page:
<%@ page buffer="none"%>
5 kb buffer size for the page, which has below code:
<%@ page buffer="5kb"%>
8. extends:
Like java, here also this attribute is used to extend(inherit) the class.
Syntax of extends attribute:
<%@ page extends="value"%>
Value is package_name.class_name.
Example of extends:
The below code will inherit the SampleClass from package: mypackage
<%@ page extends="mypackage.SampleClass"%>
9. info:
It provides a description to a JSP page. The string specified in info will return when we will
call getServletInfo() method.
Syntax of info:
<%@ page info="value"%>
here value is Message or Description
Example of info attribute:
<%@ page info="This code is given by Chaitanya Singh"%>
10. language:
It specifies the scripting language( underlying language) being used in the page.
Syntax of language:
<%@ page language="value"%>
value is scripting language here.
Example of language attribute:
<%@ page language="java"%>
11. autoFlush:
If it is true it means the buffer should be flushed whenever it is full. false will throw an
exception when buffer overflows.
Default value: True
Syntax of autoFlush:
<%@ page autoFlush="value"%>
value can be true or false.
Example of autoFlush attribute:
Buffer will be flushed out when it is full –
Contact:
[email protected] Call:9763 9763 33, 020-65009763 | 6
www.vertexitservices.com
Advanced Java
<%@ page autoFlush="true"%>
It will throw an exception when buffer is full due to overflow condition
<%@ page autoFlush="true"%>
12. isScriptingEnabled:
It has been dropped and not in use.
13. isELIgnored:
This attribute specify whether expressions will be evaluated or not.
Default value: true
Syntax of isELIgnored:
<%@ page isELIgnored="value"%>
value can be true or false.
Example of isELIgnored attribute:
Any expression present inside JSP page will not be evaluated –
<%@ page isELIgnored="false"%>
Expression will be evaluated (true is a default value so no need to specify)-
<%@ page isELIgnored="true"%>
2) Include Directive
Include directive is used to copy the content of one JSP page to another. It’s like including
the code of one file into another.
Syntax of Include Directive:
<%@include file ="value"%>
here value is the JSP file name which needs to be included. If the file is in the same directory
then just specify the file name otherwise complete URL(or path) needs to be mentioned in
the value field.
Note: It can be used anywhere in the page.
Example:
<%@include file="myJSP.jsp"%>
You can use the above code in your JSP page to copy the content of myJSP.jsp file. However
in this case both the JSP files must be in the same directory. If the myJSP.jsp is in the
different directory then instead of just file name you would need to specify the complete
path in above code.
3) Taglib Directive
This directive basically allows user to use Custom tags in JSP. we shall discuss about Custom
tags in detail in coming JSP tutorials. Taglib directive helps you to declare custom tags in JSP
page.
Syntax of Taglib Directive:
<%@taglib uri ="taglibURI" prefix="tag prefix"%>
Where URI is uniform resource locator, which is used to identify the location of custom tag
and tag prefix is a string which can identify the custom tag in the location identified by uri.
Example of Targlib:
<%@ taglib uri="http://www.sample.com/mycustomlib" prefix="demotag" %>
<html>
<body>
<demotag:welcome/>
</body>
</html>
As you can see that uri is having the location of custom tag library and prefix is identifying
the prefix of custom tag.
Note: In above example – <demotag: welcome> has a prefix demotag.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 7
www.vertexitservices.com
Advanced Java
JSP Expression Tag
Expression tag evaluates the expression placed in it, converts the result into String and send
the result back to the client through response object. Basically it writes the result to the
client(browser).
Syntax of expression tag in JSP:
<%= expression %>
JSP expression tag Examples
Example 1: Expression of values
Here we are simply passing the expression of values inside expression tag.
<html>
<head>
<title>JSP expression tag example1</title>
</head>
<body>
<%= 2+4*5 %>
</body>
</html>
Output:
Example 2: Expression of variables
In this example we have initialized few variables and passed the expression of variables in
the expression tag for result evaluation.
<html>
<head>
<title>JSP expression tag example2</title>
</head>
<body>
<%
int a=10;
int b=20;
int c=30;
%>
<%= a+b+c %>
</body>
</html>
Output:
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 8
www.vertexitservices.com
Advanced Java
Example 3: String and implicit object output
In this example we are setting up an attribute using application implicit object and then
displaying that attribute and a simple string on another JSP page using expression tag.
index.jsp
<html>
<head>
<title> JSP expression tag example3 </title>
</head>
<body>
<% application.setAttribute("MyName", "Chaitanya"); %>
<a href="display.jsp">Click here for display</a>
</body>
</html>
display.jsp
<html>
<head>
<title>Display Page</title>
</head>
<body>
<%="This is a String" %><br>
<%= application.getAttribute("MyName") %>
</body>
</html>
Output:
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 9
www.vertexitservices.com
Advanced Java
Jsp Implicit Objects
These objects are created by JSP Engine during translation phase (while translating JSP to
Servlet). They are being created inside service method so we can directly use them
within Scriptlet without initializing and declaring them. There are total 9 implicit objects
available in JSP.
Implicit Objects and their corresponding classes:
out javax.servlet.jsp.JspWriter
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
exception javax.servlet.jsp.JspException
page java.lang.Object
pageContext javax.servlet.jsp.PageContext
config javax.servlet.ServletConfig
1. Out: This is used for writing content to the client (browser). It has several methods
which can be used for properly formatting output message to the browser and for
dealing with the buffer.
2. Request: The main purpose of request implicit object is to get the data on a JSP page
which has been entered by user on the previous JSP page. While dealing with login
and signup forms in JSP we often prompts user to fill in those details, this object is
then used to get those entered details on an another JSP page (action page) for
validation and other purposes.
3. Response: It is basically used for modfying or delaing with the response which is
being sent to the client(browser) after processing the request.
4. Session: It is most frequently used implicit object, which is used for storing the user’s
data to make it available on other JSP pages till the user session is active.
5. Application: This is used for getting application-wide initialization parameters and to
maintain useful data across whole JSP application.
6. Exception: Exception implicit object is used in exception handling for displaying the
error messages. This object is only available to the JSP pages, which has isErrorPage
set to true.
7. Page: Page implicit object is a reference to the current Servlet instance (Converted
Servlet, generated during translation phase from a JSP page). We can simply
use this in place of it. I’m not covering it in detail as it is rarely used and not a useful
implicit object while building a JSP application.
8. pageContext: It is used for accessing page, request, application and session
attributes.
9. Config: This is a Servlet configuration object and mainly used for accessing getting
configuration information such as servlet context, servlet name, configuration
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 10
www.vertexitservices.com
Advanced Java
parameters etc.
Exception handling in JSP
Exception Handling in JSP is much easier than Java Technology exception handling. Although
JSP Technology also uses the same exception class object.
It is quite obvious that you dont want to show error stack trace to the guy surfing your
website. You can't prevent all errors in your application but you can atleast give an user
friendlier error response page.
Ways to perform exception handling in JSP
JSP provide two different way to perform exception handling.
1. Using isErrorPage and errorPage attribute of page directive.
2. Using <error-page> tag in Deployment Descriptor.
Example of isErrorPage and errorPage attribute
isErrorPage attribute in page directive officially appoint a JSP page as an error page.
error.jsp
errorPage attribute in page directive tells the Web Container that if an exception occur in
this page, forward the request to an error page.
sum.jsp
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 11
www.vertexitservices.com
Advanced Java
Declaring error page in Deployment Descriptor
You can also declare error pages in the DD for the entire Web Apllication.Using <error-
page> tag inDeployment Descriptor you can even configure different error pages for
different exception types, or HTTP error code type(400,500 etc.).
Declaring an error page for all type of exception
<error-page>
<exception-type>java.lang.Throwable</exception-type>
<location>/error.jsp</location>
</error-page>
Declaring an error page for more detailed exception
<error-page>
<exception-type>java.lang.ArithmeticException</exception-type>
<location>/error.jsp</location>
</error-page>
Declaring an error page based on HTTP Status code
<error-page>
<error-code>404</error-code>
<location>/error.jsp</location>
</error-page>
JSP – Architecture /Execution process of JSP Application
1. The web server needs a JSP engine ie. container to process JSP pages. The JSP
container is responsible for intercepting requests for JSP pages. This tutorial makes
use of Apache which has built-in JSP container to support JSP pages development.
2. A JSP container works with the Web server to provide the runtime environment and
other services a JSP needs. It knows how to understand the special elements that
are part of JSPs.
3. Following diagram shows the position of JSP container and JSP files in a Web
Application.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 12
www.vertexitservices.com
Advanced Java
JSP Processing:
The following steps explain how the web server creates the web page using JSP:
1. As with a normal page, your browser sends an HTTP request to the web server.
2. The web server recognizes that the HTTP request is for a JSP page and forwards it to
a JSP engine. This is done by using the URL or JSP page which ends with .jsp instead
of .html.
3. The JSP engine loads the JSP page from disk and converts it into a servlet content.
This conversion is very simple in which all template text is converted to println( )
statements and all JSP elements are converted to Java code that implements the
corresponding dynamic behavior of the page.
4. The JSP engine compiles the servlet into an executable class and forwards the
original request to a servlet engine.
5. A part of the web server called the servlet engine loads the Servlet class and
executes it. During execution, the servlet produces an output in HTML format, which
the servlet engine passes to the web server inside an HTTP response.
6. The web server forwards the HTTP response to your browser in terms of static HTML
content.
7. Finally web browser handles the dynamically generated HTML page inside the HTTP
response exactly as if it were a static page.
All the above mentioned steps can be shown below in the following diagram:
1. Typically, the JSP engine checks to see whether a servlet for a JSP file already exists
and whether the modification date on the JSP is older than the servlet. If the JSP is
older than its generated servlet, the JSP container assumes that the JSP hasn't
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 13
www.vertexitservices.com
Advanced Java
changed and that the generated servlet still matches the JSP's contents. This makes
the process more efficient than with other scripting languages (such as PHP) and
therefore faster.
2. So in a way, a JSP page is really just another way to write a servlet without having to
be a Java programming wiz. Except for the translation phase, a JSP page is handled
exactly like a regular servlet
JSP - Database Access
Check our Example
JSP - Form Processing
You must have come across many situations when you need to pass some information from
your browser to web server and ultimately to your backend program. The browser uses two
methods to pass this information to web server. These methods are GET Method and POST
Method.
1. GET method:
The GET method sends the encoded user information appended to the page request. The
page and the encoded information are separated by the ? character as follows:
http://www.test.com/hello?key1=value1&key2=value2
The GET method is the default method to pass information from browser to web server and
it produces a long string that appears in your browser's Location:box. Never use the GET
method if you have password or other sensitive information to pass to the server.
The GET method has size limitation: only 1024 characters can be in a request string.
This information is passed using QUERY_STRING header and will be accessible through
QUERY_STRING environment variable which can be handled using getQueryString() and
getParameter() methods of request object.
2. POST method:
A generally more reliable method of passing information to a backend program is the POST
method.
This method packages the information in exactly the same way as GET methods, but instead
of sending it as a text string after a ? in the URL it sends it as a separate message. This
message comes to the backend program in the form of the standard input which you can
parse and use for your processing.
JSP handles this type of requests using getParameter() method to read simple parameters
and getInputStream() method to read binary data stream coming from the client.
Reading Form Data using JSP
JSP handles form data parsing automatically using the following methods depending on the
situation:
1. getParameter(): You call request.getParameter() method to get the value of a form
parameter.
2. getParameterValues(): Call this method if the parameter appears more than once
and returns multiple values, for example checkbox.
3. getParameterNames(): Call this method if you want a complete list of all parameters
in the current request.
4. getInputStream(): Call this method to read binary data stream coming from the
client.
GET Method Example Using URL:
Here is a simple URL which will pass two values to HelloForm program using GET method.
http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI
Contact:
[email protected] Call:9763 9763 33, 020-65009763 | 14
www.vertexitservices.com
Advanced Java
Below is main.jsp JSP program to handle input given by web browser. We are going to
use getParameter() method which makes it very easy to access passed information:
<html>
<head>
<title>Using GET Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Now type http://localhost:8080/main.jsp?first_name=ZARA&last_name=ALI in your
browser's Location:box. This would generate following result:
Using GET Method to Read Form Data
First Name: ZARA
Last Name: ALI
GET Method Example Using Form:
Here is a simple example which passes two values using HTML FORM and submit button. We
are going to use same JSP main.jsp to handle this input.
<html>
<body>
<form action="main.jsp" method="GET">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Keep this HTML in a file Hello.htm and put it in <Tomcat-installation-
directory>/webapps/ROOT directory. When you would
accesshttp://localhost:8080/Hello.htm, here is the actual output of the above form.
First Name:
Last Name:
POST Method Example Using Form:
Let us do little modification in the above JSP to handle GET as well as POST methods. Below
is main.jsp JSP program to handle input given by web browser using GET or POST methods.
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 15
www.vertexitservices.com
Advanced Java
Infact there is no change in above JSP because only way of passing parameters is changed
and no binary data is being passed to the JSP program. File handling related concepts would
be explained in separate chapter where we need to read binary data stream.
<html>
<head>
<title>Using GET and POST Method to Read Form Data</title>
</head>
<body>
<center>
<h1>Using GET Method to Read Form Data</h1>
<ul>
<li><p><b>First Name:</b>
<%= request.getParameter("first_name")%>
</p></li>
<li><p><b>Last Name:</b>
<%= request.getParameter("last_name")%>
</p></li>
</ul>
</body>
</html>
Following is the content of Hello.htm file:
<html>
<body>
<form action="main.jsp" method="POST">
First Name: <input type="text" name="first_name">
<br />
Last Name: <input type="text" name="last_name" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
Now let us keep main.jsp and hello.htm in <Tomcat-installation-directory>/webapps/ROOT
directory. When you would accesshttp://localhost:8080/Hello.htm, below is the actual
output of the above form.
First Name:
Last Name:
Contact: [email protected] Call:9763 9763 33, 020-65009763 | 16
www.vertexitservices.com