Introduction to JSP
• JSP technology is used to create dynamic web applications.
• JSP pages are easier to maintain then a Servlet
• JSP pages are opposite of Servlets as a servlet adds HTML
code inside Java code, while JSP adds Java code inside
HTML using JSP tags.
• Everything a Servlet can do, a JSP page can also do it.
Java Server Pages
JSP vs Servlets
• JSP provides an easier way to code dynamic web pages.
• JSP does not require additional files like, java class files, web.xml etc
• Any change in the JSP code is handled by Web Container, and doesn't
require re-compilation
• JSP pages can be directly accessed, and web.xml mapping is not
required like in servlets.
Sample JSP Code
• <%-- JSP comment --%>
• <HTML>
• <HEAD>
• <TITLE>MESSAGE</TITLE>
• </HEAD>
• <BODY>
• <%out.print("Hello, Sample JSP code");%>
• </BODY>
• </HTML>
<%out.print(“ Hello, Sample JSP code ”);%>
• It is a JSP element, known as scriplet
• Scriptlets can contain Java codes.
• Syntax : <%Executable java code%>
• they must end with a semicolon(;)
Setting up the JSP Environment
• Java Development Kit(JDK) Setup
• Setup and install Apache Tomcat server
• Create a Folder within the Tomcat\Webapps folder
• Create a JSP file
• Run using localhost:8080/Folder-name/JSP_File.jsp
JSP Life Cycle
Initialization : jspinit()
Processing Response
Jspservice() Request
jspdestroy()
Generating Dynamic Content
• You create dynamic content by accessing Java programming
language objects from within scripting elements.
• Using Objects within JSP Pages
– Implicit Objects
– Application-Specific Objects
– Shared Objects
Implicit Objects
Application Specific Objects
• When possible, application behavior should be encapsulated in objects so that page designers
can focus on presentation issues.
• Objects can be created by developers who are proficient in the Java programming language
and in accessing databases and other services.
• There are four ways to create and use objects within a JSP page:
– Instance and class variables of the JSP page's servlet class are created
in declarations and accessed in scriptlets and expressions.
– Local variables of the JSP page's servlet class are created and used
in scriptlets and expressions.
– Attributes of scope objects are created and used in scriptlets and expressions.
– javaBeans components can be created and accessed using streamlined JSP elements.
Shared Object
• Used in JSP pages that run as multithreaded servlets.
• You can indicate how a Web container should dispatch multiple client requests with the
following page directive:
– <%@ page isThreadSafe="true|false" %>
• When isThreadSafe is set to true, the Web container may choose to dispatch multiple
concurrent client requests to the JSP page.