S
Servlet
l t Basics
B i
If you make
k th
the web.xml
b l entries
t i ffrom th
the upcoming
i slides,
lid you could
ld also
l use
the URL http://localhost/intro/hi2
9
© 2009 Marty Hall
Testing with
Eclipse
Installing Eclipse
• Overview
–E
Eclipse
li is
i a free
f open-source development
d l environment
i
with support for Java and many other languages
• Downloading
g
– http://www.eclipse.org/downloads/
• Choose “Eclipse IDE for Java EE Developers”
• As of 12/2008, version 3.4, called Eclipse Ganymede
• Installing
– Unzip into directory of your choice
– Put
P shortcut
h to eclipse.exe
li on your desktop
d k
• Integrating Tomcat in Eclipse
– http://www
http://www.coreservlets.com/
coreservlets com/
Apache-Tomcat-Tutorial/eclipse.html
11
Configuring Eclipse
• Make sure Eclipse
k
knows about
b T
Tomcat
– Click on Servers tab at bottom.
R-click in window.
window
– New, Server, Apache, Tomcat v6.0,
Next, navigate to folder, Finish.
• Suppress unnecessary
compiler warnings
– Wi d Preferences
Window P f
Java Compiler
Errors/Warnings
g
• Change “Serializable class
without ...” to “Ignore”
12
13
Adding Code to Eclipse Projects
• Locations
– src
• Unpackaged Java code
• Packages strongly recommended
– src/somePackage
• Java code in somePackage package
– WebContent
• Web files ((HTML, JavaScript,
p
CSS, JSP, images, etc.)
– WebContent/some-subdirectory
• Web content in subdirectory
– WebContent/WEB-INF
W bC t t/WEB INF
• web.xml (will be discussed later)
• Can also click on
“Deployment
p y Descriptor”
p
• Note
– Can cut/paste or drag/drop files into appropriate locations
14
• Eclipse details
– Name off Eclipse
li project
j is i “test”
– Servlet is in src/coreservlets/HelloServlet2.java
– Deployed by right-clicking on Tomcat,
Tomcat Add and Remove
Projects, Add, choosing test project, Finish, right-clicking
20
again, Start
Debugging Servlets
• Use print statements; run server on desktop
• Use Apache Log4J
• Integrated debugger in IDE
– Right-click in left margin in source to set breakpoint (Eclipse)
– R
R-click
click Tomcat and use “Debug”
Debug instead of “Start”
Start
• Look at the HTML source
• Return error pages to the client
– Plan ahead for missingg or malformed data
• Use the log file
– log("message") or log("message", Throwable)
• Separate
p the request
q and response
p data .
– Request: see EchoServer at www.coreservlets.com
– Response: see WebClient at www.coreservlets.com
• Make sure browser is not caching
– Internet Explorer: use Shift-RELOAD
– Firefox: use Control-RELOAD
21
• Stop and restart the server
© 2009 Marty Hall
F
Form Data
D t
30
31
© 2009 Marty Hall
JSP S
Scripting
i ti
JSP Expressions
• Format
– <%= Java Expression %>
• Result
– Expression evaluated
evaluated, converted to String,
String and placed
into HTML page at the place it occurred in JSP page
– That is, expression placed in _jspService inside out.print
• Examples
– Current time: <%= new java.util.Date() %>
– Your
Y hhostname:
t <%=
<% request.getRemoteHost()
t tR t H t() %>
• XML-compatible syntax
– <jsp:expression>Java Expression</jsp:expression>
– You cannot mix versions within a single page. You must
35
use XML for entire page if you use jsp:expression.
Predefined Variables
• request
– The HttpServletRequest (1st argument to service/doGet)
• response
– The
Th HttpServletResponse
H S l R (2nd
(2 d arg to service/doGet)
i /d G )
• out
– The Writer (a buffered version of type JspWriter) used to
send output to the client
• session
– The HttpSession associated with the request (unless
disabled with the session attribute of the page directive)
• application
– The ServletContext (for sharing data) as obtained via
36 getServletContext().
JSP Scriptlets
• Format
– <% Java Code %>
• Result
– Code
C d is
i inserted
i d verbatim
b i into
i servlet's
l ' _jspService
j S i
• Example
– <%
String queryData = request.getQueryString();
out.println("Attached GET data: " + queryData);
%>
– <% response.setContentType("text/plain"); %>
• XML
XML-compatible
compatible syntax
– <jsp:scriptlet>Java Code</jsp:scriptlet>
37
JSP Declarations
• Format
– <%! Java Code %>
• Result
– Code is inserted verbatim into servlet's class definition,
definition
outside of any existing methods
• Examples
p
– <%! private int someField = 5; %>
– <%! private void someMethod(...) {...} %>
• Design
D i consideration
id ti
– Fields are clearly useful. For methods, it is usually better
to define the method in a separate Java class.
• XML-compatible syntax
38 – <jsp:declaration>Java Code</jsp:declaration>
doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd" />
<jsp:directive.page contentType="text/html"/>
For JSP pages in XML syntax, default content
<head><title>Some Title</title></head> type is text/xml.
body bgcolor="#fdf5e6">
<body bgcolor #fdf5e6
Body
</body></html> Normal xhtml content, plus JSP commands that use
jjsp:blah
p syntax,
y pplus JSP custom tagg libraries.
41
XML Syntax for Generating Regular
XML Files (somefile.jspx)
(somefile jspx)
<?xml version="1.0" encoding="UTF-8" ?>
<your-root-element xmlns:jsp="http://java.sun.com/JSP/Page">
// / S /
<your-tag1>foo</your-tag1>
<your tag2>bar</your tag2>
<your-tag2>bar</your-tag2>
<your-root-element>
• Uses
U
– When you are sending to client that expects real XML
• Ajax
j
• Web services
• Custom clients
– Note
• You can omit the xmlns declaration if you are not using
any JSP tags. But then you could just use .xml extension.
42
43
Sample HTML 4 Page: Classic
Syntax (sample
(sample.jsp)
jsp)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD ...">
<HTML>
<HEAD><TITLE>Sample (Classic Syntax)</TITLE></HEAD>
<BODY BGCOLOR="#FDF5E6">
<CENTER>
<H1>Sample (Classic Syntax)</H1>
<H2>Num1: <%
<%= Math.random()
Math.random()*10
10 %></H2>
<% double num2 = Math.random()*100; %>
<H2>Num2: <%= num2 %></H2>
<%!
%! p
private
ate doub
double
e num3
u 3 = Math.random()*1000;
at . a do () 000; %>
%
<H2>Num3: <%= num3 %></H2>
</CENTER>
</BODY></HTML>
44
46
47
© 2009 Marty Hall
j
jsp:include
i l d
50
51
A News Headline Page: Result
52
MVC
HTML or JSP
Java Code
(Business Logic)
R l
Results
(beans)
submit form
Servlet
Form (URL matches url-
pattern of servlet)
(Store beans in
request, session, or
pp
application scope)
p )
JSP1
JSP2
JSP3
(Extract data from beans
and put in output. Pages
usually under WEB-INF.)
Eg: ${customer.firstName}
54
• Type of sharing
– Each request should result in a new number, so request-
based sharingg is appropriate.
pp p
55
Request-Based Sharing: Bean
package coreservlets;
57
Request-Based Sharing:
Business Logic
public class RanUtils {
public static NumberBean getRandomNum(String rangeString) {
double range;
try {
range = Double.parseDouble(rangeString);
} catch(Exception e) {
range = 10.0;
}
return(new NumberBean(Math.random() * range));
}
}
58
Request-Based Sharing:
URL Pattern (web
(web.xml)
xml)
...
<servlet>
<servlet-name>RandomNumberServlet</servlet-name>
<servlet-class>
coreservlets.RandomNumberServlet
</servlet-class>
</servlet>
<servlet mapping>
<servlet-mapping>
<servlet-name>RandomNumberServlet</servlet-name>
<url-pattern>/random-number</url-pattern>
/se et app g
</servlet-mapping>
...
59
Request-Based Sharing:
Input Form
...
<fieldset>
<legend>Random Number</legend>
<form action="./random-number">
Range: <input type=
type="text"
text name=
name="range"><br/>
range ><br/>
<input type="submit" value="Show Number">
</form>
</fieldset>
...
60
Request-Based Sharing:
Results Page
…
<body>
<h2>Random Number: ${randomNum.number}</h2>
</body></html>
61
Request-Based Sharing:
Results
62
Summary
• Set up Java 6, Tomcat, and Eclipse
– hhttp://www.coreservlets.com/
// l /
Apache-Tomcat-Tutorial/eclipse.html
• Give custom URLs to all servlets
– Use servlet, servlet-mapping, and url-pattern in web.xml
• Forms
–UUse relative
l ti URLs
URL for
f ACTION.
ACTION
– Read parameters with request.getParameter
• JSP Scripting
– If you use scripting, put most Java code in regular classes
• MVC
– Very widely
id l applicable
li bl approach.h
– Consider using it in many (most?) applications
63
© 2009 Marty Hall
Questions?