Day 16
Day 16
& ENGINEERING
Domain Summer Winning Camp 2024
Subject Name: Advanced Java
Day:16
Topics Covered: JSP tags, Creating dynamic web pages
using JSP
Handling Building web application using JSP
Prerequisites:
• Strong understanding of HTML, CSS, and JavaScript.
• Familiarity with Java programming language fundamentals.
• Basic knowledge of web development concepts such as HTTP, web
servers, and client-server architecture.
Objectives:
• Utilize JSP tags to embed Java code and dynamic content within
HTML pages.
• Create dynamic web pages using JSP to generate content based
on user input or database queries.
• Develop robust web applications using JSP for handling user
requests, managing session data, and interacting with databases.
• Follow best practices in JSP development to ensure code
readability, performance, and security.
Outcomes:
• Proficiency in using JSP tags to perform common tasks such as
variable interpolation, flow control, and including other resources.
• Capability to create dynamic web pages that respond to user
2
input and provide personalized content.
• Implementation of custom JSP tags to encapsulate complex logic
and promote code reusability.
What is JSP?
JSP lies in the presentation tier on the web server, with the main
responsibility of generating HTML content that needs to be
served to the browser. It also has the additional responsibility
of pass on the requests to the backend through the JavaBeans,
as and when required.
Why JSP?
1. High performance
2. Convenient to code and maintain as against servlets
3. Separates presentation from content
4. Powered by Java
– Has access to all Java APIs
– Has access to all J2EE APIsa
– Inherent Platform independence
Creating JSP in Eclipse IDE with Tomcat server
• javax.servlet.jsp package
• The javax.servlet.jsp package has two interfaces and classes.
The two interfaces are as follows:
1.JspPage
2.HttpJspPage
The classes are as follows:
• JspWriter
• PageContext
• JspFactory
• JspEngineInfo
• JspException
• JspError
• The JspPage interface
• According to the JSP specification, all the generated servlet classes must
implement the JspPage interface. It extends the Servlet interface. It provides two
life cycle methods.
Object Type
out JspWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
application ServletContext
session HttpSession
pageContext PageContext
page Object
exception Throwable
JSP out implicit object
For writing any data to the buffer, JSP provides an implicit object named out. It is the
object of JspWriter. In case of servlet you need to write.
PrintWriter out=response.getWriter();
But in JSP, you don't need to write this code.
In this example we are simply displaying date and time.
index.jsp
<html>
<body>
<% out.print("Today is:"+java.util.Calendar.getInstance().getTime()); %>
</body>
</html>
JSP request implicit object
• The JSP request is an implicit object of type HttpServletRequest i.e.
created for each jsp request by the web container.
• It can be used to get request information such as parameter, header
information, remote address, server name, server port, content type,
character encoding etc.
index.html
<form action="welcome.jsp">
<input type="text" name="uname">
<input type="submit" value="go"><br/>
</form>
welcome.jsp
<%
String name=request.getParameter("uname");
out.print("welcome "+name);
%>
• JSP response implicit object
</servlet>
String driver=config.getInitParameter("dname");
<servlet-mapping>
out.print("driver name is="+driver); <servlet-name>sonoojaiswal</servlet-
%> name>
<url-pattern>/welcome</url-pattern>
• JSP application implicit object
• In JSP, application is an implicit object of type ServletContext.
• 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 configuaration file (web.xml). It
can also be used to get, set or remove attribute from the application scope.
• This initialization parameter can be used by all jsp pages. web.xml file
<web-app>
index.html <servlet>
<servlet-name>sonoojaiswal</
<form action="welcome"> servlet-name>
<input type="text" name="uname"> <jsp-file>/welcome.jsp</jsp-
file>
<input type="submit" value="go"><br/> </servlet>
</form>
<servlet-mapping>
welcome.jsp <servlet-name>sonoojaiswal</
servlet-name>
<% <url-pattern>/welcome</url-
out.print("Welcome "+request.getParameter("uname")); pattern>
</servlet-mapping>
<context-param>
String driver=application.getInitParameter("dname"); <param-name>dname</
out.print("driver name is="+driver); param-name>
<param-
%> value>sun.jdbc.odbc.JdbcOdbcDri
ver</param-value>
</context-param>
session implicit object
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.
Example of session implicit object
Index.html Welcome.jsp
<html> <html>
<body> <body>
<form action="welcome.jsp"> <%
<input type="text" name="uname"> String name=request.getParameter("uname");
<input type="submit" value="go"><br/>
</form> out.print("Welcome "+name);
</body> session.setAttribute("user",name);
</html> <a href="second.jsp">second jsp page</
a> %>
</body>
</html>
second.jsp
<html>
<body>
<%
String name=(String)session.getAttribute("user");
out.print("Hello "+name);
%>
</body>
</html>
pageContext implicit object
error.jsp
<%@ page isErrorPage="true" %>
<html>
<body>
</body>
• In JSP, there are two ways to perform exception
handling:
1.By errorPage and isErrorPage attributes of page
directive
2.By <error-page> element in web.xml file
Example of exception handling in jsp by the elements of page
directive
In this case, you must define and create a page to handle the
exceptions, as in the error.jsp page. The pages where may occur
exception, define the errorPage attribute of page directive, as in the
process.jsp page.
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);
%>
error.jsp
<%@ page isErrorPage="true" %>
<h3>Sorry an exception occured!</h3>
Exception is: <%= exception %>
• Example of exception handling in jsp by specifying
the error-page element in web.xml file
<error-page>
<exception-type>java.lang.Exception</exception-type>
<location>/error.jsp</location>
</error-page>
</web-app>
• web.xml file if you want to handle the
exception for a specific error code
<web-app>
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>
</error-page>
</web-app>
JSP directives
The jsp directives are messages that tells the web container how to translate a
JSP page into the corresponding servlet.
</body>
</html>
contentType
• The contentType attribute defines the MIME(Multipurpose
Internet Mail Extension) type of the HTTP response.The
default value is "text/html;charset=ISO-8859-1".
</body>
</html>
extends
• The extends attribute defines the parent class that will be inherited by the generated
servlet. It is rarely used.
info
• This attribute simply sets the information of the JSP page which is retrieved later
by using getServletInfo() method of Servlet interface.
</body>
</html>
• The web container will create a method getServletInfo() in the resulting servlet.For
example:
public String getServletInfo() {
return "composed by xyz";
buffer
The buffer attribute sets the buffer size in kilobytes to handle output generated
by the JSP page. The default size of the buffer is 8Kb.
</body>
</html>
language
The language attribute specifies the scripting language used in the JSP page. The
default value is "java".
• isThreadSafe
• Servlet and JSP both are multithreaded.If you want
to control this behaviour of JSP page, you can use
isThreadSafe attribute of page directive.The value
of isThreadSafe value is true.If you make it false,
the web container will serialize the multiple
requests, i.e. it will wait until the JSP finishes
responding to a request before passing another
request to it.If you make the value of isThreadSafe
attribute like:
• <%@ page isThreadSafe="false" %>
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.
</body>
</html>
isErrorPage
The isErrorPage attribute is used to declare that the current page is the error
page.
Note: The exception object can only be used in the error page.
Example of isErrorPage attribute
//myerrorpage.jsp
<html>
<body>
</body>
</html>
Jsp Include Directive
The include directive is used to include the contents of any resource it may be
jsp file, html file or text file.
The include directive includes the original content of the included resource at
page translation time (the jsp page is translated only once so it will be better
to include static resource).
</body>
</html>
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.
action Tags
• There are many JSP action tags or elements. Each JSP action tag
is used to perform some specific tasks.
• The action tags are used to control the flow between
pages and to use Java Bean. The Jsp action tags are given
below.
JSP Action Tags Description
jsp:forward forwards the request and response to another resource.
The jsp:forward action tag is used to forward the request to another resource
it may be jsp, html or another resource.
Syntax of jsp:forward action tag without parameter
<jsp:forward page="relativeURL | <%= expression %>" />
Syntax of jsp:forward action tag with parameter
<jsp:forward page="relativeURL | <%= expression %>">
<jsp:param name="parametername" value="parametervalue
| <%=expression%>" />
</jsp:forward>
Example of jsp:forward action tag with parameter
In this example, we are forwarding the request to the printdate.jsp
file with parameter and printdate.jsp file prints the parameter value
with date and time.
index.jsp
<html>
<body>
<h2>this is index page</h2>
</body>
</html>
printdate.jsp
<html>
<body>
<
% out.print("Today is:"+java.util.Calendar.getInstance().getTime());
%>
<%= request.getParameter("name") %>
• jsp:include action tag
• The jsp:include action tag is used to
include the content of another resource it
may be jsp, html or servlet.
• The jsp include action tag includes the
resource at request time so it is better
for dynamic pages because there
might be changes in future.
• The jsp:include tag can be used to
include static as well as dynamic page
Difference between jsp include directive and
include action
In this example, index.jsp file includes the content of the printdate.jsp file.
File: index.jsp
File: printdate.jsp
• A JavaBean property is a named feature that can be accessed by the user of the
object. The feature can be of any Java data type, containing the classes that you
define.
• A JavaBean property may be read, write, read-only, or write-only. JavaBean
features are accessed through two methods in the JavaBean's implementation
class:
1. getPropertyName ()
• For example, if the property name is firstName, the method name would be
getFirstName() to read that property. This method is called the accessor.
2. setPropertyName ()
• For example, if the property name is firstName, the method name would be
setFirstName() to write that property. This method is called the mutator.
• jsp:useBean action tag
• The jsp:useBean action tag is used to locate or instantiate a bean class. If bean
object of the Bean class is already created, it doesn't create the bean depending
on the scope. But if object of bean is not created, it instantiates the bean.
• Syntax of jsp:useBean action tag
1. <jsp:useBean id= "instanceName" scope= "page | request | session | application"
}
index.jsp file
<jsp:useBean id="obj" class="com.xyz.Calculator"/
>
<%
int m=obj.cube(5);
out.print("cube of 5 is "+m);
%>
• jsp:setProperty and jsp:getProperty
action tags
• The setProperty and getProperty action tags are
used for developing web application with Java
Bean. In web devlopment, bean class is mostly used
because it is a reusable software component that
represents data.
Record:<br>
<jsp:getProperty property="name" name=
"u"/><br>
• Displaying applet in JSP (jsp:plugin action tag)
• 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 of jsp:plugin action tag
<jsp:plugin type= "applet | bean" code= "nameOfClassFile"
codebase= "directoryNameOfClassFile"
</jsp:plugin>
• Example of displaying applet in JSP
• In this example, we are simply displaying applet in jsp using the jsp:plugin tag. You must have
MouseDrag.class file (an applet class file) in the current folder where jsp file resides. You may simply
download this program that contains index.jsp, MouseDrag.java and MouseDrag.class files to run this
application.
index.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Mouse Drag</title>
</head>
<body bgcolor="khaki">
<h1>Mouse Drag Example</h1>
</body>
</html>
Placement Related Questions:
• What are JSP tags, and how do they differ from HTML tags?
• Explain the difference between standard JSP tags and custom JSP tags.
Provide examples of each.
• How do you include another JSP file within a JSP page? What are the benefits
of using this approach?
• Describe the various types of JSP directives and their purposes.
• What is the purpose of Expression Language (EL) in JSP? How do you use
EL to access and manipulate data?
• How do you handle form submissions in a JSP page? Walk me through the
process of receiving form data and processing it in a JSP.
• Explain the concept of JSP Expression Language (EL) and its advantages over
using scriptlets in JSP pages.
• How do you use JSP standard actions to perform common tasks such as
including files, iterating over collections, and handling exceptions?
• Discuss the role of JSP custom tags in web development. Provide an example
of when you would use a custom tag and how you would implement it.
• What are the best practices for building web applications using JSP? How do
you ensure code maintainability and performance in your JSP-based projects?
Worksheets
• https://leetcode.com/problems/remove-k-digits/description/
• https://leetcode.com/problems/string-compression/description/
• https://leetcode.com/problems/occurrences-after-bigram/
• https://tests.mettl.com/authenticateKey/5106dfd
• https://www.hackerrank.com/challenges/pattern-syntax-
checker/problem
• https://leetcode.com/problems/trapping-rain-water/description/
• https://leetcode.com/problems/sort-colors/description/
• https://leetcode.com/problems/word-pattern/description/
References:
Books:
1. Balaguruswamy, Java.
2. A Primer, E.Balaguruswamy, Programming with Java, Tata McGraw Hill
Companies
3. John P. Flynt Thomson, Java Programming.
Video Lectures :
https://www.youtube.com/watch?v=NQ7xKNULkTk
Reference Links:
https://beginnersbook.com/2013/05/jsp-tutorial-directives/
https://docs.oracle.com/javaee/5/tutorial/doc/bnaou.html
https://beginnersbook.com/2013/05/jsp-tutorial-scriptlets/
https://www.javatpoint.com/jsp-scriptlet-tag
https://beginnersbook.com/2013/05/jsp-tutorial-directives/
https://beginnersbook.com/2013/11/jsp-declaration-tag/
THANK YOU