Transcript JSP

Java the UML Way
http://www.tisip.no/JavaTheUmlWay/
Web Programming With JavaServer Pages
Programming for the Web
Servlets
JavaServer Pages (JSP) basics
Inputting data from the user
Client side validation with JavaScript
Databases
Storing state information
Programming cookies
Programming sessions
The problem with reloading pages
versjon 2002-04-17
page 2-3
page 4-6
page 7-12
page 13-18
page 19
page 20-24
page 25-27
page 28
page 29-30
page 31
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21
Searching for Hotels on the Internet?
• You enter a city and get back a list of possible hotels.
• You examine the source code, and you find the hotel names hardcoded.
• Why doesn’t the page contain program logic that searches for the
hotels in a database?
• The answer is that the HTML code is specially adapted.
• The Web server receives your query for hotels in a specific city, sends
this query to a program that searches the database, and generates
HTML code with the applicable hotels.
• This code is then sent to the client in response to the query.
• This chapter is about this kind of programming.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 2
Different Ways of Programming for the Web
•
Dynamic on the client side, in the client’s browser
– An applet is a program that is downloaded to a Web client in connection with an
HTML page.
• The download takes a little longer than normal
• The browser prints an alert in the status line that Java is being started.
• In return, the user gets a page with far greater functionality than a purely static HTML
page offers.
– Various scripting languages have gradually made simple dynamics possible without
costing too much in download time.
– The user may examine the source code of these scripts.
•
Dynamic on the server side
– We fill in forms and push the Send-button.
– The data are handled by a program on the server side.
– This handling may involve specially created HTML pages that are sent back to the
client.
– We’ll use JavaServer Pages (JSP) to program the server side. Something called
servlets are the basis of JSP.
•
Software
– You’ll need a Web server that supports servlets and JSP.
– You’ll need the API online documentation for these classes.
– The book tells you how to install and use LiteWebServer from Gefion Software.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 3
Servlets
The service() message
is sent to the servlet
object every time a client
requests the page.
The servlet object no
longer exists, because
the web server has shut
down, or the servlet has
stopped, or for another
reason.
service()
init()
loaded
service()
The servlet object is created
and initiated when the server
starts, or when the page is
requested for the first time.
running
destroy()
dead
A servlet is a Java program that
runs on a Web server.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 4
The Servlet Object
• All clients work with the same servlet object.
• Any instance variables there might be can be updated by multiple
clients.
• Methods that work with the instance variables should be synchronized.
– For example, the synchronized java.util.Vector class should be used in
stead of the unsynchronized java.util.ArrayList.
• When a servlet is initialized, a pool of threads is usually generated that
the service() method runs in.
– A client that requests the servlet (and thereby the service() method) will be
assigned its own thread.
– This thread is returned to the pool after use.
– If a thread is requested and the pool is empty, the client has to wait, or the
pool can be expanded.
– By using a pool of threads, we avoid resource-intensive initialization
every time a request comes from a client.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 5
Example of Server-Side Programming
public class SimpleServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
source code
at the server side
PrintWriter out = response.getWriter();
out.print("<html>");
…see program listing 21.1…
out.println("</html>");
}
}
<html><head><title>An example of server side programming</title></head>
<body>
This page was downloaded: Mon Aug 27 10:54:14 GMT+02:00 2001
</body>
</html>
the request from the
client generates this
HTML source code
the browser
displays the page
Solve the problems, pp. 656-657.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 6
JavaServer Pages (JSP)
• A jsp file contains HTML code with elements of Java code.
• The user requests the jsp file directly.
– If this is a first request for this file, it will be converted to a servlet.
– The servlet is compiled and starts automatically.
– The result of the servlet’s service() method will be an HTML page that is
sent to the client and presented in the client’s browser.
•
A JSP page is thus an HTML page that is created by a servlet based on
a jsp file.
<!-Time.jsp E.L. 2001-08-27
--!>
<html><head><title>An example of server side programming</title></head>
<body>
This page was downloaded: <%= new java.util.Date() %>
</body>
</html>
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 7
Why JSP?
•
•
•
•
•
•
Only to avoid writing out.print() around the HTML elements?
No!
HTML is presentation.
A jsp file mainly contains HTML.
Web designers create HTML code.
Java programmers create Java classes dealing with the problem that’ll
be solved.
• Only small snippets of Java code are needed to link the jsp file to the
Java classes.
• However, this book is about programming, not design.
• In this book the jsp files are rather untypical, they’ll contain relatively
little HTML.
Solve the problems, page 658.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 8
JSP Predefined Objects and JSP Expressions
• Predefined objects
–
–
–
–
request, type: HttpServletRequest
response, type: HttpServletResponse
out, type: PrintWriter
session, type: HttpSession
• JSP expressions
– Surrounded by <%= and %>
– Examples:
This page was downloaded: <%= new java.util.Date() %> // No semicolon!
The server calculates 17 * 7 and gets <%= 17 * 7 %>
The client machine is: <%= request.getRemoteHost() %>
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 9
JSP Scriptlets
Java code surrounded by <% and %>, the same example in two ways:
Five random numbers in the interval [1, 100]:
<%
int sum = 0;
for (int i = 0; i < 5; i++) {
int number = (int) (100 * Math.random() + 1);
out.println("<br>" + number);
sum += number;
}
out.println("<br>" + "The sum is " + sum);
%>
The client output looks like this:
Five random numbers in the interval [1, 100]:
<%
int sum = 0;
for (int i = 0; i < 5; i++) {
int number = (int) (100 * Math.random() + 1);
%>
<br> <%= number %>
<%
sum += number;
}
%>
<br> The sum is <%= sum %>
Five random numbers in the interval [1, 100]:
86
7
43
91
3
The sum is 230
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 10
JSP Declarations
•
•
Local variables are declared inside scriptlets. Every client gets its own.
Variables declared outside become instance variables (common for all clients),
and they must be surrounded by <%! and %>
<%! private int noOfVisits = 0; %>
<% noOfVisits++; %>
No. of visits since servlet started = <%= noOfVisits %>
<br>
<% int counter = 0; %>
<% counter++; %>
Counter = <%= counter %>
•
The first time the servlet is accessed, we get this printout in the browser
window:
No. of visits since servlet started = 1
Counter = 1
•
The next time it looks like this:
No. of visits since servlet started = 2
Counter = 1
•
And so on:
No. of visits since servlet started = 3
Counter = 1
•
Every time the servlet restarts, the variable noOfVisits is set to zero.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 11
Comments and Directives
• Regular Java comments in the Java code
• JSP comments in the JSP code
<%-- this is a JSP comment, it can be several lines long --%>
• HTML comments for comments that should be sent to the browser
<!-- this is an HTML comment, it can be several lines long -->
• A JSP directive controls the construction of the servlet that is created
from the jsp file.
• A directive is enclosed between <%@ and %>.
• The page directive:
<%@ page import="myLibrary.Book, java.text.NumberFormat" %>
• The include directive, the contents of the file named are inserted before
the servlet is generated:
<%@ include file = "PersonForm.jsp"%>
Solve problems 1 and 2, page 662.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 12
Inputting Data from the User
<html><head>
<title>One Input Field</title>
</head>
<form action="ReadCountry.jsp" method="post">
<p>Enter Your Home Country:<br>
<input name="country" type="text" size="30">
<p>
<input type="submit" name="Send" value="Send">
<input type="reset" name="Reset" value="Reset">
</p>
</form>
</body></html>
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 13
What Happens After the User Presses the Send Button?
ReadCountry.jsp
<html><head><title>Feedback</title></head><body>
<%
String theCountry = request.getParameter("country");
if (theCountry != null) {
theCountry = theCountry.trim();
if (theCountry.equals("")) out.println("You have to enter data!");
else out.println("Hallo, you are from " + theCountry + "!");
}
%>
<p>
<a href = "Country.html">Back</a>
</body></html>
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 14
Parameter Name and Value
<input name="country" type="text" size="30">
parameter value
parameter name
String theCountry = request.getParameter("country");
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 15
Error Message on the Same Page As the Input Field
<!-ReadCountry2.jsp E.L. 2001-08-27
-->
<html><head><title>An Input Field with Error Check</title></head>
<form action="ReadCountry2.jsp" method="post">
<p>Enter Your Country:
<br><input name="country" type="text" size="30">
<p>
<input type="submit" value="Send">
<input type="reset" value="Reset">
</form>
<p>
<hr>
<%
String country = request.getParameter("country");
/* country is null the first time the page is downloaded by a user */
if (country != null) {
country = country.trim();
if (country.equals("")) out.println("You have to enter data!");
else out.println("Hallo, you are from " + country + "!");
}
%>
</body></html>
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 16
What If We’d Used “get” Instead of “post”?
• In the HTML file we now write:
<form action="ReadCountry.jsp" method="get">
• The data the user entered is now attached to the URL so that it shows
in the browser’s address field.
• There is a limit to the number of characters. In terms of sending data,
there is usually no reason to use get instead of post.
• Always use post transfer if the user is entering sensitive data.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 17
Show program
listings 21.4 and 21.5,
pp. 667-669.
Solve problem 1, page 670.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 18
Client Side Validation with JavaScript
•
•
•
As a supplement to server side checking, data should be checked before they
are sent to the server.
The HTML code has to be expanded with script code.
JavaScript is the de facto standard for client-side script programming.
<html><head><title>An Input Field with JavaScript data control</title>
<script language="JavaScript">
function checkData() {
if (window.document.countryInput.country.value == "") alert("You have to enter data!");
else window.document.countryInput.submit();
}
</script>
</head>
<form name="countryInput" action="ReadCountry.jsp" method="post">
<p>Enter Your Home Country:
<br><input name="country" type="text" size="30">
<p>
<input type="button" value = "Send" onClick = "checkData()">
<input type="reset" name="Reset" value="Reset">
</form></body></html>
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 19
Databases
<!-SimplePersonTable.jsp E.L. 2001-08-27
-->
<html><head>
<title>A Simple Test of Database Connection</title>
</head>
<body bgcolor="wheat" text="black" link="darkgreen"
vlink="steelblue" alink="darkblue">
<font size="+2">A Listing Of Persons</font>
<br><br>
<table border=1>
<tr><th>Ident.no.</th><th>First Name</th>
<th>Last Name</th></tr>
<tr><td>100</td><td>EDWARD</td><td>BROWN</td></tr>
<tr><td>101</td><td>ANN MARGARET</td><td>GREEN</td></tr>
<tr><td>102</td><td>JOHN</td><td>JOHNSON</td></tr>
</table>
</body>
</html>
The Server Side JSP Code, see next slide.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 20
<html><head><title>A Simple Test of Database Connection</title></head>
<body bgcolor="wheat" text="black" link="darkgreen" vlink="steelblue" alink="darkblue">
<font size="+2">A Listing Of Persons</font>
<br><br>
<%@ page import="java.sql.*" %>
<table border=1>
<tr><th>Ident.no.</th><th>First Name</th><th>Last Name</th></tr>
<%
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:@loiosh.stud.idb.hist.no:1521:orcl", ”username", ”password");
java.sql.Statement statement = conn.createStatement();
String sql = "select * from person";
ResultSet resSet = statement.executeQuery(sql);
while (resSet.next()) {
out.print("<tr><td>" + resSet.getString("identno") + "</td>");
out.print("<td>" + resSet.getString("firstname") + "</td>");
out.println("<td>" + resSet.getString("lastname") + "</td></tr>");
}
if (statement != null) statement.close();
if (conn != null) conn.close();
} catch (Exception e) {
out.print("Error, database connection: " + e);
} %></table></body></html>
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
SimplePerson.jsp
Chapter 21, page 21
A Web Application That Works with a Database
We use the Database
class from program
listing 20.2.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 22
The Order the Various Files are Requested in
NameArchive.jsp
form action
Show program
listing 21.8,
pp. 676-680.
HandleSelection.jsp
delete
include
DeletePersonData.jsp
new
edit
include
idNo as for the person
managingFile= "UpdatePersonData.jsp"
include
idNo= "not defined"
managingFile= "AddPersonData.jsp"
PersonForm.jsp
PersonForm.jsp
form action
Solve problems
AddPersonData.jsp
form action
UpdatePersonData.jsp
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 23
Programming Database Handling
•
The handling files, DeletePersonData.jsp, AddPersonData.jsp and
UpdatePersonData.jsp, are put together the same way:
– establish a database connection
– do a database operation
– close the database connection
•
•
•
•
•
This is not a particularly efficient way of dealing with a database. The whole
thing can be very sluggish with many requests to the database.
Professional systems should maintain a pool of database connections and
distribute these among the clients as needed.
Several books include code for a Connection class of this type (see for
example section 18.7 in [Hall 2000]).
Many database drivers [http://industry.java.sun.com/products/jdbc/drivers]
also have built-in “connection pooling”.
In our example, we can add uses of this service to the Database constructor
and the closeTheConnection() method. The rest of the code then remains
unchanged.
Solve problem 1 and 2, page 680.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 24
Storing State Information
• HTTP is a stateless protocol.
– The same client can send request after request to the Web server, which
handles each individual request completely independently of all the other
requests.
• How to transfer data from page to page?
– Using the submit button and then interpreting the request object
– Using hidden fields
– Saving data, either on the client side (cookies) or on the server side
(session object)
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 25
Cookies Overview
•
•
•
•
•
•
•
Client side storage
Often used for personal information, such as name and address
Handled by the browser
Max 4kb per cookie
Max 20 cookies per Web server
Max 400 cookies per browser
You will almost certainly find a lot of cookies on your computer (if
you haven’t configured your browser not to accept cookies). Search for
directories with the name cookies and files with the name cookies.*.
• Cookies let the server recognize you, but not identify you.
• Programs on Web servers, however, should not depend on cookies
working.
• Cookies should be an option for the client and not the only solution.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 26
Session Objects - Overview
•
•
•
•
•
Server side storage
A client will to be assigned a session ID when the session starts, i.e. when
contact is established between the client and the server.
The data are stored in a session object on the server, while the session ID is
normally stored as a cookie on the client.
But as we’ll see later, it is possible to use sessions without using cookies.
An example using cookies and session objects:
1. You log onto an Internet store to order pizza and soda and are assigned a session
ID, which is stored on your computer as a cookie.
2. At the same time, you are assigned a session object on the Web server.
3. Every time your computer asks for a new file from the Web server, the session ID
is sent along with the URL.
4. If you place an order, it is saved in the associated session object on the server.
5. If the Web server has already saved your name, telephone number, and delivery
address in cookies on your computer, you will be asked to confirm that they are
correct before your order is confirmed.
6. Or you may have to enter this information and then they will be saved
automatically in cookies so that you don’t have to enter them again later.
7. If you decide to forget the whole order and make do with what you have in the
fridge, the session object will be deleted from the Web server after a given period
of time.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 27
Programming Cookies
Show program listing 21.9, pp. 683-684.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 28
Programming Sessions
Show program listing 21.10, pp. 686-688.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 29
A Little Bookstore
Show
program
listing 21.11
pp. 690-692.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 30
The Problem With Reloading Pages
• You download the HTML file in program listing 21.4 to your Web
browser. You fill inn the data, and then press “Send”. Then you’ll get
the message “Your evaluation is saved”.
• Click the Reload button in your browser. What happens? The data are
stored in the file once more. A single user may fill up your evaluation
file with repeating data.
• A solution to this problem is to use a session attribute. We set the
attribute for the first time after the data are saved. Before the saving
section there is a check if this attribute exists. If it does, we do not save
again.
• The same considerations apply to updating databases, as well.
Solve problems 1 and 3, page 694.
Only to be used in connection with the book "Java the UML Way", by Else Lervik and Vegard B. Havdal.
ISBN 0-470-84386-1, John Wiley & Sons Ltd 2002
The Research Foundation TISIP, http://tisip.no/engelsk/
Chapter 21, page 31