Transcript Servlets

Servlets
▮ Explain how browsers and servers work
▮ Use Page Designer to create web pages
▮ Explain how servlets work
▮ Show how to define a form to invoke a
servlet
Chapter 8
© copyright Janson Industries 2014
1
New Source of Documentation
Chapter 8
© copyright Janson Industries 2014
http://download.oracle.com/javaee/7/api/
2
Servlets and JSPs
▮ Servlets are Java programs that
generate HTML which is sent to a
browser
▮ JSP’s (Java Server Pages) are HTML
with embedded Java commands
▮ The advantage over static web pages:
servlets and JSP’s can dynamically build
web pages and their content
Chapter 8
© copyright Janson Industries 2014
3
Servlets and JSP’s
▮ In actuality, JSP’s are converted into
Servlets by the JSP “container”
▮ Need a server that provides Servlet and
JSP containers – an application server
▮ Before we can create need to:
▮ Explain how browser, server & servlets work
▮ Show some alternatives for building servlets:
▮ Source code
▮ RAD Page Designer
Chapter 8
© copyright Janson Industries 2014
4
Servers
▮ When a link is clicked or a URL is entered,
the browser sends a request to the server
▮ There are many type of requests
▮ Primarily, browsers send get and post requests
▮ A browser get request asks for a file’s
contents, a post sends HTML FORM info
▮ If the get request identifies a html file, the
server sends the html back to the client as
part of a response
Chapter 8
© copyright Janson Industries 2014
5
Servlets
▮ If a request identifies a servlet, servlet is
run i.e. its init() method is run
▮ if a constructor exists, it will be run also
▮ If a get request, server also invokes the
doGet method of the servlet
▮ What method does a post request invoke?
▮ Server also passes 2 objects to the servlet:
HttpServletRequest
Chapter 8
HttpServletResponse
© copyright Janson Industries 2014
6
Servlets
Users PC
Browser
S/W
1
URL
.class
Server
2
Get request
for servlet
Server
S/W
Req &
Resp
objects
.CLASS
3
Load and
run servlet
Servlet
User
Chapter 8
© copyright Janson Industries 2014
7
Servlets
▮ The servlet modifies the response
object
▮ When the servlet finishes, the
response is passed back to the server
▮ The server returns the modified
response object back to the browser
Chapter 8
© copyright Janson Industries 2014
8
Servlets
Server
Users PC
Browser
S/W
5
Response
w/ HTML
6
Display
Web Page
Server
S/W
4
Response
object
Servlet
User
Chapter 8
© copyright Janson Industries 2014
9
Server based apps can’t be stored in a Java project
We will create and use a Dynamic Web project
File, New, Project, Dynamic Web Project
Chapter 8
© copyright Janson Industries 2014
10
New project - MyWeb
Must create an EAR then add MyWeb to EAR
Chapter 8
© copyright Janson Industries 2014
11
New EAR project - MyWebEAR
RAD will ask for perspective
switch to JEE, click Yes
© copyright Janson Industries 2014
12
Chapter 8
Chapter 8
© copyright Janson Industries 2014
13
Select JSTL (Java Standard Tag Library) Facet
Chapter 8
© copyright Janson Industries 2014
14
Will ask for perspective switch to Web, click Yes
Chapter 8
© copyright Janson Industries 2014
15
Opens Technology Quickstarts pane which has links to
tutorials/help for common web development actions
(They’re OK)
Chapter 8
© copyright Janson Industries 2014
16
Create an initial web page:
Click on MyWeb then File, New, Web Page
Specify file name, HTML/XHTML, click Finish
Chapter 8
© copyright Janson Industries 2014
17
Servers
▮ Servers require that web app resources be
stored in specific locations, i.e.
▮ Web pages are stored in a particular folder
▮ Servlets are stored in a particular folder
▮ RAD picks the correct folder: WebContent
Chapter 8
© copyright Janson Industries 2014
18
Page Designer started - graphical tool
Defaults to Split view
Click on page & type to insert new text...
8
Janson Industries 2014
19
orChapter
select
HTML tags© copyright
(page
components) from palette...
Click Palette tab to display components
Multiple trays of components
Chapter 8
© copyright Janson Industries 2014
20
Or insert other components (Images, Links, Lines,
Tables,
etc.)2014
Chapter 8
© copyright
Janson Industries
21
Insert a form by clicking on the Form Tags tray
Click on Form and then on the page
Chapter 8
© copyright Janson Industries 2014
22
Shows form in design view and inserts the HTML
Chapter 8
© copyright Janson Industries 2014
23
Must put other visual components in the form
Click Text Field then click inside form
Specify properties and click OK
Name is very important!
Chapter 8
© copyright Janson Industries 2014
24
Places component at cursor location
Move by click and drag...
...but Web pages are line oriented (as opposed to
Frames) Have to put in blank lines and spaces to drag
Chapter 8
© copyright Janson Industries 2014
25
Display and change component properties:
Select component, switch to Properties view (may need
to click Window, Show View, Properties)
Chapter 8
© copyright Janson Industries 2014
26
Put in 3 new lines (Enter 3 times) in web
page then clicked ListBox and the last line
Specify LB properties
Must click Add to specify values
Chapter 8
© copyright Janson Industries 2014
27
Chapter 8
© copyright Janson Industries 2014
28
Click and drag on resize handles to reshape or
change properties
Chapter 8
© copyright Janson Industries 2014
29
Chapter 8
© copyright Janson Industries 2014
30
Text Field
List Box
Drop Down Menu
Notice in DDM that selected item (Inventory) not chosen
Chapter 8
© copyright Janson Industries 2014
31
Switch to Preview pane
Employee item in list is selected and listed at top and
Inventory in DDM is selected and displayed
Chapter 8
© copyright Janson Industries 2014
32
To format: select component (or components), click
Format
Chapter 8
© copyright Janson Industries 2014
33
Choose format options
Chapter 8
© copyright Janson Industries 2014
34
You get the idea…
I’ll add text and pretty it up a little
Chapter 8
© copyright Janson Industries 2014
35
Alternative view: Source
Chapter 8
© copyright Janson Industries 2014
36
Of course, you can modify source directly
Forms must have a submit button!
Chapter 8
© copyright Janson Industries 2014
37
Chapter 8
© copyright Janson Industries 2014
38
Chapter 8
© copyright Janson Industries 2014
39
In Class Assg
▮ Create a page called Functions2 that has
form and a drop down box with options for:
▮ Customer
▮ Sale
▮ Create two pages (Cust.html and Sale.html)
that:
▮ Have forms with text fields and text to enter
customer and transaction info that look like the
following...
Chapter 8
© copyright Janson Industries 2014
40
Chapter 8
© copyright Janson Industries 2014
41
Chapter 8
© copyright Janson Industries 2014
42
A trick to get all the components to line up:
Invisible tables (tables with Border = 0)
Chapter 8
© copyright Janson Industries 2014
43
Chapter 8
© copyright Janson Industries 2014
44
TXServlet Example
▮ Need to change web page such that:
▮ The Functions form calls a servlet
▮ The servlet builds/returns the correct response
▮ Servlet will echo back data entered and
selections made by the user on
Functions.html
Chapter 8
© copyright Janson Industries 2014
45
TXServlet Example
▮ This means the servlet has to:
▮ Read the page components contents from
the request
▮ Write html and the page components
contents to the response
Chapter 8
© copyright Janson Industries 2014
46
To create a servlet for the first time: File, New, Other
Expand Web and select Servlet
Chapter 8
© copyright Janson Industries 2014
47
Notice RAD knows where to save source
Specify name and then click Finish
Chapter 8
© copyright Janson Industries 2014
48
Basic methods are created. Need to change so functions
and emp num sent back as text on a page
Notice that doGet and doPost expect Response and
Request objects as parameters, will change parameter
names to resp and req
Chapter 8
© copyright Janson Industries 2014
49
To tie a web page to the servlet, in Design view of page
click form outline or in Properties pane the form tab
Chapter 8
copyright Janson Industries 2014
Then ©click
the Action button
50
RAD will display the available servlets
Select a servlet and click the OK button
Chapter 8
© copyright Janson Industries 2014
51
Drop Down Menu
■ To retrieve the selected item from the
DDM use the request object’s
getParmeter method
♦ Remember form data imbedded in the
request
♦ Each of the forms visual components is a
request “parameter”
■ Syntax is:
String func = req.getParameter(“DDMName");
Chapter 8
© copyright Janson Industries 2014
52
Tieing To Other Pages
■ A response object’s sendRedirect()
method allows you to redirect the
browser to another url
if (func.equals(“other”)) {
resp.sendRedirect(“Otherpage.html");
}
Chapter 8
© copyright Janson Industries 2014
53
In Class Assg 2
▮ Create a servlet called FuncServlet that is
▮ Called by Functions2.html
▮ Based on the selected function, redirects to
either Cust.html or Sale.html
Functions2
.html
User
FuncServlet
Cust or
Sale.html
Assg 2 Solution
Chapter 8
© copyright Janson Industries 2014
54
Writing to a Response
▮ Servlets need two objects to manipulate
a Response object:
▮ PrintWriter
▮ OutputStream
▮ The PrintWriter, OutputStream, and
Response are “tied together”
▮ The PrintWriter feeds the OutputStream,
which writes to the Response
Chapter 8
© copyright Janson Industries 2014
55
Servlets
▮ PrintWriter takes Strings and numbers
and converts to a text output stream
▮ OutputStream converts a text output
stream to a binary stream
Text
PrintWriter Stream
Primitives
& Strings
Chapter 8
Output
Stream
Binary
Stream
Response
© copyright Janson Industries 2014
56
Servlets
▮ The Response object has a method that
returns a OutputStream object that is tied to
the repsonse:
resp.getOutputStream()
▮ Must create a PrintWriter object and pass it the
OutputStream object (ties the two together)
▮ Standard syntax to create PrintWriter object:
PrintWriter out = new PrintWriter(resp.getOutputStream());
▮ Don’t forget to import the class
import java.io.PrintWriter;
Chapter 8
© copyright Janson Industries 2014
57
Servlets
▮ Use the request object to retrieve info from page
components then assign to variables:
String empNum = req.getParameter(“EmpNum”);
String funcLB = req.getParameter(“FuncLB”);
String funcDD = req.getParameter(“FuncDD”);
▮ HTML for basic page:
out.println("<HTML>");
out.println("<HEAD><Title>Servlet Response</Title></HEAD>");
out.println("<BODY>");
out.println("</BODY>");
out.println("</HTML>");
Chapter 8
© copyright Janson Industries 2014
58
Servlets
▮ HTML for page body content
out.println("The Employee Number passed was: "
+ EmpNum);
out.println("The List Box function was: " +
FuncLB);
out.println("The Drop Down List function was: "
+ FuncDD);
Chapter 8
© copyright Janson Industries 2014
59
import java.io.PrintWriter;
:
:
:
:
public void doGet(javax.servlet.http.HttpServletRequest req,
javax.servlet.http.HttpServletResponse resp)
{ resp.setContentType("text/html");
try
{ PrintWriter out = new PrintWriter(resp.getOutputStream());
String empNum = req.getParameter("EmpNumTF");
String funcLB = req.getParameter("FuncLB");
String funcDD = req.getParameter("FuncDD");
out.println("<HTML>");
out.println("<HEAD><Title>Servlet Response</Title></HEAD>");
out.println("<BODY>");
out.println("The Employee Number passed was: " + empNum);
out.println("The List Box function was: " + funcLB);
out.println("The Drop Down List function was: " + funcDD);
out.println("</BODY>");
out.println("</HTML>");
out.close();
}
catch (Exception e)
{
System.out.println("Sample Servlet failed: ");
e.printStackTrace();
Chapter
8
© copyright Janson Industries 2014
}
}
60
To tie Web page and servlet together: specify that when
Chapter 8
© copyright Janson Industries 2014
61
SubmitBtn
clicked, TxServlet called
Start by clicking form outline in Design view or form tab
in Properties pane to display Properties
Chapter 8
© copyright Janson Industries 2014
Then click Action
button and select Servlet
62
RAD will display the available servlets
Select TxServlet and click the OK button
Chapter 8
© copyright Janson Industries 2014
63
Will not work in Preview pane
Must run the web page on server
In lab must sign on with IBM id
In Project Explorer:
Chapter 8
copyright Janson Industries 2014
64
Right
click the web©page,
select Run as, Run on Server
If a server isn't already defined...
Chapter 8
© copyright Janson Industries 2014
65
If first time or in lab, create a new Test server
Chapter 8
© copyright Janson Industries 2014
66
Deselect RMI and IPC. Soap plays nicer with the
firewall.
Chapter 8
© copyright Janson Industries 2014
67
If not first time or not in lab, use existing server
Chapter 8
© copyright Janson Industries 2014
68
If you get an error, click the Details button and follow
instructions
Chapter 8
© copyright Janson Industries 2014
69
Server Problems
▮ How to fix server errors when running
servlets
▮ Turn off your firewall
▮ Turn off anti-virus s/w (or configure it so
RAD has total authority)
▮ Run RAD as an administrator
▮ Right click RAD icon/menu item
▮ Select Run as administrator
Chapter 8
© copyright Janson Industries 2014
70
Server Problems
▮ Profile name AppSrv1 is invalid. Specify
a profile name that exists on the server.
▮ Click here for document with instructions
on how to create server profile name
Chapter 8
© copyright Janson Industries 2014
71
Server Problems
▮ If resource not found error
▮ In Servers pane, right click server
▮ Select Add and Remove
▮ Click Remove All then Finish
▮ This forces the server to reload the project the next
time it is run
▮ In Explorer pane select the project
▮ In Command bar click on Project
▮ Select Clean
▮ Forces RAD to rebuild the project
Chapter 8
© copyright Janson Industries 2014
72
First time will take a while!
Page (eventually)
displayed in browser pane
If not, click refresh
© copyright Janson Industries 2014
Notice all the messages
generated by the server 73
Chapter 8
Enter info, click Submit
Chapter 8
© copyright Janson Industries 2014
74
Chapter 8
© copyright Janson Industries 2014
75
In Class Assg 3 - SaleServlet
▮ Sale.html should invoke SaleServlet
▮ Create SaleServlet to:
▮ Echo back the data from the Sale Web Page
Sale.html
User
Chapter 8
HTML (response)
With Sale info
© copyright Janson Industries 2014
Sale
Servlet
76
In Class Assg 3 - SaleServlet
Solution
Chapter 8
© copyright Janson Industries 2014
77
In Class Assg 4 - Servlets
co
Creates
Func2
Servlet
Cust.html
User
Chapter 8
HTML (response)
With Cust info
Customer
object
Creates
co
request
response
© copyright Janson Industries 2014
Retrieves info
Cust
Servlet
78
Display Functions2,
choose Customer
Enter some info
Click Submit
Func2Servlet creates
Customer &
CustServlet objects,
Chapter
8
invokes
doGet... © copyright Janson Industries 2014
Voila
79
In Class Assg 4 - CustServlet
▮ Cust.html should invoke Func2Servlet
that:
▮ Creates a Customer object, assigns to a
variable called co, populates object with
page data
▮ Must copy Customer class into MyWeb
▮ Code CustServlet such that:
▮ doGet also expects a Customer variable
▮ Echoes back data from Customer object
Chapter 8
© copyright Janson Industries 2014
80
In Class Assg 4 - CustServlet
▮ Func2Servlet will invoke CustServlet
differently
▮ Instead of Func2Servlet redirecting to
CustServlet, Func2Servlet:
▮ Instantiates a CustServlet object (cs)
▮ Invokes cs.doGet method passing co, the
request, and the response
Solution
Chapter 8
© copyright Janson Industries 2014
81
All In Class Assgs Example
CO
FuncServlet
Cust.html
Functions2
.html
Creates
Func2
Servlet
Customer
object
Request
Response
CO
Cust or
Sale.html
HTML (response)
With Cust info
User
Sale.html
HTML (response)
With Sale info
Chapter 8
© copyright Janson Industries 2014
Retrieves info
Cust
Servlet
Sale
Servlet
82
Chapter 8 Tutorial
▮ To turn in the C8 (and C9) tutorial:
▮ Export the dynamic web project as a
WAR file
▮ Give the WAR file the same name as the
project with your initials at the end
▮ Send the WAR as an email attachment to
me at [email protected]
▮ I will let you know within 1 business day
that I received it, if you don’t hear
from me I didn’t get it
Chapter 8
© copyright Janson Industries 2014
83