Title: Internet programming Integrating Servlets and JSPs
1Internet programmingIntegrating Servlets and JSPs
- Prof. Dr.-Ing. Holger Vogelsang
holger.vogelsang_at_hs-karlsruhe.de
2Integrating Servlets and JSPs Contents
- Architecture and Protocols
- Dynamic HTML pages
- Servlets
- JavaServer Pages
- Combination of Servlets and JavaServer Pages
- Forwarding requests
- Including resource contents
- Forwarding from a JSP
- Expression language
- Taglibs
- Applets as front ends for Servlets
3Integrating Servlets and JSPs Idea
- Servlets
- Servlets are useful, when a lot of programming is
needed. - Servlets can modify HTTP status codes and
headers, use cookies, compress pages, ... - But generating HTML is difficult and hardly
modifiable by web designers. - JSP
- JSP documents can be created using normal web
tools. - Expressions, scriptlets and declarations are
useful to integrate dynamic behavior into the
page. - Directives control the layout of the document.
- Beans contain complicated Java code.
4Integrating Servlets and JSPs Idea
- So, where's the problem?
- A JSP is useful, if it contains the entire layout
of the resulting page. - But what happens, if the result is completely
different depending on the request parameters? - JSP and taglib documents have a static structure.
- Solution
- Using a combination of servlets and JSP
documents - A Servlet accepts a complicated request.
- It precalculates some results and stores them in
a Java bean. - It forwards the request to one of multiple JSPs
or it generates some output and integrates the
output of one or more JSPs. - Forwarding can be handled on the server side
without any client access.
5Integrating Servlets and JSPs Idea
- Integration of servlet and JSPs, simple scenario
selecting a JSP - Integration of servlet and JSPs, scenario with a
Java bean
Browser
forward
request
Servlet
JSP
response
JSP
Servlet engine
Java Bean
Session Context
create bean
access bean
Browser
forward
request
Servlet
JSP
response
Servlet engine
6Integrating Servlets and JSPs Forwarding
requests
- A RequestDispatcher is used to forward requests
and to include external contents. - Getting a RequestDispatcher object
- RequestDispatcher dispatcher
- getServletContext().getRequestDispatch
er(url) - getServletContext() is a method of HttpServlet.
- url is a URL relative to the root directory of
the application (here relative to /IP). - Example (RequestDispatcher for /presentations/pres
entation1.jsp) - String url "/presentation/presentation1.jsp"
- RequestDispatcher dispatcher
- getServletContext().getRequestDispatch
er(url) - If the requested URL is a static HTML page, this
page should have the file extension .jsp.
Otherwise forwarding a POST request does not work
(a GET request will work).
7Integrating Servlets and JSPs Forwarding
requests example
- The following example asks the user for a payment
method. Depending on the selection one of four
JSP documents is shown. - Entry page (Payment.jsp)
8Integrating Servlets and JSPs Forwarding
requests example
- Source code
- lthtmlgt
- ltheadgt
- lttitlegtPayment methodlt/titlegt
- lt/headgt
- ltbodygt
- lth2gtHow do you want to pay?lt/h2gt
- ltform action"/IP/servlet/hska.faki.PaymentServle
t"gt - ltinput typeradio name"Paymentmethod"
value"Creditcard" checkedgt - CreditcardltBRgt
- ltinput typeradio name"Paymentmethod"
value"Check" gt CheckltBRgt - ltinput typeradio name"Paymentmethod"
value"Credit" gt CreditltBRgt - ltinput typesubmit value"Ok"gt
- lt/formgt
- lt/bodygt
- lt/htmlgt
9Integrating Servlets and JSPs Forwarding
requests example
- The Servlet examines the payment type and
forwards the request to a JSP document (File
PaymentServlet.java) - public class PaymentServlet extends HttpServlet
- public void doGet(HttpServletRequest request,
- HttpServletResponse
response) - throws
ServletException, IOException - String payment request.getParameter("Paymen
tmethod") - if (payment null)
- forwardTo("/JSP/NoPayment.jsp", request,
response) -
- else if (payment.equals("Creditcard"))
- forwardTo("/JSP/CreditcardPayment.jsp",requ
est,response) -
- else if (payment.equals("Check"))
- forwardTo("/JSP/CheckPayment.jsp",
request, response) -
10Integrating Servlets and JSPs Forwarding
requests example
- else if (payment.equals("Credit"))
- forwardTo("/JSP/CreditPayment.jsp",
request, response) -
-
- private void forwardTo(String url,
- HttpServletRequest
request, - HttpServletResponse
response) - throws
ServletException, IOException - RequestDispatcher dispatcher
- dispatcher getServletContext().getRequestDi
spatcher(url) - dispatcher.forward(request, response)
-
-
11Integrating Servlets and JSPs Forwarding
requests example
- Requested JSP for creditcard payment (File
CreditcardPayment.jsp)
12Integrating Servlets and JSPs Forwarding
requests example
- Source code
- lthtmlgt
- ltheadgt
- lttitlegtCreditcard paymentlt/titlegt
- lt/headgt
- ltbodygt
- lth2gtPlease enter your creditcard
informationlt/h2gt - ltformgt
- lttablegt
- lttrgt
- lttdgtNumberlt/tdgtlttdgtltinput type"text"
name"number" size"12" -
maxLength"12"gtlt/tdgt - lt/trgt
- lttrgt
- lttdgtExp. datelt/tdgtlttdgtltinput type"text"
name"number" - size"12"
maxLength"12"gtlt/tdgt - lt/trgt
- lt/tablegt
- lt/formgt
13Integrating Servlets and JSPs Forwarding
requests example
- Requested JSP for credit payment (File
CreditPayment.jsp)
14Integrating Servlets and JSPs Forwarding
requests example
- Source code
- lthtmlgt
- ltheadgt
- lttitlegtCredit paymentlt/titlegt
- lt/headgt
- ltbodygt
- lth2 style"colorred"gtNice jokelt/h2gt
- lt/bodygt
- lt/htmlgt
15Integrating Servlets and JSPs Forwarding
requests sending data to the destination page
- Using the previous description, a JSP can access
all forwarded request information (parameters,
...). - This is in practice not a good idea
- It's easier to write complicated applications as
Servlets. - Often, all destination JSP documents have to
process the data in a similar way. We would
produce a lot of code by copy and paste. - Improved idea
- The Servlet processes the data and stores the
information in one or more beans. - There are three different places to store the
information - request scope Data is removed when request is
answered. - session scope Data is removed when session
terminates. - application scope Data is removed when web
application terminates.
16Integrating Servlets and JSPs Forwarding
requests sending data to the destination page
17Integrating Servlets and JSPs Forwarding
requests sending data to the destination page
Java Bean
Java Bean
Request Context
Java Bean
create Bean
access Bean
access Bean
request1
response
forward
forward
Servlet
JSP
JSP
access Bean
access Bean
Application Context
Java Bean
Java Bean
access Bean
request2
response
JSP
18Integrating Servlets and JSPs Forwarding
requests relative URLs
- Forwarding vs. redirection
- response.sendRedirect
- The client is asked to display a new URL.
- Request data can be lost.
- A new URL is used.
- dispatcher.forward
- The server handles the forwarding.
- Request data is kept.
- The original URL is kept.
- Relative URLs and forwarding
- Suppose, a Servlet forwards the request to a JSP.
- The JSP adds links with relative URLs (IMG-Tag,
A-Tag, ... ). - Relative links are interpreted relative to the
original (Servlet) directory, not relative to the
JSP directory! - Solution Use absolute server URLs.
19Integrating Servlets and JSPs Forwarding
requests an example
- This example has a Servlet that reads the
firstName and lastName request parameters. - If they are both present, it forwards the user to
a page that displays them. - If one of the request parameters is missing or is
an empty string, it uses previously seen values
from that client. - If values are still missing after that, it
forwards the user to a page that tells them which
parameter is missing. - A session-based bean is used for sharing.
20Integrating Servlets and JSPs Forwarding
requests an example
Session Context
Java Bean
access Bean
access Bean
response
forward
Register.html
Registration-Servlet
ShowName.jsp
request
get
21Integrating Servlets and JSPs Forwarding
requests an example
- Entry page (Register.html)
22Integrating Servlets and JSPs Forwarding
requests an example
- Source code (file Register.html)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtRegistrationlt/titlegtlt/headgt
- lth1 align"center"gtRegistrationlt/h1gt
- ltform action"/IP/servlet/hska.faki.RegistrationS
ervlet"gt - lttablegt
- lttrgt
- lttdgtFirst namelt/tdgt
- lttdgtltinput type"text" name"firstName"
value"" size"30" - maxLength"40"gtlt/tdgt
- lt/trgt
- lttrgt
- lttdgtLast namelt/tdgt
- lttdgtltinput type"text" name"lastName"
value"" size"30" - maxLength"40"gtlt/tdgt
- lt/trgt
- lt/tablegt
23Integrating Servlets and JSPs Forwarding
requests an example
24Integrating Servlets and JSPs Forwarding
requests an example
- Called Servlet
- public class RegistrationServlet extends
HttpServlet - public void doGet(HttpServletRequest request,
- HttpServletResponse
response) - throws
ServletException, IOException - HttpSession session request.getSession(true
) - NameBean nameBean
- (NameBean)session.getAttribut
e("nameBean") - if (nameBean null)
- nameBean new NameBean()
- session.setAttribute("nameBean",
nameBean) -
- String firstName request.getParameter("firs
tName") - if (firstName ! null)
- nameBean.setFirstName(firstName)
-
25Integrating Servlets and JSPs Forwarding
requests an example
- String lastName request.getParameter("lastN
ame") - if (lastName ! null)
- nameBean.setLastName(lastName)
-
- RequestDispatcher dispatcher
- getServletContext().getRequestDispatcher(
-
"/JSP/ShowName.jsp") - dispatcher.forward(request, response)
-
-
26Integrating Servlets and JSPs Forwarding
requests an example
- Forwarded JSP
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtThanks for Registeringlt/titlegt
- lt/headgt
- ltbodygt
- lth1gtThanks for Registeringlt/h1gt
- ltjspuseBean id"nameBean" class"hska.faki.NameB
ean" - scope"session" /gt
- lth4gtFirst Name
- ltjspgetProperty name"nameBean"
property"firstName" /gt - lt/h4gt
- lth4gtLast Name
- ltjspgetProperty name"nameBean"
property"lastName" /gt - lt/h4gt
- lt/bodygt
- lt/htmlgt
27Integrating Servlets and JSPs Forwarding
requests an example
- The bean class (NameBean.java)
- public class NameBean
- private String firstName "Missing first
name" - private String lastName "Missing last
name" - public NameBean()
-
- public NameBean(String nFirstName, String
nLastName) - setFirstName(nFirstName)
- setLastName(nLastName)
-
-
- public String getFirstName()
- return firstName
-
-
- public void setFirstName(String nFirstName)
- firstName nFirstName
28Integrating Servlets and JSPs Forwarding
requests an example
- public String getLastName()
- return lastName
-
-
- public void setLastName(String nLastName)
- lastName nLastName
-
-
29Integrating Servlets and JSPs Forwarding
requests an example
- Improved version Input validation using
JavaScript (RegisterImproved.html) - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgtltheadgtlttitlegtRegistrationlt/titlegt
- ltscript language"JavaScript"gt
- lt!--
- function chkForm()
- if (document.registration.firstName.value
"") - alert ("Please enter your first name!")
- document.registration.firstName.focus()
- return false
-
- if (document.registration.lastName.value
"") - alert ("Please enter your last name!")
- document.registration.lastName.focus()
- return false
-
- return true
-
- //--gt
30Integrating Servlets and JSPs Forwarding
requests an example
- lth1 align"CENTER"gtRegistrationlt/h1gt
- ltform name"registration" onSubmit"return
chkForm()" - action "/IP/servlet/hska.faki.Registrati
onServlet"gt - lttablegt
- lttrgt
- lttdgtFirst namelt/tdgt
- lttdgtltinput type"text" name"firstName"
value"" size"30" - maxLength"40"gtlt/tdgt
- lt/trgt
- lttrgt
- lttdgtLast namelt/tdgt
- lttdgtltinput type"text" name"lastName"
value"" size"30" - maxLength"40"gtlt/tdgt
- lt/trgt
- lt/tablegt
- ltinput type"submit" value"Register"gt
- lt/formgt
- lt/bodygt
31Integrating Servlets and JSPs Forwarding
requests an example
- Pressing Register with empty text fields
32Integrating Servlets and JSPs Contents
- Architecture and Protocols
- Dynamic HTML pages
- Servlets
- JavaServer Pages
- Combination of Servlets and JavaServer Pages
- Forwarding requests
- Including resource contents
- Forwarding from a JSP
- Expression language
- Taglibs
- Applets as front ends for Servlets
33Integrating Servlets and JSPs Including
resource contents
- Forward gives the complete control over the
response generation to another document. - The include method of a RequestDispatcher is used
to include the output of other resources like
JSPs, Servlets and HTML files. - Getting a RequestDispatcher object (does not
differ) - RequestDispatcher dispatcher
- getServletContext().getRequestDispatch
er(url) - Calling the include method of the request
dispatcher gives control temporarily to another
document. - This document creates some output data.
- The output data is appended to the callers
response. - The caller receives control back after completing
the included document.
34Integrating Servlets and JSPs Including
resource contents
- Integration of Servlets and JSPs, simple scenario
selecting a JSP - Integration of Servlets and JSPs, scenario with a
Java bean
Browser
include
request
Servlet
JSP
response
JSP
Servlet engine
Java Bean
Session Context
create bean
access bean
Browser
include
request
Servlet
JSP
response
Servlet engine
35Integrating Servlets and JSPs Including
resource contents a modified example
Session Context
Java Bean
access Bean
access Bean
request
include
Register.html
Registration-Servlet
ShowName.jsp
get
response
36Integrating Servlets and JSPs Including
resource contents a modified example
- The modified Servlet (RegistrationIncludeServlet.j
ava) - public class RegistrationIncludeServlet extends
HttpServlet - public void doGet(HttpServletRequest request,
- HttpServletResponse
response) throws IOException - // ....
- RequestDispatcher dispatcher
- getServletContext().getRequestDispatche
r( -
"/JSP/ShowNameInclude.jsp") - dispatcher.include(request, response)
- PrintWriter writer response.getWriter()
- writer.println("Sorry, no contents
available.") - writer.println("lt/bodygtlt/htmlgt" )
-
-
37Integrating Servlets and JSPs Including
resource contents a modified example
- The JSP does not append the end tags
(ShowNameInclude.jsp) - lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgt
- lttitlegtThanks for Registeringlt/titlegt
- lt/headgt
- ltbodygt
- lth1gtThanks for Registeringlt/h1gt
- ltjspuseBean id"nameBean" class"hska.faki.NameB
ean" - scope"session" /gt
- lth4gtFirst Name
- ltjspgetProperty name"nameBean"
property"firstName" /gt - lt/h4gt
- lth4gtLast Name
- ltjspgetProperty name"nameBean"
property"lastName" /gt - lt/h4gt
No end tags!
38Integrating Servlets and JSPs Including
resource contents a modified example
JSP output
Servlet output
39Integrating Servlets and JSPs Contents
- Architecture and Protocols
- Dynamic HTML pages
- Servlets
- JavaServer Pages
- Combination of Servlets and JavaServer Pages
- Forwarding requests
- Including resource contents
- Forwarding from a JSP
- Expression language
- Taglibs
- Applets as front ends for Servlets
40Integrating Servlets and JSPs Forwarding from a
JSP
- Often requests are processed by Servlets and
forwarded to JSPs - Evaluating the request normally requires a lot of
programming ? Servlets are a better solution. - Generating the output using JSP is a good
solution, because the structure of the document
can be edited by web tools. - But this is not the only possible solution
- E.g. A JSP can forward the request to another
JSP, if an error state encounters. - Forwarding the request to a Servlet does not
differ from the mechanism described previously. - Syntax ltjspforward page"Relative URL" /gt
- Example with additional request parameters
- ltjspforward page"Relative URL"gt
- ltjspparam name"param1" value"value1" /gt
- ltjspparam name"param2" value"value2" /gt
- lt/jspforwardgt
41Integrating Servlets and JSPs Forwarding from a
JSP
- The page attribute can contain JSP expressions to
allow runtime evaluation.
forward
request
Browser
Servlet
JSP
response
jspforward
JSP
Servlet engine
42Integrating Servlets and JSPs Forwarding from a
JSP
- Example
- Depending on the value of a random generator,
different JSPs are used.
jspforward
Forward1.jsp
request
Browser
ForwardMain.jsp
Forward2.jsp
response
jspforward
Servlet engine
43Integrating Servlets and JSPs Forwarding from a
JSP
- Main page (ForwardMain.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgtltheadgt
- lttitlegtForwarding JSPslt/titlegt
- lt String destination
- String message
- if (Math.random() gt 0.5)
- destination "/JSP/Forward2.jsp"
- message "second half"
-
- else
- destination "/JSP/Forward1.jsp"
- message "first half"
-
- gt
- lt/headgtltbodygt
- ltjspforward page"ltdestinationgt" gt
- ltjspparam name"part" value"ltmessagegt" /gt
44Integrating Servlets and JSPs Forwarding from a
JSP
- Forwarded page (Forward1.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtForwarding JSPs - Page
1lt/titlegtlt/headgt - ltbodygt
- lth1gtForwarding JSPs - Page 1lt/h1gt
- Message ltrequest.getParameter("part")gt
- lt/bodygt
- lt/htmlgt
- Forwarded page (Forward2.jsp)
- lt!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0
Transitional//EN"gt - lthtmlgt
- ltheadgtlttitlegtForwarding JSPs - Page
2lt/titlegtlt/headgt - ltbodygt
- lth1gtForwarding JSPs - Page 2lt/h1gt
- Message ltrequest.getParameter("part")gt
- lt/bodygt
- lt/htmlgt
45Integrating Servlets and JSPs Forwarding from a
JSP