Slot 6-7 JSP
Slot 6-7 JSP
JSP Syntax
Techniques:
MVC Design Pattern
Dynamic DB Connection
Web Server
Container
1. Send request C 2. Call
3. Query
6. Response DAO DB
5. Render/Send
4. Store data into
7. Display V
DTO
3/40
Objectives
• How to build web application applying MVC
model using Servlet, JSP + Scripting Element
– MVC Model
– JSP vs. Servlet
– JSP mechanism, syntax
– How to use JSP combining the Servlets and Java
objects
– How to connect DB using Dynamic connection or
DataSource
4/40
Objectives
Day 1, 2, 3 – Login
Servlet
Day 4, 5 – Search
Break Down
Day 6, 7 – MVC2
JSP
Web Day 8, 9, 10 – CUD, Shopping Carts
Sessions
Web based
App - PBL Day 11, 12 – Login
Framework
JavaBeans
6/40
MVC Design Pattern
MVC Model 2
7/40
MVC Design Pattern
Model – View – Controller
User
View Controller
Model
This is a MVC Model
8/40
MVC Design Pattern
Model – View – Controller
www.netbeans.org
9/40
MVC Design Pattern
Model – View – Controller
www.netbeans.org
10/40
MVC Design Pattern
No MVC
Page-centric application
13/40
MVC Design Pattern
MVC Model 1 – Example
14/40
MVC Design Pattern
MVC Model 1 – Generalization
16/40
MVC Design Pattern
MVC Model 1
Container
18/40
MVC Design Pattern
MVC Model 2
• Separates the “Business Logic” from the “Presentation Logic” and
has an additional component – a Controller
• Use Servlet and JSP together
• JSP pages
– Are used only for presentation
– Retrieve the objects created by the Servlet
– Extract dynamic content for insertion within a template for display
• Servlet
– Handles initial request, partially process the data, set up beans, select suitable
business logic to handle request , then forward the results to one of a number of
different JSP pages
– Serves as a gatekeeper provides common services, such as authentication
authorization, login, error handling, and etc
– Servlet serves as a central controller that act as a state machine or an event
dispatcher to decide upon the appropriate logic to handle the request
– Act as a Controller that controls the way Model and View layer interacts19/40
MVC Design Pattern
MVC Model 2 – Generalization
Servlet-centric Scenario
20/40
MVC Design Pattern
MVC Model 2 – Generalization
• Purpose
– Separation of presentation logic and business logic
– A Model represents information specific to a particular domain on
which the application operates
– A View is typically a user interface element. A single Model may
be presented as multiple views
– A controller component responds to events and processes request
and may invoked changes on the Model
• Advantages
– Easier to build, maintain and extend
– Provide single point of control (Servlet) for security & logging
– Encapsulate incoming data into a form usable by the backend
– Can reusable code
• Limitations
– Increase Design Complexity 21/40
MVC Design Pattern
MVC Model 1 & Model 2 Comparison
Criteria Model 1 Model 2
Processing requests and
Are used for the
JSP page responsibility sending back replies to
presentation layer
clients
Are used for processing
Servlets responsibility N/A
task
Developing an application
Nature of Developer’s Task Quick prototyping that can be modified and
maintained
View and Controller is View and Controller is
Who is doing the work? developed by the same developed by the different
team teams
22/40
Java Server Pages
Need for JSP
• Servlet
– Is a java class that must be compiled to deploy on server
– Low level HTML format that does not focus on the
presentation logic (very complex) of the web
application
– Is not flexible in modify with editor program
à Need the replaced thing that is easily focus on the
presentation logic and approaches the non-
experience presentation developer
23/40
Java Server Pages
JSP
• Java Server Page (JSP) is a server side script language
running web (application) server (Tomcat, Sun, JBoss …)
• Saved with .jsp extension
• A simple, yet powerful Java technology for creating and
maintaining dynamic-content webs pages (embedded)
• JSP page are converted by the web container into a Servlet
instance
• It focus on the presentation logic of the web application
• JSP page contains HTML tags
• JSP page contains tags (standard & custom), which are used
to generate dynamic content and invoke the operations on
Javabeans components and processing requests.
• A combination of HTML, XML, Servlet (extends from
Servlet), and Java Code to create dynamic Web content.
24/40
Java Server Pages
• Benefits JSP
– Segregation of the work profiles of a Web designer and a Web
developer (separating presentation logic and
content/business/processing logic)
– Emphasizing Reusable Components (JavaBeans)
– Simplified Page Development (easy to use JSP through tag,
flexibility, scalability)
– Access & instantiate JavaBeans component (support tag element
with get/set functions)
– High secure
• Choosing Servlet or JSP
– Servlet are well suited for handling binary data dynamically
• Ex: for uploading files or for creating dynamic images, since they need not
contain any display logic
– JSP is easy to create the presentation logic with dynamic
generated data combine template and do not compile before
executing or running time
25/40
Java Server Pages
JSP – Example
• Simple JSP page displays current date.
<html>
<head>
<title>A simple date</title>
</head>
<body>
The time on the server is <%= new java.util.Date() %>
</body> View Source
</html>
• Server processes JSP components converting static data on
HTML which can be displayed by Web browser
• To testing JSP page, the JSP page should be copied to the
ROOT of web server – Tomcat
26/40
Java Server Pages
JSP – In Nature
public void
_jspService(HttpServletRe
quest request,
HttpServletResponse
response)
throws
java.io.IOException,
27/40
ServletException {
Java Server Pages
JSP – In Nature
• When the JSP page is requested to server, the JSP page is
converted to java file as filename_jsp.java (filename.jsp)
• The filename_jsp.java file is complied if it is correct syntax
• Ex:
– Omit the “)” of Date function in the simpleDate.jsp
– Correct above mistake, run the file, then checking the result at
• C:\Documents and Settings\LoggedUser\Application Data\NetBeans\
7.4\apache-tomcat-7.0.41.0_base\work\Catalina\localhost
• C:\Users\LoggedUser\AppData\Roaming\NetBeans\7.4\
apache-tomcat-7.0.41.0_base\work\Catalina\localhost
28/40
Java Server Pages
JSP
29/40
Java Server Pages
JSP Life Cycle
HTTP
WEB JSP
Client SERVER ENGINE Database
JSPs are
processed here
JSP Files
30/40
Java Server Pages
JSP Life Cycle
31/40
Java Server Pages
JSP Life Cycle
Servlet from JSP
Request
Response _jspService()
32/40
JSP Elements
JSP Tags
• Tags
– Interface
– Functional
– Encapsulation
– A tag starts with “<” and ends with “>”.
– The tags contain body and attributes.
• The 4 types of JSP tags
– Comment
– Directives
– Scripting elements
– Standard actions
33/40
JSP Elements
Comments
• Are used for documenting JSP code
• Should not be visible to the client
• Explains the functioning of the code
• Comments are ignored by the servlet during compilation
• A JSP page contains 03 types comments as JSP, HTML, and
scripting
– HTML comments
• Are passed to resulting HTML documents
• Are not visible in the output but the end user can view them.
– JSP comments
• The browser cannot view these comments as a part of the source code
• Are ignored by the JSP to scriptlet translator.
– Scripting language comments
• Are written scriptlets in a JSP page.
• The comment should be in the same comment syntax used for scripting
language.
• Are not visible in the output of the JSP page 34/40
JSP Elements
Comments
• Syntax
– JSP comments: <%-- comments --%>
– Ex: <%-- a JSP comment --%>
– HTML comments: <!-- comments -->
– Ex: <!-- a HTML comment -->
– Scripting language comment
– <%/* comments */%>
– <%// comments %>
– Ex: <%//It’s is a variable declaration %>
35/40
JSP Elements
Scripting Elements
• A way of performing server-side operations in a JSP page
• Enable the code to be directly embedded in a JSP page
• Insert Java code into the JSP page
• Declarations:
– Defines the variables and methods for a JSP page
– Are inserted into the servlet, outside the _jspservice() method
– Are used in combination with scriptlets and expressions to display
an output.
– A single declaration tag can be used to define multiple variables
– Syntax: <%! Declaration; %>
– Ex: <%! String s = “Aptech”; %>
36/40
JSP Elements
• Scriptlets Scripting Elements
– Is used to embed Java code, which is inserted into the _jspService() method of
the servlet within an HTML code
– Refers to code blocks executed for every request (a fragment codes)
– Are used to add complex data to an HTML form
– Syntax: <% scriptlet %>
– Ex: <% for (int i =0 ; i<n; i++){
System.out.println(i + “.This is scriptlets.”); } %>
• Expressions
– Can be used to display individual variables or the result of some calculation
– Contains a Java statement whose value will be evaluated and inserted into the
generated web page
– Refers to single line codes executed for every request.
– Provides dynamic output generation and the result is converted into a string
– Evaluates at HTTP request
– A declaration block is enclosed between delimiters.
– Syntax: <%= expression %>
– Ex: <%= i %>
37/40
JSP Directives
Directives
• Controls the structure of the servlet by sending messages from the
JSP page to the JSP container.
• The scope of directives is the entire JSP file
• JSP uses directives for controlling the processing of JSP pages.
• Do not produce any output and inform the JSP engine about the
actions to be performed on the JSP page
• Specify scripting language used
– Ex: <%@ page language = “java” ...%>
• Denote the use of custom tags library (taglib)
– Ex: <%@ taglib uri = “c:\...” prefix = “abc” %>
• Include the contents of another JSP page into the current page
– Ex: <%@ include file = “c:\...” %>
• Include Java file to Java packages list.
– Ex: <%@ page …. import = “java.util.*, java.lang.*” %>
• Error handle in JSP page and JSP page is catched errors (isErrorPage).
– Ex: handle error <%@ page … errorpage = “/error.jsp” … %>
38/40
process error <%@ page isErrorPage = “true” %>
Page Directives
• Is used to define and manipulate a number of important attributes that affect the entire JSP page
• Is written at the beginning of a JSP page
• A JSP page can contain any number of page directives. All directives in the page are processed together
during translation and result is applied together to the JSP page
• Syntax: <%@ page attributes %>
Attributes Descriptions
language Define the scripting language used in the page. Default value is Java
extends Change the content of the servlet that is generated
import Include Java files to the Java package import list. Separating uses commas
session Specify if the JSP page takes part in a HTTP session. Default value is true
buffer Specify the size of the page buffer. Default value is 8KB
autoflush Flush the page buffer is filled. Default value is true
Define the safety level of threads in the page. The JSP engine queues the
isThreadSafe
requests sent for processing when the value is set to false. Default value is true
info Describe the page
errorPage Define the page to display errors ocurring in the JSP page
isErrorPage Indicate the current JSP page if contains the path another error page of JSP
Set the content type or MIME type and character encoding for JSP. Default
contentType 39/40
value is text/html
JSP Directives
• Include Include & Tablib Directives
– Is used to physically include the contents of another file sending
to the server. The included file can be a HTML or JSP
– Identify the file through the local URL
– A single JSP file can include multiple include directives
– Syntax: <%@ include file = “URL” %>
• Taglib
– Enables the use of custom tags in the JSP page
– Access to all the objects that are available for a JSP page
– Extend the functionality of a JSP page one after the other
– The TLD – Tag Library Descriptor is identified through the URI –
Uniform Resource Identifier and prefix describes the prefix string
used to define the custom tag
– Syntax: <%@ taglib uri = “URL” prefix = “name” %>
40/40
Example
<%@ page import="java.util.Date" %>
<html>
Directives - page
<head>
<title>First JSP program</title>
</head> HTML Comments
<body>
Scriptlet
<!-- myFirstProgram.jsp -->
<% out.println("Hello there!"); %><br>
<%= "Current date is " + new Date() %>
<%-- end Program --%>
Expression
</body>
JSP Comments
</html>
41/40
JSP Elements
Example
42/40
JSP Elements
• Main (main.jsp) file
<html>
Example
<head>
<title>Directive Includes JSP program</title>
</head>
JSP Comments
<body>
Directives - include
<%-- include use directives --%>
Current date is
<%@ include file = "myDate.jsp" %>
</body>
Directives - page
</html>
• Include (myDate.jsp) file
<%@ page import="java.util.Date" %>
<html>
<head>
<title>Date JSP program</title>
</head> Expression
<body>
<%= new Date().toLocaleString() %>
</body>
</html>
43/40
JSP Elements Example
44/40
JSP Elements
Example
45/40
JSP Elements Example
jspInit
Declarations
jspDestroy
46/40
JSP Elements Example
47/40
JSP Elements
Example
Expression!!!
50/40
JSP Elements
Example – Exception
51/40
JSP Elements
Example – Exception
52/40
JSP Implicit Objects
Implicit Objects
• Does not initialize or declare
• Are loaded by the Web Container automatically and maintains them in a
JSP page (Available for scriptlets or expressions)
• Created using directives and accessible according to the specified scopes
• The names of the implicit objects are reserved words of JSP
• The scopes for the IB in JSP page including page, request, session, and
application
• Access dynamic content using JavaBeans
• Syntax: ImplicitObject.method(params)
• Types of Implicit Objects
– Input & Output Objects
• The objects control page input and output
• Are request, response and out
– Scope Communication Objects: provide access to all objects available in the
given scope
– Servlet Objects
• Provides information about the page context
• Processes request objects from a client and sends the response objects back to the
client 53/40
JSP Implicit Objects
• Types of Implicit Objects (cont)
– The Error Objects
• The object handles errors in a JSP page (exception)
• Can access this object by declaring your JSP page as an error page
<%@page isErrorPage=“true” %>
Object Class / Interface
page javax.servlet.jsp.HttpJspPage – variable synonym for this object
config javax.servlet.ServletConfig
request javax.servlet.http.HttpServletRequest
response javax.servlet.http.HttpServletResponse
out javax.servlet.jsp.JspWriter
session javax.servlet.http.HttpSession
application javax.servlet.ServletContext
pageContext javax.servlet.jsp.PageContext
exception java.lang.Throwable 54/40
JSP Implicit Objects
Input & Output Objects
Objects Descriptions
- Refer to the current request made by the client that is being processed by JSP
container. The container passed the request IB to JSP page as a parameter to the
_jspservice().
request - Implement the javax.servlet.http.HttpServletRequest interface
- Syntax: request.method(params)
- Scope: request
-Ex: request.getParameter(“username”);
- Refers the result that is returned to the user after a JSP processed
- Implement the javax.servlet.http.HttpServletResponse interface
response - Syntax: response.method(params)
- Scope: page
- Ex : response.addCookie(cookie)
- Represent the output stream for the JSP page (send to client)
- Implement the javax.servlet.jsp.JspWriter interface (the buffer size is
supported by Servlet)
out
- Syntax: out.method(params)
- Scope: page
- Ex: out.println(“output stream”)
55/40
JSP Implicit Objects
Input & Output Objects – Example
56/40
JSP Implicit Objects
Input & Output Objects – Example
57/40
JSP Implicit Objects
Scope Communication Objects
Objects Descriptions
- Specify data and store information in the current session.
- Implement the javax.servlet.http.HttpSession interface
session - Syntax: session.method(params)
- Scope: session
- Ex: session.setAttribute(“username”, “Aptech”);
- Represent the application of the required JSP page and represent the
servlet context about Web Application in which it is running.
- Implement the javax.servlet.ServletContext interface
application
- Syntax: application.method(params)
- Scope: application
- Ex: application.setAttribute(“username”, “Aptech”);
- An instance of Pages (javax.jsp.PageContext)
- Enable access to the JSP page and the attributes associated with that page
- provides following fields to find the scope or specify the scope of the
pageContext
objects (PAGE, REQUEST, SESSION, and APPLICATION)
- Syntax: pageContext.method(params)
- Ex: pageContext.getAttributes(“username”);
58/40
JSP Implicit Objects
Scope Communication Objects – Example
59/40
JSP Implicit Objects
Scope Communication Objects – Example
60/40
JSP Implicit Objects
Servlet Objects
Objects Descriptions
- Represents the servlets and the initialization parameters
of the servlet are stored in the config IB
- Use “this” reference and the page IB represents it.
page
- Implements the javax.lang.object interface
- Syntax: <%@ page info = “information” %>
- Scope: page
- Represent the configuration of the servlet data
- Implement the javax.Servlet.ServletConfig interface
config
- Access objects through config.getInitParameter(“par”)
- Scope: page
61/40
JSP Implicit Objects
Servlet Objects – Example
62/40
JSP Implicit Objects
Error Objects
Objects Descriptions
- Refer to the runtime exception in an error page
- Is available only on pages that are assigned as error
page using the isErrorPage attribute of the page
directive.
- Implement the javax.lang.Throwable interface
- Exception methods are supported
exception + getMessage() : return the error message associated
with the exception
+ toString() : Return a string with the class name of
the exception within the error message.
+ printStackTrace(): prints the execution stack in
effect when the exception was thrown to the
designated output stream
63/40
JSP Implicit Objects
Error Objects – Example
64/40
JSP Implicit Objects
Error Objects – Example
65/40
Summary
• How to build web application applying
MVC model using Servlet, JSP + Scripting
Element
– JSP vs. Servlet
– JSP mechanism, syntax
– MVC Model
– How to use JSP combining the Servlets and Java
objects
– How to connect DB using Dynamic connection or
DataSource Q&A
66/40
Next Lecture
• How to write CUD Web Application
– Session Tracking Techniques
– Manipulate DB Techniques in Web Application
– Break down structure component in building web
application
• Techniques: Error Handling in Servlets
– Reporting Errors
– Logging Errors
– Users Errors vs. System Errors
67/40
Next Lecture
Day 1, 2, 3 – Login
Servlet
Day 4, 5 – Search
Break Down
Day 6, 7 – MVC2
JSP
Web Day 8, 9, 10 – CUD, Shopping Carts
Sessions
Web based
App - PBL Day 11, 12 – Login
Framework
JavaBeans
74/40
Appendix
Create the JSP Page on NetBeans
Fill your file
name without .jsp
Locate the
directory store
jsp file in current
project
Using JSP File
76/40
Java Server Pages
JSP Life Cycle
• Translation
– A servlet code to implement JSP tags is
automatically generated, complied and loaded
into the servlet container.
– jspInit() method is invoked when the JSP page is
initialized and requested
– The _jspService() method corresponds to the
body of the JSP page and is defined
automatically by the JSP container and never be
defined by the JSP page
– The jspDestroy() method is invoke when the JSP
page is going to be destroyed (requested again)
– Notes: the servlet must implement the
javax.servlet.jsp.HttpJspPage interface 77/40
Java Server Pages
JSP Life Cycle
• Complication
– The JSP page is automatically compiled and
executed again by JSP/ Servlet Engine
• Execution
– Is carried out with the help of page directives
controlling various execution parameters and
are used for buffering output and handling
errors
78/40
JSP Elements
Overview
• Enables to create dynamic JSP pages
• The JSP server translates and executes JSP elements
Elements Description
Root Classifies standard elements and attributes of namespaces in
tag library
Comment Used in JSP file documentation
Declaration Declares variables and methods in a scripting language page.
Expression Includes expression in a scripting language page
include Directive Includes content of one JSP page into the current JSP page
79/40
JSP Elements
Overview
Elements Description
81/40
MVC Design Pattern
MVC Model 2
82/40
MVC Design Pattern
MVC Model 2
83/40
MVC Design Pattern
MVC Model 2
84/40
MVC Design Pattern
MVC Model 2
85/40
MVC Design Pattern
MVC Model 2
86/40
MVC Design Pattern
MVC Model 2
87/40
Appendix
Data Source
• Java EE applications use DataSource objects when they access
relational databases through the JDBC API
– A DataSource object works with a JNDI naming service
– After it is registered with a JNDI naming service, an application can use the
JNDI API to access that DataSource object
• A DataSource has a set of properties that identify and describe the
real-world data source that it represents
– A DataSource XML descriptor that contains essential information, such as
the name of the underlying JDBC driver, database URL, the name of the
database, and the network protocol, connection pooling properties, and so on
– A DataSource alias is a logical name mapped to the name of a real
DataSource available in the system. It specified in the name element begins
with a namespace scope
• java:comp/env/, the datasource will be available for the component in
which it is defined, such as a servlet, EJB, or application client component
– The DataSource alias is used in application code to connect to the underlying
data source
88/40
Appendix
Dynamic DB Connection
• Adding and modify the web.xml as following
89/40
Appendix
Dynamic DB Connection
• Adding and modify the web.xml as following
90/40
Appendix
Dynamic DB Connection
• Adding and modify the context.xml in the META-INF
directory as following
91/40