• No results found

Java Enterprise Edition The Web Tier

N/A
N/A
Protected

Academic year: 2021

Share "Java Enterprise Edition The Web Tier"

Copied!
59
0
0

Loading.... (view fulltext now)

Full text

(1)

Java Enterprise Edition

The Web Tier

(2)

Objectives of this Course

Focus on Presentation

(3)

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

(4)

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 SE

EJB

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 SE

Applet

Applet

Container

Java SE HTTP SSL HTTP SSL Database JDBC JDBC RMI/IIOP
(5)

Java Web Application request handling

●

Servlet technology serves as the base to build Web Applications

(6)
(7)

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

(8)

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

(9)

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)

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)

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)

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

(13)

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.

(14)

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

(15)

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())

…

(16)

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();

(17)
(18)

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>

(19)

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

(20)

Deployment - the WAR File

killerapp.war

whack. html vendor.xml

crimeportal

classes

WEB-INF

web.xml AssassinationServlet
(21)

Session 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.

(22)

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);

…

}

(23)

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

(24)

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);

}

(25)

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);

}

(26)

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>

(27)

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>

(28)

@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

(29)
(30)

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

(31)

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.

(32)

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

(33)

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.

(34)

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);

}

(35)
(36)

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.

(37)

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.

(38)

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}

●
(39)

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

(40)

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:8080

USER 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

(41)

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:

(42)

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: “

<%= … %>

”

(43)

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

(44)

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>

(45)

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>

(46)

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

(47)

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

(48)

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

(49)

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.

(50)

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

(51)

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

(52)

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

(53)

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)

(54)

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;

} }

(55)

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

(56)

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.

(57)

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(), ...

(58)

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>

(59)

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>

References

Related documents

As Halley demonstrates in “Rape at Rome: Feminist Interventions in the Criminalization of Sex-Related Violence in Positive International Criminal Law” (2008), feminists advanced

Students will apply knowledge of literary techniques, including foreshadowing, metaphor, simile, personification, onomatopoeia, alliteration, and flashback, to understand

Finally, a global partnership for development will only be achieved when affected communities – including people who use drugs and subsistence farmers involved in illicit

Consequently, this study ex- plored formula feeding bottles as a potential source of exposure to bacterial contamination for in- fants and young children, and assessed the

Extrasystoles from the outflow tract may pro- voke ventricular fibrillation or tachycardia in coexistent is- chaemic heart disease (even during acute infarction),

The local thermal equilibrium implies several assumptions, like low fluid velocities, fast energy exchange between the phases and a smooth spatial temperature distribution.... 2.1

Rezultati Post - hoc LSD testa za broj tankih stabala svih vrsta drveća prema kategorijama povijesnog vlasništva (kategorija vlastelini tretirana objedinjeno).. 40

large compared to the estimates of financial means available to terrorist organizations. While substantial amounts of assets were frozen in the aftermath of the