Java Enterprise Edition
The Web Tier
Objectives of this Course
Focus on Presentation
The Presentation Tier as a Web application
â
Managed by the Web Container as a Web Application
â
Web applications are of the following types:
â
Presentation-oriented: generate interactive web pages containing
various types of markup language (HTML, XHTML, XML, ...)
â
Service-oriented: implements the endpoint of a web service. Often
Java EE Containers
Servlet
JSP
Servlet
JSF
Web Container
JA X -R P C JA X -W S JA X -R S SAAJ JA S P IC W eb S er vic es W S M et ad at a M an ag em en t JM S C on ne cto rs JT A Ja va M ail JP A JA X R JA C C Java SEEJB
EJB Container
JA X -R P C JA X -W S JA X -R S SAAJ JA S P IC W e b S er vic es W S M eta da ta M an ag em en t JM S C on ne cto rs JT A Ja vaM ail JP A JA X R JA C C Java SE. .
. .
. .
. .
RMI/IIOP
Client Application
Client Container
JA X -R P C JA X -W S JA X R SAAJ W e b S er vic es W S M et ad ata M an ag em en t JP A JM S Java SEApplet
Applet
Container
Java SE HTTP SSL HTTP SSL Database JDBC JDBC RMI/IIOPJava Web Application request handling
â
Servlet technology serves as the base to build Web Applications
7
Servlets
ï¬
Servlets are programs written in Java which run on the
web server and communicate with the web browser using
HTTP and HTML
ï¬
The servlet runs inside a container called a Servlet
Engine
ï¬
The communication services, security etc are provided by the
container
ï¬
Container runs within the JVM
ï¬
Hides coding issues around with Sockets, TCP/IP or Java serialisation.
ï¬
Servlets communicate with the browser using only HTML
and HTTP
ï¬
Compatible with all web browsers
ï¬
Servlets run only on the server
ï¬
Servlets do not need any component to be stored or installed on the
Servlets features
â
Produce dynamic web content.
â
Processing HTTP Requests with Servlets.
âServlet API â GET and POST requests.
âPassing parameters to servlets.
â
Servlet API - getParameter
âHTTP Sessions.
â
Keeping server-side state for a client.
â
Creating and deploying a packaged web application
âWar file.
â
More advanced topics
HTTP Client
Servlet Architecture
Web Server http://crimeportal.org/killerapp/assassination
Servlet Container
Request Dispatcher
Assassination Servlet
Killer App
Other Web App 2 Other Web App 1
/killerapp
10
Client
Server
Servlet Lifecycle I:
Web
Browser
Web Server
Servlet Container
Servlet
Service
Init
HTML
Get or Post
1.
Web browser sends HTTP Post or Get message to Web Server
2.
Web server redirect the request to the servlet. If the servlet is not already
loaded it loads it and calls the servlet's init method
3.
The web browser passes the HTML request to the servlet's service
11
Client
Server
Servlet Lifecycle II:
Web
Browser
Web Server
Servlet Container
Servlet
doGet
doPost
Service
Init
Destroy
HTML
HTML
HTML
4.
Service method calls the doGet or doPost method of the servlet
5.
Method executes and generates HTML which is passed back to the web
browser.
12
Client
Server
Servlet Lifecycle III:
Web
Browser
Web Server
Servlet Engine
Servlet
doGet
doPost
Service
Init
Destroy
4.
When the servlet container decides to unload the servlet it calls the
destroy method
ï¬
At shutdown or if memory is short
Writing a Servlet
â
All Servlets extend the Servlet class
â
Normally extends HttpServlet which is derived from Servlet class
â
HttpServlet class provides default implementations
of
â
Init
: Need to override if some additional initialisation required
such as open a database connection.
â
Destroy
: Need to override if some additional cleaning up
required such as closing a database connection.
â
Service
: Not normally be overridden
â
doGet:
Normally over-ridden as HTTP Get is the default web
browser request which causes the doGet method of the servlet to
be invoked.
import javax.servlet.*;
import javax.servlet.http.*; Import java.io.*;
public class AssassinationServlet extends HttpServlet {
public void doGet ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
PrintWriter out = response.getWriter() ;
out.println( "<html><head><title>Assassination Servlet</title></head>" ) ; out.println( "<body><b>BANG!!<b></body>" ) ;
out.println( "</html>" ) ; out.close();
}
public void doPost ( HttpServletRequest request, HttpServletResponse response ) throws ServletException, IOException {
doGet(request,response); // just calls doGet method.
} }
AssassinationServlet.java
A Simple Example
Request and Response
ï
Request and Response arguments are passed to
doGet,
doPost,
etc.
ï
HttpServletRequest â provides access to:
â
Named parameters passed to URL.
â
Client information â remote host, security info if authenticated.
â
Stored attributes (inserted using the
setAttribute
method).
â
Session information (more later).
ï
HttpServletResponse
â
Used to write the output to the client.
â
Can be text (
getWriter())
â¦
Request Parameters
ï
A browser can pass values to the server side by embedding
them in the
GET
URL
â
They are passed using standard CGI format, name-value pairs:
http://crimeportal.org/killerapp/assassination?who=Fredo&how=pistol
â
The web container parses the URL and stores them in the
HttpServletRequest
object.
â
The servlet programmer then has access to them using the
getParameter()
method:
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
PrintWriter out = res.getWriter() ;
out.println( "<html><head><title>Sicilian Message</title></head>" ) ;
out.println( "<body>" + req.getParameter("who") +Â " sleeps with the
fishes.</body>" ) ;
out.println( "</html>" ) ;
out.close();
}
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
PrintWriter out = res.getWriter() ;
out.println( "<html><head><title>Sicilian Message</title></head>" ) ;
out.println( "<body>" +
req.getParameter("who")
+Â " sleeps with the
fishes.</body>" ) ;
out.println( "</html>" ) ;
out.close();
Using Forms and HTTP Post
ï
Post
is an HTTP alternative to
GET.
â
Must be used with forms (not URLs).
â
No limit on parameter size.
â
Results not cached by browser.
<html>
<head><title>Assassination
Servlet</title></head>
<body>
<form method= "POST"
action="assassination">
Name: <input type="text"
name="who">
Method: <input type="text"
name="how">
<br><br>
<input type="submit"
value="Whack" name="submit">
</form>
</body>
</html>
<html>
<head><title>Assassination
Servlet</title></head>
<body>
<form method= "POST"
action="assassination">
Name: <input type="text"
name="who">
Method: <input type="text"
name="how">
<br><br>
<input type="submit"
value="Whack" name="submit">
</form>
</body>
</html>
Deployment Descriptor - web.xml
â¦
<web-app>
<display-name>Crime Portal Killer Application</display-name>
<description>use with care</description>
<!-- register the servlet - name and full class name -->
<servlet>
<servlet-name>whacker</servlet-name>
<servlet-class>crimeportal.AssassinationServlet</servlet-class>
</servlet>
<!-- set up the mapping to a URL (or URLs) -->
<servlet-mapping>
<servlet-name>whacker</servlet-name>
<url-pattern>/assassination</url-pattern>
</servlet-mapping>
â¦
</web-app>
web.xml
â¦
<web-app>
<display-name>Crime Portal Killer Application</display-name>
<description>use with care</description>
<!-- register the servlet - name and full class name -->
<servlet>
<servlet-name>whacker</servlet-name>
<servlet-class>crimeportal.AssassinationServlet</servlet-class>
</servlet>
<!-- set up the mapping to a URL (or URLs) -->
<servlet-mapping>
<servlet-name>whacker</servlet-name>
<url-pattern>/assassination</url-pattern>
</servlet-mapping>
â¦
</web-app>
web.xml
Deployment - the WAR File
killerapp.war
whack. html vendor.xmlcrimeportal
classes
WEB-INF
web.xml AssassinationServletSession Tracking
ï
In Java EE, the web-tier has the responsibility of tracking a user
session.
ï
However, Http is a stateless request/response protocol.
â
There is no inherent concept of a session.
â
âCookiesâ allow requests from the same client to be recognised.
ï
Using
HttpServlet
gives you session management for free.
â
Can maintain state for a user across multiple requests.
â
The session ID is passed as a cookie or by rewriting URLs.
â
Container handles it all - transparent to application.
â
Essential for any serious online applications.
ï
The session is a private storage area for the application.
â
Server code can add or remove objects (EJB references, shopping
carts).
ï
Allows secure sessions to be handled for authenticated users.
HttpSession Interface
â
Obtained by invoking getSession on HttpServletRequest. Two
forms:
â
getSession() creates new session instance or returns existing one.
â
getSession(boolean create) as above, but only creates a new session if
create is true. Otherwise, if no session already exists, returns null.
â
Attributes (objects) can be stored, retrieved or removed from
the session
â
setAttribute, getAttribute, removeAttribute methods.
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String who = req.getParameter("who");
HttpSession sesh = req.getSession();
// store attribute for future reference
sesh.setAttribute("themark", who);
â¦
}
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
String who = req.getParameter("who");
HttpSession sesh = req.getSession();
// store attribute for future reference
sesh.setAttribute("themark", who);
â¦
}
Ending Sessions
ï
Sessions usually have a timeout.
â
Can be set in
web.xml
file.
â
Can be read or set programmatically using
get/setMaxInactiveInterval().
ï
Can call
invalidate()
on the session.
â
Invalidates the session and unbinds any objects stored in it.
<web-app>
â¦
<session-config>
<session-timeout>30</session-timeout>
</session-config>
â¦
</web-app>
web.xml
<web-app>
â¦
<session-config>
<session-timeout>30</session-timeout>
</session-config>
â¦
</web-app>
web.xml
The Request Dispatcher
(javax.servlet.RequestDispatcher)
â
Used to forward the request to another resource (servlet, JSP,
HTML).
â
On the same server.
â
Allows processing by multiple resources.
â
âservlet chainingâ.
â
Can be used to implement control flow logic.
â
Key part of âcontrollerâ servlet in âModel-2â frameworks such as struts.
ï
Example usage:
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
â¦
String path = "/forward/to/url";
RequestDispatcher rd =
getServletContext().getRequestDispatcher(path);
rd.forward(request, response);
}
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
â¦
String path =
"/forward/to/url";
RequestDispatcher rd
=
getServletContext().
getRequestDispatcher(path);
rd.forward
(request, response);
}
The Request Dispatcher (continued)
ï
Also provides âincludeâ
â
Allows content to be included, the URL doesnât change
â
Key to portals and other similar interfaces
ï
Usually dreadfully lower performance than concatenating
strings/composing the interface directly.
â
But its far easier to do..
ï
Example usage:
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
â¦
String path = "/include/url";
RequestDispatcher rd =
getServletContext().getRequestDispatcher(path);
rd.include(request, response);
}
public void doGet (HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
â¦
String path =
"/include/url";
RequestDispatcher rd
=
getServletContext().
getRequestDispatcher(path);
rd.include
(request, response);
}
Filters
ï
Filters can perform request and response pre-processing for the
servlet.
â
Can replace the request and response objects with customized
ones.
â
Can be linked together to form a chain.
â
Can terminate a request.
<filter>
<filter-name>Whack Filter</filter-name>
<filter-class>crimeportal.WhackFilter</filter-class>
</filter>
<filter-mapping>
<!-- apply the filter to a particular
servlet -->
<filter-name>Whack Filter</filter-name>
<servlet-name>whacker</servlet-name>
</filter-mapping>
web.xml
<filter>
<filter-name>Whack Filter</filter-name>
<filter-class>
crimeportal.WhackFilter
</filter-class>
</filter>
<filter-mapping>
<!-- apply the filter to a particular
servlet -->
<filter-name>Whack Filter</filter-name>
<servlet-name>
whacker
</servlet-name>
</filter-mapping>
Application Lifecycle Events
ï
Now have ability to listen for web application events.
â
ServletContextListener:
context creation and destruction.
â
HttpSessionListener:
session creation and destruction.
â
Listener classes must implement one of these interfaces.
<web-app>
<listener>
<listener-class>crimeportal.SessionListener</listener-class>
</listener>
...
</web-app>
web.xml
<web-app>
<listener>
<listener-class>
crimeportal.SessionListener
</listener-class>
</listener>
...
</web-app>
@Webservlet Annotation
@WebServlet(
attribute1=value1,
attribute2=value2,
...
)
public class TheServlet extends javax.servlet.http.HttpServlet {
// servlet code...
}
@WebServlet(
attribute1=value1,
attribute2=value2,
...
)
public class TheServlet extends javax.servlet.http.HttpServlet {
// servlet code...
}
â
@WebServlet annotation is used to declare a servlet.
âAvoid the manipulation of the web.xml file
â
@WebServlet attributes are :
â
name Description, Value, UrlPatterns, InitParams, LoadOnStartup,
AsyncSupported, SmallIcon, largeIcon
The problem with Servlets
â
Servlets are great for server side request processing.
â
But not so good for rendering output.
â
Producing anything other than simple HTML is very messy.
â
Lots of out.println() statements.
â
The HTML is embedded in Java code.
â
Canât be edited separately.
â
Makes designer/coder role separation impossible.
â
Have to recompile the servlet class every time you make a
What are JSPs?
â
JSP-JavaServer Pages is a server side programming language.
â
It has the ability to integerate with HTML very easily to enhance
the presentation of a page. JSP pages helps to differentiate the
design from the programming logic of a web page.
â
They are compiled into Java servlets when first accessed.
â
The servlet is then compiled to Java bytecode.
â
So JSPs are
just servlets, as far as the server is concerned.
âThe servlet generates the HTML code for the page.
Servlet vs. JSP
public class HelloWorldServlet extends HttpServlet {protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
res.setContentType("text/html"); PrintWriter out = res.getWriter(); out.println("<html>");
out.println(" <head>");
out.println(" <title>Bonjour tout le monde</title>"); out.println(" </head>");
out.println(" <body>");
out.println(" <h1>Bonjour tout le monde</h1>");
out.println(" Nous sommes le " + (new java.util.Date().toString()) ); out.println(" </body>"); out.println("</html>"); } } <html> <head>
<title>Bonjour tout le monde</title> </head>
<body>
<h1>Bonjour tout le monde</h1>
Nous sommes le <%= new java.util.Date().toString() %> </body>
</html>
Java code added in JSP
Bonjour tout le monde
Architecture
JSP pages are converted into Servlet then compiled before
execution
Translation and compilation are executed if necessary ; when
the page is called the first time or modified.
Conversion JSP to Servlet
public final class helloworldjsp_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
HttpSession session = null;
...
try {
...
_jspx_out = out;
out.write("<html>\r\n");out.write("\t<head>\r\n");
out.write("\t\t<title>Bonjour tout le monde</title>\r\n");
out.write("\t</head>\r\n");out.write("\t<body>\r\n");
out.write("\t\t<h1>Bonjour tout le monde</h1>\r\n");
out.write("\t\tNous sommes le ");out.print( new java.util.Date().toString() );
out.write(" et tout va bien.\r\n");out.write("\t</body>\r\n");out.write("</html>");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
...
if (_jspx_page_context != null)
_jspx_page_context.handlePageException(t);
}
} finally {
if (_jspxFactory != null) _jspxFactory.releasePageContext(_jspx_page_context);
}
Standard objects
â
A JSP is a servlet so it has access to servlet parameters and
properties.
â
These are provided through named objects.
â
These âimplicit objectsâ include:
â
request -
HttpServletRequest
.
â
response -
HttpServletResponse
.
âsession -
HttpSession
.
â
out â
JspWriter.
â...
â
They can be accessed directly by name in your JSP code.
Predefined Variable
â
request
: This variable specifies the data included in a http request. This
variable takes value from the clients' browser to pass it over to the server.
â
reponse
: This variable specifies the data included in the http response. It is
used with cookies and also in http headers.
â
out
: This variable specifies the output stream otherwise known as printwriter in
a page context.
â
session
: This variable specifies the data associated with httpsession object
with a specific session of a user. The main purpose of this object is to use the
session information to maintain multiple page requests.
â
application
: this variable is used to share data with all application pages.
âconfig
: This variable refers the java servlet configuration value.
â
pagecontext
: This variable is used to store the environment for the page like
page attributes, access to the request, response and session objects.
Expression Language in JSP
â
JSP EL is used to set action attribute values from different
sources at runtime.
â
JSP EL always starts with a "$" followed by a "{" and ends with a
"}".
â
The expression is specified inside the brackets : ${expr}
â
Examples
â
${2+3+4}
â
Box Perimeter is: ${2*box.width + 2*box.height}
âJSP EL Implicit Objects
Implicit Objects
Description
pageScope
Scoped variables from page scope
requestScope
Scoped variables from request scope
sessionScope
Scoped variables from session scope
applicationScope
applicationScope
Scoped variables from application scope
param
Request parameters as strings
paramValues
Request parameters as collections of strings
header
HTTP request headers as strings
headerValues
HTTP request headers as collections of strings
initParam
Context-initialization parameters
cookie
Cookie values
JSP Implicit Objects - Example
Example
Result
<html>
<body>
<form action="implicitObjects.jsp" method="GET">
NAME:<input type="text" name="nam">
<input type="submit">
</form>
<p><b>NAME</b> : ${param.nam}</p>
<p><b>HEADER</b> : ${header["host"]}</p>
<p><b>USER AGENT</b>:${header["user-agent"]}</p>
</html>
<html>
<body>
<form action="implicitObjects.jsp" method="GET">
NAME:<input type="text" name="nam">
<input type="submit">
</form>
<p><b>NAME</b> : ${param.nam}</p>
<p><b>HEADER</b> : ${header["host"]}</p>
<p><b>USER AGENT</b>:${header["user-agent"]}</p>
</html>
NAME : william HEADER : localhost:8080USER AGENT:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.114 Safari/537.36
NAME : william
HEADER : localhost:8080
USER AGENT:Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.114 Safari/537.36
JSP Tags - Directives
â
These are messages to the container.
â
They donât (directly) produce any output.
â
They are delimited by
â
<%@ ⦠%>
â.
â
âPageâ directives are
used for page dependent properties such
as:
â
Import statements:
<%@
page
import
=âjava.util.*;â %>
âError page declarations:
<%@
page errorPage
=â/aaarrrghh.jspâ %>
â
Indicate if a page is a normal ou error page :
<%@ page isErrorPage=false %>
â
Content types
<%@
page contentType
=âtext/html;GB2312â %>
â
âIncludeâ directives are used to include other source in the
page:
JSP Tags - Scripting
â
Used for computation within the page.
â
Manipulate the page objects (beans, implicit objects).
âUsed for iteration and conditional execution.
â
There are 3 variationsâ¦
â
Variable declarations: â
<%! ⦠%>
â
â
Translate to instance members of the generated servlet.
â<%! int hits = 0; %>
â
Scriptlets: â
<% ⦠%>
â
â
Contain pure Java code.
â
Java expressions: â
<%= ⦠%>
â
Examples
<%@ page import=âjava.util.*â %> <%@ page errorPage=â/error.jspâ %> <html>
<body>
<% for ( int i = 0; i < 50; i++ ) { %>
Hello from your friendly JSP !!! (count = <%= i %>) <br> <% } %> </body> </html> <%@ page import=âjava.util.*â %> <%@ page errorPage=â/error.jspâ %> <html> <body>
<% for ( int i = 0; i < 50; i++ ) { %>
Hello from your friendly JSP !!! (count = <%= i %>) <br>
<% } %>
</body> </html>
import java.util classes
print out the value of âiâ define the page to
show if an error occurs normal html
<%!
public int mul(int a, int b) {
return a * b; }
%>
Multiplication of two numbers:<%= mul(2, 2) %> Result:
Multiplication of two numbers:4
<%!
public int mul(int a, int b) {
return a * b; }
%>
Multiplication of two numbers:<%= mul(2, 2) %> Result:
Multiplication of two numbers:4
Creating a method
JSP Deployment
â
- Like an html file, somewhere in the webapp tree, outside WEB-INF
â- Container detects the .jsp extension
â
- You can add a web.xml entry
â
url-patterns + init parameters
<servlet>
<servlet-name>myjsp</servlet-name>
<jsp-file>/myjsp.jsp</jsp-file>
<init-param>
<param-name>hello</param-name>
<param-value>test</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myjsp</servlet-name>
<url-pattern>/myjsp</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>myjsp</servlet-name>
<jsp-file>/myjsp.jsp</jsp-file>
<init-param>
<param-name>hello</param-name>
<param-value>test</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>myjsp</servlet-name>
<url-pattern>/myjsp</url-pattern>
</servlet-mapping>
Including JSP pages
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>jsp:include example</title> </head> <body> This is a page<br/> <jsp:include page="welcome.jsp" /> </body> </html> <html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>jsp:include example</title> </head> <body> This is a page<br/> <jsp:include page="welcome.jsp" /> </body> </html> <html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title>
</head> <body>
Welcome Dynamic Include Is Working Now </body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title>
</head> <body>
Welcome Dynamic Include Is Working Now </body>
Redirecting JSP pages
<html><head>
<title>JSP Redirect Example</title> </head>
<body> <%
String redirectURL = "http://www.examples.net/"; response.sendRedirect(redirectURL); %> </body> </html> <html> <head>
<title>JSP Redirect Example</title> </head>
<body> <%
String redirectURL = "http://www.examples.net/"; response.sendRedirect(redirectURL); %> </body> </html> <html> <head>
<title>JSP Redirect Example</title> </head> <body> <% ... %> </body> </html> <html> <head>
<title>JSP Redirect Example</title> </head> <body> <% ... %> </body> </html>
â
Redirection to resource to different servers or domains
âClient/browser is aware, the header change
Forwarding JSP pages
<html><head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>jsp:forward example</title> </head> <body> This is a page<br/> <jsp:forward page="welcome.jsp" /> </body> </html> <html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>jsp:forward example</title> </head> <body> This is a page<br/> <jsp:forward page="welcome.jsp" /> </body> </html> <html> <head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title>
</head> <body>
Welcome Forward Is Working Now </body>
</html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Welcome</title>
</head> <body>
Welcome Forward Is Working Now </body>
</html>
â
Forward to resource within the same server
âClient/browser not involved
JSP â Exception Handling
<%@ page errorPage="ShowError.jsp" %> <html>
<head>
<title>Error Handling Example</title> </head>
<body> <%
// Throw an exception to invoke the error page int x = 1;
if (x == 1) {
throw new RuntimeException("Error condition!!!"); } %> </body> </html> <%@ page errorPage="ShowError.jsp" %> <html> <head>
<title>Error Handling Example</title> </head>
<body> <%
// Throw an exception to invoke the error page int x = 1;
if (x == 1) {
throw new RuntimeException("Error condition!!!"); }
%>
</body> </html>
Redirection to dedicated error pages
Redirection to dedicated error pages
JSP â Exception Handling
<%@ page isErrorPage="true" %> <html>
<head>
<title>Show Error Page</title> </head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.
<p>Here is the exception stack trace: </p> <pre> <% exception.printStackTrace(response.getWriter()); %> </pre> </body> </html> <%@ page isErrorPage="true" %> <html> <head>
<title>Show Error Page</title> </head>
<body>
<h1>Opps...</h1>
<p>Sorry, an error occurred.
<p>Here is the exception stack trace: </p> <pre>
<% exception.printStackTrace(response.getWriter()); %> </pre>
</body> </html>
Error-handling page includes the directive
<%@ page isErrorPage="true" %>.
Causes the JSP compiler to generate the
exception
instance
variable.
JSP â Exception Handling
<html> <head> <title>Try...Catch Example</title> </head> <body> <% try{ int i = 1; i = i / 0;out.println("The answer is " + i); }
catch (Exception e){
out.println("An exception occurred: " + e.getMessage()); } %> </body> </html> <html> <head> <title>Try...Catch Example</title> </head> <body> <% try{ int i = 1; i = i / 0;
out.println("The answer is " + i); }
catch (Exception e){
out.println("An exception occurred: " + e.getMessage()); }
%>
</body> </html>
â
Using Try...Catch Block
â
Handling errors within the same page and want to take some
JSP Tags - Actions
â
The JSP specification also defines standard
action
tags.
â
Use an XML-based syntax, prefixed with
â<jsp:â
â
Examples:
â
<jsp:useBean .../> -
allows a Java object to be used as a scripting
variable.
â
<jsp:forward .../> -
dispatches the request to another resource.
â<jsp:plugin .../> -
use the Java Plug-In to run a Java applet.
â
Additional actions can be defined using the taglib mechanism
Using a JavaBean from a JSP
â
Java bean : a class that implements java.io.Serializable interface
and uses set/get methods to project its properties.
â
There are three basic actions or tags used to embedd a java bean
into a jsp page
â
<jsp:useBean>
â
used to associate a bean with the given "id" and "scope" attributes.
â
<jsp:setProperty>
â
used to set the value for a beans property mainly with the "name"
attribute which defines a object already defined with the same
scope. Other attributes are "property", "param", "value"
â
<jsp:getProperty>
â
used to get the referenced beans instance property and stores in
Rules for using Java Beans
â
Package should be first line of Java bean
â
Bean should have an empty constructor
â
All the variables in a bean should have "get", "set" methods.
â
The Property name should start with an Uppercase letter when
used with "set", "get" methods.
â
For example the variable "name" the get, set methods will be
getName(), setName(String)
Using Java beans â Example
package pack;public class Counter {
int count = 0; String name;
public Counter() { } public int getCount() {
return this.count; }
public void setCount(int count){ this.count = count;
}
public String getName(){ return this.name; }
public void setName(String name){ this.name=name;
} }
package pack;
public class Counter {
int count = 0; String name;
public Counter() { } public int getCount() {
return this.count; }
public void setCount(int count){ this.count = count;
}
public String getName(){ return this.name; }
public void setName(String name){ this.name=name;
} }
Using Java beans from a JSP
<%@ page language="java" %>
<%@ page import="pack.Counter" %>
<jsp:useBean id="counter" scope="page" class="pack.Counter" />
<jsp:setProperty name="counter" property="count" value="4" />
Get Value: <jsp:getProperty name="counter" property="count" /><BR>
<jsp:setProperty name="counter" property="name" value="prasad" />
Get Name: <jsp:getProperty name="counter" property="name" /><BR>
<%@ page language="java" %>
<%@ page import="pack.Counter" %>
<jsp:useBean id="counter"
scope="page"
class="pack.Counter" />
<jsp:setProperty name="counter" property="count" value="4" />
Get Value: <jsp:getProperty name="counter" property="count" /><BR>
<jsp:setProperty name="counter" property="name" value="prasad" />
Get Name: <jsp:getProperty name="counter" property="name" /><BR>
â
The created bean is associated with a scope or context:
âpage
â
request
âsession
âapplication
JSP Tag Libraries
â
Tag libraries are used to extend the list of supported action
tags.
â
The tags encapsulate Java code.
â
They are implemented using standard APIs.
â
Cleaner than inserting code directly in the page.
âEasier for designers to work around.
â
Facilitates reuse.
â
The use of the âtaglibâ directive indicates that a page uses a
taglib.
â
<%@ taglib uri="tagLibraryURI" prefix="tagPrefix" %>
â
Used as
<tagPrefix:doSomething>â¦â¦..</tagPrefix:doSomething>
â
You can write your own or use third-party libraries.
Some JSP Tag Libraries
â
Core Tags
â
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
âSome tags : <c:out >, <c:if>, <c:choose>, <c:forEach >, ...
â
Formatting tags
â
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
âSome tags : <fmt:formatNumber>, <fmt:formatDate>, ...
â
SQL tags
â
<%@ taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql" %>
â<sql:setDataSource>, <sql:query>, <sql:update>, ...
â
XML tags
â
<%@ taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
â<x:parse>, <x:transform >, ...
â
JSTL Functions
â
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
âfn:contains(), fn:endsWith() , fn:length() , fn:startsWith(), fn:substring(), ...
Example of tag lib â Accessing database
<%@ page import="java.io.*,java.util.*,java.sql.*"%><%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <html>
<head>
<title>SELECT Operation</title> </head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST" user="root" password="pass123"/> <sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees; </sql:query>
...
<%@ page import="java.io.*,java.util.*,java.sql.*"%>
<%@ page import="javax.servlet.http.*,javax.servlet.*" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%> <html>
<head>
<title>SELECT Operation</title> </head>
<body>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost/TEST" user="root" password="pass123"/> <sql:query dataSource="${snapshot}" var="result">
SELECT * from Employees; </sql:query>
Example of tag lib â Database Access
....<table border="1" width="100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr>
<c:forEach var="row" items="${result.rows}"> <tr> <td><c:out value="${row.id}"/></td> <td><c:out value="${row.first}"/></td> <td><c:out value="${row.last}"/></td> <td><c:out value="${row.age}"/></td> </tr> </c:forEach> </table> </body> </html> ....
<table border="1" width="100%"> <tr> <th>Emp ID</th> <th>First Name</th> <th>Last Name</th> <th>Age</th> </tr>
<c:forEach var="row" items="${result.rows}"> <tr> <td><c:out value="${row.id}"/></td> <td><c:out value="${row.first}"/></td> <td><c:out value="${row.last}"/></td> <td><c:out value="${row.age}"/></td> </tr> </c:forEach> </table> </body> </html>