Web Apps Tomcat configuration Static pages To let

Web. Apps (Tomcat configuration)

Static pages To let Tomcat serve static pages, we must define a “Web Application”. That is, in the Tomcat Document Root (by default $CATALINA_HOME/webapps/) we must create a folder named after our Web Application (e. g. my. App). webapps In that “my. App” folder, we MUST create a WEB-INF folder (that can be empy). In the my. App folder we can then depost the static html files. On our Tomcat server, the URL for the hello. html file becomes: http: //machine/port/my. App/hello. html my. App WEB-INF To actually see the webapp, we might have to restart Tomcat web. xml hello. html

Static pages A web. xml file MUST be provided: <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc. //DTD Web Application 2. 3//EN“ "http: //java. sun. com/dtd/web-app_2_3. dtd"> <web-app> </web-app> webapps my. App WEB-INF web. xml hello. html

JSP pages To let Tomcat serve JSP pages, we follow the same procedure that we described for static pages. webapps In the my. App folder we can depost the JSP files. On our Tomcat server, the URL for the hello. jsp file becomes: http: //machine/port/my. App/hello. jsp The WEB-INF directory is still empty. my. App To actually see the webapp, you might have to restart Tomcat (depending on the version you have) The same web. xml file as in the static case must be provided. WEB-INF web. xml hello. jsp

Servlets To let Tomcat serve servlet, we need add some info. The compiled servlets (. class) must be stored in a “classes” directory in WEB-INF. Moreover, the web. xml file MUST contain at least: <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc. //DTD Web Application 2. 3//EN" "http: //java. sun. com/dtd/web-app_2_3. dtd"> <web-app> <servlet-mapping> <servlet-name>invoker</servlet-name> <url-pattern>/magic/*</url-pattern> </servlet-mapping> </web-app> The “magic” word is the servlet activation keyword (you can of course customize this word). To execute the servlet called My. Servlet. class, the URL will be: http: //machine/port/my. App/magic/My. Servlet

Servlets The web. xml file CAN contain many additional info. For instance, it can contain a section defining an alias name for the servlet: … <servlet> <servlet-name>pippo</servlet-name> <servlet-class>Servlet 1</servlet-class> </servlet> … In such case, the servlet called My. Servlet. class Can be activated ALSO by the URL: http: //machine/port/my. App/magic/pippo webapps my. App WEB-INF web. xml classes My. Servlet. class

SERVLETS: Dispatching, monitoring, filtering

Dispatching Request. Dispatcher dispatch = cntx. get. Request. Dispatcher("/Second. Servlet"); dispatch. forward(req, res); Request. Dispatcher dispatch = cntx. get. Request. Dispatcher("/Second. Servlet"); dispatch. include(req, res);

Dispatching example package servlets; import javax. servlet. http. Http. Servlet. Request; import javax. servlet. http. Http. Servlet. Response; import javax. servlet. http. Http. Servlet; import javax. servlet. Servlet. Config; import javax. servlet. Servlet. Context; import java. io. IOException; import javax. servlet. Servlet. Context; import javax. servlet. Request. Dispatcher; public class Second. Servlet extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws IOException, Servlet. Exception { Printer out=res. get. Writer(); System. out. println("Second Servlet Called"); } }

Dispatching example package servlets; import javax. servlet. http. Http. Servlet. Request; import javax. servlet. http. Http. Servlet. Response; import javax. servlet. http. Http. Servlet; import javax. servlet. Servlet. Config; import javax. servlet. Servlet. Context; import java. io. IOException; import javax. servlet. Servlet. Context; import javax. servlet. Request. Dispatcher; public class First. Servlet extends Http. Servlet { public void do. Get(Http. Servlet. Request req, Http. Servlet. Response res) throws IOException, Servlet. Exception { Printer out=res. get. Writer(); out. println("First Servlet Called"); Servlet. Config config = get. Servlet. Config(); Servlet. Context cntx = config. get. Servlet. Context(); Request. Dispatcher dispatch = cntx. get. Request. Dispatcher("/Second. Servlet"); dispatch. forward(req, res); } }

Dispatching example <servlet> <servlet-name>First. Servlet</servlet-name> <servlet-class>servlets. First. Servlet</servlet-class> </servlet> <servlet-name>Second. Servlet</servlet-name> <servlet-class>servlets. Second. Servlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>First. Servlet</servlet-name> <url-pattern>/firstservlet/*</url-pattern> </servlet-mapping> <servlet-name>Second. Servlet</servlet-name> <url-pattern>/Second. Servlet/*</url-pattern> </servlet-mapping>

Monitoring Servlets Lifecycle Web context Session Request Initialization and Destruction Servlet. Context. Listener Servlet. Context. Event Attribute added, removed, or replaced Servlet. Context. Attribute. Listener Servlet. Context. Attribu te. Event Creation, invalidation, activation, passivation, and timeout Http. Session. Listener. Http. Session Activation. Listener Http. Session. Event Attribute added, removed, or replaced Http. Session. Attribute. Listener Http. Session. Binding. Ev ent A servlet request has started being processed by Web components Servlet. Request. Listener Servlet. Request. Event Attribute added, removed, or replaced Servlet. Request. Attribute. Listener Servlet. Request. Attribu te. Event

Monitoring Servlets Lifecycle - Example /* File : Application. Watch. java */ import javax. servlet. Servlet. Context. Listener; import javax. servlet. Servlet. Context. Event; public class Application. Watch implements Servlet. Context. Listener { public static long application. Initialized = 0 L; /* Application Startup Event */ public void context. Initialized(Servlet. Context. Event ce) { application. Initialized = System. current. Time. Millis(); } /* Application Shutdown Event */ public void context. Destroyed(Servlet. Context. Event ce) {} }

Monitoring Servlets Lifecycle - Example /* File : Session. Counter. java */ import javax. servlet. http. Http. Session. Listener; import javax. servlet. http. Http. Session. Event; public class Session. Counter implements Http. Session. Listener { private static int active. Sessions = 0; /* Session Creation Event */ public void session. Created(Http. Session. Event se) { active. Sessions++; } /* Session Invalidation Event */ public void session. Destroyed(Http. Session. Event se) { if(active. Sessions > 0) active. Sessions--; } public static int get. Active. Sessions() { return active. Sessions; } }

Monitoring Servlets Lifecycle - Example <!-- Web. xml --> <? xml version="1. 0" encoding="ISO-8859 -1"? > <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc. //DTD Web Application 2. 3//EN" "http: //java. sun. com/j 2 ee/dtds/web -app_2. 3. dtd"> <web-app> <!-- Listeners --> <listener-class> com. stardeveloper. web. listener. Session. Counter </listener-class> </listener> <listener-class> com. stardeveloper. web. listener. Application. Watch </listenerclass> </listener> </web-app>

Scope Objects Web context Servlet. Context Web components within web context servlet. get. Servlet. Config(). get. Servlet. Con text Session Http. Session Web components handling requests that belong to a session Request Servlet. Request Web component handling the request Page. Context Web component in the JSP page Main Methods: Object get. Attribute(String name) void set. Attribute(String name, Object o) Enumeration get. Attribute. Names()

AOP The programming paradigms of aspect-oriented programming (AOP), and aspect-oriented software development (AOSD) attempt to aid programmers in the separation of concerns, specifically cross-cutting concerns, as an advance in modularization. Logging and authorization offer two examples of crosscutting concerns: a logging strategy necessarily affects every single logged part of the system. Logging thereby crosscuts all logged classes and methods. Same is true for authorization.

Filters (javax. servlet. filter) Other classes that preprocess/postprocess request/response A filter is an object than perform filtering tasks on either the request to a resource (a servlet or static content), or on the response from a resource, or both. Filters perform filtering in the do. Filter method. Every Filter has access to a Filter. Config object from which it can obtain its initialization parameters, a reference to the Servlet. Context which it can use, for example, to load resources needed for filtering tasks. Filters are configured in the deployment descriptor of a web application Examples that have been identified for this design are 1) Authentication Filters 2) Logging and Auditing Filters 3) Image conversion Filters 4) Data compression Filters 5) Encryption Filters 6) Tokenizing Filters 7) Filters that trigger resource access events 8) XSL/T filters 9) Mime-type chain Filter http: //java. sun. com/products/servlet/Filters. html

Filters are important for a number of reasons. First, they provide the ability to encapsulate recurring tasks in reusable units. Second, filters can be used to transform the response from a servlet or a JSP page. A common task for the web application is to format data sent back to the client. Increasingly the clients require formats (for example, WML) other than just HTML.

Filters can perform many different types of functions. * Authentication-Blocking requests based on user identity. * Logging and auditing-Tracking users of a web application. * Image conversion-Scaling maps, and so on. * Data compression-Making downloads smaller. * Localization-Targeting the request and response to a particular locale. * XSL/T transformations of XML content-Targeting web application responses to more that one type of client. These are just a few of the applications of filters. There are many more, such as encryption, tokenizing, triggering resource access events, mime-type chaining, and caching.

The state problem Client 1 ? Client 2 htt pd ern +CGI Data User 2 Int 3 et Client Data User 1 Data User 3 Server

A typical solution Client 1 t p i r Sc d e t a r v o a p J p u & S va a J by Cookie Data User 1 Client 2 htt pd ern Cookie +CGI Data User 2 Int 3 et Client Cookie Data User 3 Server

htt pd et ern ces pro Startup Socket connection pro Jav app a let ces s Browser Int Startup Client HTTP Get d e t r o p p Su ava by J Cgi-bin s A more radical solution Server

ern et Browser htt pd ces pro HTTP Get Startup Jav app a let pro ces s Int Startup Client d e t r o p p Su ava by JCgi-bin s An even more radical solution Server CO Middle RB A Tier

Cookies

Cookies: what are they A Cookie is a small amount of information sent by a servlet to a Web browser, saved by the browser, and later sent back to the server. A cookie's value can uniquely identify a client, so cookies are commonly used for session management. A cookie has a name, a single value, and optional attributes such as a comment, path and domain qualifiers, a maximum age, and a version number. Some Web browsers have bugs in how they handle the optional attributes, so use them sparingly to improve the interoperability of your servlets.

Cookies affect the caching of the Web pages that use them. HTTP 1. 0 does not cache pages that use cookies created with this class. The Java class “Cookie” does not support the cache control defined with HTTP 1. 1. This class supports both the Version 0 (by Netscape) and Version 1 (by RFC 2109) cookie specifications. By default, cookies are created using Version 0 to ensure the best interoperability

Cookies: why? To maintain status across a “user session” To maintan infos across sessions p. Customer identification p. Targeted advertisement p. Elimination of username e password

Attribute summary String get. Comment() / void set. Comment(String s) Gets/sets a comment associated with this cookie. String get. Domain() / set. Domain(String s) Gets/sets the domain to which cookie applies. Normally, cookies are returned only to the exact hostname that sent them. You can use this method to instruct the browser to return them to other hosts within the same domain. Note that the domain should start with a dot (e. g. . prenhall. com), and must contain two dots for non-country domains like. com, . edu, and. gov, and three dots for country domains like. co. uk and. edu. es.

Attribute summary int get. Max. Age() / void set. Max. Age(int i) Gets/sets how much time (in seconds) should elapse before the cookie expires. If you don't set this, the cookie will last only for the current session (i. e. until the user quits the browser), and will not be stored on disk. See the Long. Lived. Cookie class below, which defines a subclass of Cookie with a maximum age automatically set one year in the future. String get. Name() / void set. Name(String s) Gets/sets the name of the cookie. The name and the value are the two pieces you virtually always care about. Since the get. Cookies method of Http. Servlet. Request returns an array of Cookie objects, it is common to loop down this array until you have a particular name, then check the value with get. Value. See the get. Cookie. Value method shown below.

Attribute summary String get. Path() / void set. Path(String s) Gets/sets the path to which this cookie applies. If you don't specify a path, the cookie is returned for all URLs in the same directory as the current page as well as all subdirectories. This method can be used to specify something more general. For example, some. Cookie. set. Path("/") specifies that all pages on the server should receive the cookie. Note that the path specified must include the current directory. boolean get. Secure / set. Secure(boolean b) Gets/sets the boolean value indicating whether the cookie should only be sent over encrypted (i. e. SSL) connections.

Attribute summary String get. Value() / void set. Value(String s) Gets/sets the value associated with the cookie. Again, the name and the value are the two parts of a cookie that you almost always care about, although in a few cases a name is used as a boolean flag, and its value is ignored (i. e the existence of the name means true). int get. Version() / void set. Version(int i) Gets/sets the cookie protocol version this cookie complies with. Version 0, the default, adheres to the original Netscape specification. Version 1, not yet widely supported, adheres to RFC 2109.

Placing Cookies in the Response Headers The cookie is added to the Set-Cookie response header by means of the add. Cookie method of Http. Servlet. Response. Here's an example: Cookie user. Cookie = new Cookie("user", "uid 1234"); response. add. Cookie(user. Cookie);

Reading Cookies from the Client To read the cookies that come back from the client, you call get. Cookies on the Http. Servlet. Request. This returns an array of Cookie objects corresponding to the values that came in on the Cookie HTTP request header. Once you have this array, you typically loop down it, calling get. Name on each Cookie until you find one matching the name you have in mind. You then call get. Value on the matching Cookie, doing some processing specific to the resultant value. This is such a common process that the following section presents a simple get. Cookie. Value method that, given the array of cookies, a name, and a default value, returns the value of the cookie matching the name, or, if there is no such cookie, the designated default value.

Cookies: examples Cookie user. Cookie = new Cookie(“user”, ”uid 1234”); user. Cookie. set. Max. Age(60*60*24*365); response. add. Cookie(user. Cookie); Code to check if the client accepts cookies: See http: //www. purpletech. com/code/src/com/purpletech/servlets/Cookie. Detector. java

Set. Cookies import java. io. *; import javax. servlet. http. *; /** Sets six cookies: three that apply only to the current session * (regardless of how long that session lasts) and three that persist for an hour * (regardless of whether the browser is restarted). */ public class Set. Cookies extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { for(int i=0; i<3; i++) { // Default max. Age is -1, indicating cookie // applies only to current browsing session. Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i); response. add. Cookie(cookie);

Set. Cookies cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i); // Cookie is valid for an hour, regardless of whether // user quits browser, reboots computer, or whatever. cookie. set. Max. Age(3600); response. add. Cookie(cookie); } response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String title = "Setting Cookies"; out. println (("<HTML><HEAD><TITLE>" +title+ “</TITLE></HEAD>" + "<BODY BGCOLOR="#FDF 5 E 6">n" +"<H 1 ALIGN="CENTER">" + title + "</H 1>n" +"There are six cookies associated with this page. n" + "</BODY></HTML>"); } }

Show. Cookies import java. io. *; import javax. servlet. http. *; /** Creates a table of the cookies associated with the current page. */ public class Show. Cookies extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String title = "Active Cookies"; out. println(("<HTML><HEAD><TITLE>" +title+ “</TITLE></HEAD>" + "<BODY BGCOLOR="#FDF 5 E 6">n" + "<H 1 ALIGN="CENTER">" + title + "</H 1>n" + "<TABLE BORDER=1 ALIGN="CENTER">n" + "<TR BGCOLOR="#FFAD 00">n" + " <TH>Cookie Namen" + " <TH>Cookie Value");
![Show. Cookies Cookie[] cookies = request. get. Cookies(); Cookie cookie; for(int i=0; i<cookies. length; Show. Cookies Cookie[] cookies = request. get. Cookies(); Cookie cookie; for(int i=0; i<cookies. length;](http://slidetodoc.com/presentation_image_h2/12c14a5750037d8482e30c508be3c704/image-39.jpg)
Show. Cookies Cookie[] cookies = request. get. Cookies(); Cookie cookie; for(int i=0; i<cookies. length; i++) { cookie = cookies[i]; out. println("<TR>n" + " <TD>" + cookie. get. Name() + "n" + " <TD>" + cookie. get. Value()); } out. println("</TABLE></BODY></HTML>"); } }

Sessions

Session tracking using cookies String session. ID = make. Unique. String(); Hashtable session. Info. Table = new Hashtable(); Hashtable global. Table = get. Table. Storing. Session(); global. Table. put(session. ID, session. Info. Table ); Cookie session. Cookie=new Cookie(“Session. ID”, session. ID); session. Cookie. set. Path(“/”); response. add. Cookie(session. Cookie); info key session. Info. Table session. ID global. Table

Http. Session Class Provides a way to identify a user across more than one page request or visit to a Web site and to store information about that user. The servlet container uses this interface to create a session between an HTTP client and an HTTP server. The session persists for a specified time period, across more than one connection or page request from the user. A session usually corresponds to one user, who may visit a site many times. The server can maintain a session in many ways such as using cookies or rewriting URLs.

Http. Session Class This interface allows servlets to View and manipulate information about a session, such as the session identifier, creation time, and last accessed time Bind objects to sessions, allowing user information to persist across multiple user connections. When an application stores an object in or removes an object from a session, the session checks whether the object implements Http. Session. Binding. Listener. If it does, the servlet notifies the object that it has been bound to or unbound from the session.

Session tracking API Http. Session session = request. get. Session(true); Shopping. Cart cart = (Shopping. Cart)session. get. Value(“carrello”); // 2. 1 // 2. 2 (Shopping. Cart)session. get. Attribute(“carrello”); if (cart==null) { cart=new Shopping. Cart(); session. put. Value(“carrello”, cart); //2. 1 //2. 2 session. put. Attribute(“carrello”, cart); } do. Some. Thing. With(cart);

Session tracking API public void put. Value(String name, Object value); //2. 1 public void set. Attribute(String name, Object value); public void remove. Value(String name); //2. 1 public void remove. Attribute(String name); public String[] get. Value. Names() //2. 1 public Enumeration get. Attribute. Names() //2. 2

Session tracking API public long get. Creation. Time(); public long get. Last. Accessd. Time(); milliseconds since midnight, 1. 1. 1970 public int get. Max. Inactive. Interval(); public void set. Max. Inactive. Interval(int sec); public void invalidate();

Show. Session import java. io. *; import javax. servlet. http. *; import java. net. *; import java. util. *; /** Simple example of session tracking. */ public class Show. Session extends Http. Servlet { public void do. Get(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { response. set. Content. Type("text/html"); Print. Writer out = response. get. Writer(); String title = "Session Tracking Example"; Http. Session session = request. get. Session(true); String heading; // Use get. Attribute instead of get. Value in version 2. 2. Integer access. Count = (Integer)session. get. Value("access. Count");

Show. Session if (access. Count == null) { access. Count = new Integer(0); heading = "Welcome Newcomer"; } else { heading = "Welcome Back"; access. Count = new Integer(access. Count. int. Value() + 1); } // Use set. Attribute instead of put. Value in version 2. 2. session. put. Value("access. Count", access. Count);

Show. Session out. println(("<HTML><HEAD><TITLE>" +title+ “</TITLE></HEAD>" + "<BODY BGCOLOR="#FDF 5 E 6">n" + "<H 1 ALIGN="CENTER">" + heading + "</H 1>n" + "<H 2>Information on Your Session: </H 2>n" + "<TABLE BORDER=1 ALIGN="CENTER">n" + "<TR BGCOLOR="#FFAD 00">n" + " <TH>Info Type<TH>Valuen" + "<TR>n" +" <TD>IDn" +" <TD>" + session. get. Id() + "n" + "<TR>n" +" <TD>Creation Timen" + " <TD>" + new Date(session. get. Creation. Time()) + "n" + "<TR>n" +" <TD>Time of Last Accessn" + " <TD>" +new Date(session. get. Last. Accessed. Time()) + "n" + "<TR>n" +" <TD>Number of Previous Accessesn" +" <TD>" + access. Count + "n" + "</TABLE>n" +"</BODY></HTML>"); }

Show. Session /** Handle GET and POST requests identically. */ public void do. Post(Http. Servlet. Request request, Http. Servlet. Response response) throws Servlet. Exception, IOException { do. Get(request, response); } }

Accessibility

Accessibility What is Section 508? The legislation referred to as "Section 508" is actually an amendment to the Workforce Rehabilitation Act of 1973. The amendment was signed into law by President Clinton on August 7, 1998. Section 508 requires that electronic and information technology that is developed or purchased by the Federal Government is accessible by people with disabilities. See http: //jimthatcher. com/webcourse 8. htm for accessibility when using forms http: //jimthatcher. com/webcourse 1. htm for accessibility in general. http: //www. innovazione. gov. it/ita/normativa/pubblicazioni/2004_rapporto_comm_a cc. pdf

Accessibility in Italy. Legge Stanca 9 gennaio 2004, n. 4 Disposizioni per favorire l'accesso dei soggetti disabili agli strumenti informatici Testo della legge: - http: //www. pubbliaccesso. gov. it/normative/legge_20040109_n 4. htm Vedi anche: - http: //www. cnipa. gov. it/site/it-IT/Attivit%C 3%A 0/ Commissioni_e_Gruppi_di_Lavoro_interministeriali/Accessibilit%C 3%A 0/ Rapporto 2004 della commissione. Commissione interministeriale permanente per l’impiego delle ICT a favore delle categorie deboli o svantaggiate - http: //www. innovazione. gov. it/ita/normativa/pubblicazioni/2004_rapporto_comm_acc. pdf
- Slides: 53