Original PDF Flash format cs290i---lecture-6-servlets,-webmacro,-jsp-cs290i---lecture-6-...  


Cs290i Lecture 6 Servlets, Webmacro, Jsp Cs290i Lecture 6 ...

Java Servlets
CS290i - Lecture 6
? What are servlets?
? Java objects which extend the functionality of an HTTP server
Servlets, Webmacro, JSP
? Comparable to Netscape’s NSAPI, Microsoft’s ISAPI, or
Apache Modules
? Platform independent
? Server Independent
? Servlets vs. CGI
Scalable Internet Services and Systems, Spring 2001
? Servlets do not require a new process for each request
? Servlets stay loaded between requests
Thorsten von Eicken
? Same servlet can handle many concurrent requests
Department of Computer Science
? Servlets can be sandboxed to reduce danger on server
University of California at Santa Barbara
2
Hello World! Servlet
Servlet Lifecycle
1: import java.io.*;
? Lifecycle
2: import javax.servlet.*;
3: import javax.servlet.http.*;

? Constructor (no args)
4:
? Init(ServletConfig config)
5: public class HelloClientServlet extends HttpServlet
6: {

? Init and retrieve any config info
7:
protected void doGet(HttpServletRequest req,
? Called only once
8:
HttpServletResponse res)
? Service(ServletRequest req, ServletResponse res)
9:
throws ServletException, IOException
10:
{
? Called for each request, must be thread safe
11:
res.setContentType("text/html");
? Not HTTP specific
12:
PrintWriter out = res.getWriter();
? Destroy()
13:
out.println("<HTML><HEAD><TITLE>Hello Client!</TITLE>
" +
14:
"</HEAD><BODY>Hello Client!</BODY></HTML>
");
? To load a new version or shutdown
15:
out.close();
? Must be thread-safe (requests may still be running)
16:
}
17:
?
18:
public String getServletInfo()
HTTPServlet
19:
{
? Service dispatches to doXXX
20:
return "HelloClientServlet 1.0 by Stefan Zeiger";
? (doGet, doPut, doPost, doDelete, … )
21:
}
22: }
? HEAD -> doGet and discard output
? HttpServletRequest, HttpServletResponse
3
4

HTTP Request Object
HTTP Response Object
? Encapsulates all info from client
? Encapsulates all communication to client
? Access to request headers
? Access to response headers
? String getRequestURI();
? setContentType(String type);
? Enumeration getHeaderNames();
? setContentLength(int length);
? String getHeader(String headerName);
? setStatus(int statusCode);
? HttpSession getSession();
? Access to OutputStream or Writer
? Cookie[] getCookies();
? PrintWriter getWriter();
? Access to InputStream or Reader
? Access to setting cookies
? Reader: use for text, handles Unicode
? addCookie(Cookie c);
? Stream: use for binary data
? Convenience methods for redirects, errors, etc.
? Access to CGI-like info
? sendError(int statusCode);
? String getRemoteAddr();
? sendRedirect(String url);
? Access to form data
5
6
Session Tracking
More…
? Session:
? Inter-servlet communications
? Series of requests made by a client during a time period
? Redirect to another servlet
? Tracked & abstracted by unified layer
? Include another servlet’s response
? Use cookies, URL rewriting, or SSL
? Access static documents
? Sharing data though ServletContext
? Mechanics
? HttpSession s = req.getSession(true);
? Logging
? Get hashtable (Dictionary) containing session state
? Log(String msg);
? “true” -> create new session if necessary
? Log(String msg, Throwable t);
? May change response headers (e.g. cookie)
? Boolean s.isNew();
? Versions
? s.putvalue(String key, Object value);
? We will use the Servlet 2.0 API
? Object s.getValue(String key);
? Res.encodeUrl(String url) -> add session ID
7
8

Model/View/Controller
WebMacro
? Model:
? Separation of work
? Back-end database, “hard-core code”
? Web site designer
? Business logic (catalog pages, shopping cart, etc.)
? Designs overall look & feel of web site
? What pages contain, how to get from one to another
? View:
? Codes HTML & creates GIFs
? Look & feel of site, mostly design, little code
? Doesn’t do Java, doesn’t compile, install, …
? Page layout & content
? Doesn’t want to talk to a programmer for every change
? Programmer
? Controller:
? Develops engine driving web site operation
? Deciding which view to show (language, input validation, … )
? What needs to happen for each request
? Tracking users, keeping session data
? Where to get the data for a response
?
?
Writes Java, deals with SQL
Logging
? Doesn’t do HTML, can’t draw GIFs
? Doesn’t want to search for code among pages of HTML
9
10
WebMacro Example
Example (cont.)
? Customer order history page
? Servlet
? #set ContentType = "text/html“
? Place objects accessed by template into a hashtable
<HTML><HEAD><TITLE>$Customer.Name</TITLE></HEAD>
<BODY bgcolor='white'>
? Context.put("myVar", myData);
<h1>$Customer.Name: History</h1>
? WebMacro inspects objects and substitutes values
Here's a list of your orders since
$Customer.Orders.StartDate:
? Uses Java Introspection API
<table width='70%'>
? For example WebMacro might determine:
<th><td>Order Date</td>
? $Customer.Namecorresponds to Customer.getName()
<td>Item Requested</td>
<td>Number of Units</td></th>
? $order.Item.Nameresolves to Order.getItem(String name)
#foreach $order in $Customer.Orders {
? It is possible to call methods explicitly:
<tr><td>$order.Date</td>
?
<td>$order.Item.Name</td>
$Accounting.findAccount($Customer)
<td>$order.Number</td> </tr>
? WebMacro also supports indexed properties:
}
? Java: public String[] myData.getNames();
</table></body> </html>
? WM: #foreach $name in $myVar.Names { Hello $name! }
11
12

WM HelloWorld
JSP - JavaServer Pages
? import org.webmacro.*;
? Embed Java into HTML
import org.webmacro.servlet.*;
public class HelloWorld extends WMServlet

? Thanks for ordering
{
<I><%= request.getParameter(“title”) %></I>,
public Template handle(WebContext context)
we will ship the item tomorrow.
throws HandlerException
{
? Translate JSP pages to Servlets
context.put("Hello", "Hello, brave new world!");
Template view;

? Done automatically the first time a page is requested
try {
? HTML text becomes print statements
view = getTemplate("helloWorld.wm");
} catch (ResourceException e) {
? Control over code placement
throw new HandlerException(“HelloWorld failed!\n“);
}
? <%= expr %> : expression evaluated and placed in output
return view;
? <% code %> : scriptlet inserted in service method
}
? <%! code %> : code inserted in body of servlet class
}
? <%@ page att=“val”> : directive for servlet engine
? <html><head><title>Hello, World!</title></head>
? <%@ include file=“url” %>
#set $Response.ContentType = "text/html“
## WebContext.getResponse().setContentType("text/html")

? <jsp:useBean att=“val” /> : find or build a JavaBean
<h1>WebMacro is working!</h1>
? …
<font color=red size=+1><b>$Hello</b></font>
</body></html>

13
14
Model/view/controller
JSP critique
? Model
? Comparing WebMacro to JavaServer Pages
? Encapsulate back end data; keep it separate from the servlets
? The Problems with JSP, Jason Hunter
? Java Beans, or similar abstractions
? It is too tempting to insert Java code in web pages
? View
? A template engine can enforce good design
? JSP: html page with a little Java sprinkled in
? WebMacro templates cannot contain Java code
? WebMacro: templates with variable substitutions & loops
? simple script language aimed at page designers, with access
to all of the underlying data
? Controller
? Write a servlet that reads the client request, accesses the back
? Some tasks can only be done using Java code
end, and fills in the data needed by the template
within the page
? WebMacro provides hooks for writing controllers
? Trivial for developers (?), but tricky for web page designers
? WebMacro contains built-in variables covering requests,
responses, sessions and cookies
15
16

JSP critique (cont.)
JSP critique (cont.)
? Some simple tasks are made overly difficult
? Unless JSPs are pre-compiled, the web server will
? E.g including files, search paths
need to be equipped with a compiler
? WebMacro makes including headers and footers simple.
? Compile on-the-fly is nice, but not necessarily in production
? WebMacro classes are compiled, and templates are pre-
? Looping is unnecessarily difficult
parsed
? HTML > JAVA > HTML
? WebMacro's looping directives are less clumsy than JSP-
? JSPs consume both extra hard disk and extra
specific tags
memory space
? Template engines such as WebMacro don't need to duplicate
? JSP page syntax errors are cryptic and often
the page data into a second file, so hard drive space is spared.
useless
? Template engines also give the programmer full control over
? JSP->Java translation causes errors to appear in Java
how templates are cached in memory.
? WebMacro errors are more meaningful, and a logging
capability is provided.
17
18
Template engine critique
? Where’s the spec?
? Often the implementation is the spec
? Not widely known
? Harder to find help & people
? Performance not well-tuned
19