Programming Web Applications Programming Web Applications Ith S LT Ith S LT With Servlets With Servlets
Programming Web Applications Programming Web Applications Ith S LT Ith S LT With Servlets With Servlets
Objectives
How to program Web applications using servlets Advanced concepts such as listeners filters and concepts, listeners, filters, request dispatchers Running servlets using the Tomcat server
Web Applications
Web servers
return files run programs
Web application: collection of servlets, JSP pages, HTML pages, GIF files, ... Servlets: programmed using the servlet API API, which is directly based on HTTP Lifecycles
application session i t interaction ti (shared state) (session state) (transient state) (t i t t t )
3
An Example Servlet
import java.io.*; p j ; import javax.servlet.*; import javax.servlet.http.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) l ) throws IOException, ServletException { p yp ; response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<html><head><title>ServletExample</title></head>"+ <body><h1>Hello World!</h1>"+ "<body><h1>Hello World!</h1> + "This page was last updated: "+ new java.util.Date()+ "</body></html>"); } }
An Introduction to XML and Web Technologies
Requests
Methods in HttpServletRequest
getHeader getParameter getInputStream getRemoteHost, getRemoteAddr, getRemotePort tR t H t tR t Add tR t P t ...
Responses
Methods in HttpServletResponse
setStatus addHeader, addHeader setHeader getOutputStream, getWriter setContentType tC t tT sendError, sendRedirect ...
Example: BusinessCardServlet
public class BusinessCardServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { p yp ; ; response.setContentType("text/xml;charset=UTF-8"); long expires = new Date().getTime() + 1000*60*60*24; response.addDateHeader("Expires", expires); XMLOutputter outputter = new XMLOutputter(); outputter.output(getBusinessCard(), response.getOutputStream()); response getOutputStream()); } ... using JDOM to generate an XML document with a reference to an XSLT stylesheet
9
Servlet Contexts
One ServletContext object for each Web application getServerInfo getInitParameter ... Shared state:
setAttribute(name, value) getAttribute(name) getAttribute( ) dont use for mission critical data! don t
An Introduction to XML and Web Technologies
10
11
12
13
Example: QuickPollAsk.java
public class QuickPollAsk extends HttpServlet { public void d bli id doGet(HttpServletRequest request, ( l HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.print( <html><head><title>QuickPoll</title></head><body> + out print("<html><head><title>QuickPoll</title></head><body>"+ "<h1>QuickPoll</h1>"+ "<form method=post action=vote>"); String question = (String)getServletContext().getAttribute("question"); out.print(question+ ?<p> ); out.print(question+"?<p>"); out.print("<input name=vote type=radio value=yes> yes<br>"+ "<input name=vote type=radio value=no> no<p>"+ "<input type=submit name=submit value=Vote>"+ " i b i b i l " "</form>"+ "</body></html>"); } }
An Introduction to XML and Web Technologies
14
15
16
17
18
Problems in QuickPoll
Need access control to QuickPollSetup No escaping of special characters Need to check right order of execution Need to check that expected form field data is present No synchronization in QuickPollVote Should store state in database Redundancy in HTML generation
19
20
Sessions
One HttpSession object for each session
obtained by getSession in the HttpServletRequest object Htt S l tR t bj t
Session state:
setAttribute(name, value) setAttribute( getAttribute(name)
Hides the technical details of tracking users with URL rewriting / cookies / SSL sessions
An Introduction to XML and Web Technologies
21
Web Applications
A Web app is structured as a directory: myapp/ contains HTML/CSS/GIF/... files myapp/WEB-INF/ /WEB INF/ contains the deployment descriptor web.xml myapp/ /WEB-INF/classes/ / l / contains servlet class files (in subdirs corresponding to package names) myapp/WEB-INF/lib/ /WEB INF/lib/ contains extra jar files
An Introduction to XML and Web Technologies
22
Deployment Descriptors
An XML file web xml describing web.xml mapping from URIs to application resources initialization parameters security constraints registration of listeners and filters
23
Example web.xml
<web app xmlns="http://java.sun.com/xml/ns/j2ee <web-app xmlns http://java.sun.com/xml/ns/j2ee version="2.4"> <display-name>A Small Web Application</display-name> di l A S ll W b A li ti /di l <servlet> <servlet-name>MyFirstServlet</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet mapping> <servlet-mapping> <servlet-name>MyFirstServlet</servlet-name> p / / / p <url-pattern>/hello/*</url-pattern> </servlet-mapping> </web-app> / b
An Introduction to XML and Web Technologies
24
25
26
Listeners
also called observers or event handlers ServletContextListener Web application initialized / shut down ServletRequestListener request handler starting / finishing HttpSessionListener session created / invalidated ServletContextAttributeListener context attribute added / removed / replaced HttpSessionAttributeListener session attribute added / removed / replaced
An Introduction to XML and Web Technologies
27
28
Registration in web.xml:
<listener> <listener-class>SessionMonitor</listener-class> <listener>
An Introduction to XML and Web Technologies
29
Filters
Code being executed before and after the servlet
executed in stack-like fashion with servlet at the bottom
30
31
32
33
Wrappers
Used by filters to modify requests and responses
HttpServletRequestWrapper HttpServletResponseWrapper Example: performing server-side XSLT transformation for older browsers f f
An Introduction to XML and Web Technologies
34
public class XSLTFilter implements Filter { ServletContext context; public void init(FilterConfig c) throws ServletException { context = c.getServletContext(); } public void destroy() {}
An Introduction to XML and Web Technologies
35
36
37
38
39
Request Dispatchers
Forwarding requests to other resources Often used with JSP...
40
41
Security Constraints
... <security-constraint> <web-resource-collection> <web-resource-name>Restricted Area</web resource name> <web resource name>Restricted Area</web-resource-name> <url-pattern>/restricted/*</url-pattern> <http-method>GET</http-method> <http-method>POST</http-method> </web-resource-collection> <auth constraint> <auth-constraint> <role-name>administrator</role-name> <role-name>teacher</role-name> </auth-constraint> / h i <user-data-constraint> p g / p g <transport-guarantee>CONFIDENTIAL</transport-guarantee> </user-data-constraint> </security-constraint> ...
An Introduction to XML and Web Technologies
42
Programmatic Security
Useful request methods:
getRemoteUser() isUserInRole(String role) isSecure() getAuthType() getAttribute(javax.servlet.request.X509Certificate)
43
Summary
Servlets closely follow the request response request-response pattern from HTTP Features:
Multi-threading Declarative configuration Request parsing, including decoding of form data Shared state Session management Advanced code structuring: listeners, filters, wrappers Client authentication, SSL
44
45
Limitations of Servlets
Low-level Low level construction of HTML documents
fragments (strings) written to output stream no static well-formedness/validity guarantees
46
JWIG
Research project (http://www jwig org/) (http://www.jwig.org/) Session threads
showing a page and receiving form input modeled as a Remote Procedure Call (RPC)
explicit control-flow simpler session state management
47
48
GuessingGameWrapper.xml
49
GuessingGame (1/5)
import import import import import import java.io.*; java.util.*; javax.servlet.*; javax.servlet.http. ; javax.servlet.http.*; org.jwig.*; dk.brics.xact.*;
public class GuessingGamePlay extends SessionThread { p public XML main() throws IOException, ServletException { p , p XML wrapper = XML.loadConstant("GuessingGameWrapper.xml"); XML form = [[ <form><input name="guess" type "text" size "2" maxlength "2"/> name guess type= text size= 2 maxlength= 2 /> <input type="submit" name="continue" value="continue"/></form> ]];
50
GuessingGame (2/5)
ServletContext c = getServletContext(); Integer plays = (Integer)c.getAttribute("plays"); if (plays null) (plays==null) plays = new Integer(0); else plays = new Integer(plays.intValue()+1); l ( l i l () 1) c.setAttribute("plays", plays); int number = (new Random()).nextInt(100)+1; show(wrapper.plug("BODY", [[Please guess a number between 1 and 100: <{form}>]]));
51
GuessingGame (3/5)
int guesses = 1; boolean done = false; while (!done) { int guess = Integer.parseInt(getParameter("guess")); if (guess==number) done = true; else { pp p g show(wrapper.plug("BODY", [[ That is not correct. Try a <b><{(guess>number)?"lower":"higher"}></b> number: <{form}> ]])); guesses++; } }
52
GuessingGame (4/5)
XML msg = [[You got it, using <b><{guesses}></b> guesses.]]; XML thanks = [[Thank you for playing this exciting game!]]; XML res; if (guesses<getCurrentRecord()) { show(wrapper.plug("BODY", [[ ( pp p g( , <{msg}><p/> That makes you the new record holder!<p/> Please enter your name for the hi-score list: <form><input name="name" type="text" size="20"/> <input type="submit" name="continue" value="continue"/></form> ]])); synchronized(c) { if (guesses<getCurrentRecord()) { c.setAttribute("holder", getParameter("name")); c.setAttribute("record", c setAttribute("record" new Integer(guesses)); } } res = wrapper.plug( BODY , thanks); wrapper plug("BODY" } else res = wrapper.plug("BODY", [[<{msg}><p/><{thanks}>]]); return res; ; }
An Introduction to XML and Web Technologies
53
GuessingGame (5/5)
int getCurrentRecord() { Integer record = (Integer)c.getAttribute("record"); if (record!=null) return record.intValue(); else return Integer.MAX_VALUE; // no players yet } }
54
GuessingGameHiScore
public class GuessingGameHiscore extends HttpServlet { public void doGet() throws IOException, ServletException { ServletContext c = getServletContext(); Integer plays = (Integer)c.getAttribute( plays ); (Integer)c.getAttribute("plays"); String holder = (String)c.getAttribute("holder"); Integer record = (Integer)c.getAttribute("record"); XML b d body; if (record!=null) y p y g p y g , body = [[In <{plays.toString()}> plays of this game, the record holder is <b><{holder}></b> with <b><{record.toString()}></b> guesses.]]; else body = [[No players yet.]]; XML.loadConstant("GuessingGameWrapper.xml") .plug("BODY", body).write(response.getWriter()); } }
An Introduction to XML and Web Technologies
55
plug analysis
class files
flow graph
summary graphs
receive analysis
string analysis
regular languages
show analysis
56
57