week 2 _day 8 to day 14_

Document Sample
week 2 _day 8 to day 14_ Powered By Docstoc
					Week 2: At a Glance

Day 8. Handling Errors

 

         

try/catch

try/catch request

Week 2 – Page 1

Syntax Errors
out.prinbln("Hello!") ch03_21.jsp

ch08_01.jsp

<HTML> <HEAD> <TITLE>Passing Arrays to Methods</TITLE> </HEAD> <BODY> <H1>Passing Arrays to Methods</H1> <%! void doubler(int a) { for (int loopIndex = 0; loopIndex < a.length; loopIndex++) { a[loopIndex] *= 2; } } %> <% int array[] = {1, 2, 3, 4, 5}; out.println("Before the call to doubler...<BR>"); for (int loopIndex = 0; loopIndex < array.length; loopIndex++) { out.println("array[" + loopIndex + "] = " + array[loopIndex] + "<BR>"); }

Week 2 – Page 2

doubler(array); out.println("After the call to doubler...<BR>"); for (int loopIndex = 0; loopIndex < array.length; loopIndex++) { out.println("array[" + loopIndex + "] = " + array[loopIndex] + "<BR>"); } %> </BODY> </HTML>

Apache Tomcat/4.0.3 - HTTP Status 500 Internal Server Error

org.apache.jasper.JasperException: Unable to compile class for JSP An error occurred between lines: 8 and 16 in the jsp file: /ch08_01.jsp

Week 2 – Page 3

Generated servlet error: D:\tomcat\jakarta-tomcat4.0.3\work\localhost\ch08\ch08_0005f01$jsp.java:15: Attempt to reference field length in a int. for (int loopIndex = 0; loopIndex < a.length; ^

An error occurred between lines: 8 and 16 in t he jsp file: /ch08_01.jsp Generated servlet error: D:\tomcat\jakarta-tomcat4.0.3\work\localhost\ch08\ch08_0005f01$jsp.java:17: [] can only be applied to arrays. It can't be applied to int. a[loopIndex] *= 2; ^

An error occurred between lines: 18 and 36 in the jsp file: /ch08_01.jsp Generated servlet error: D:\tomcat\jakarta-tomcat4.0.3\work\localhost\ch08\ch08_0005f01$jsp.java:83: Incompatible type for method. Can't convert int[] to int. doubler(array); ^ 3 errors at org.apache.jasper.compiler.Compiler.compile(Compiler.java:285) at org.apache.jasper.servlet.JspServlet.loadJSP(JspServlet.java:552) at org.apache.jasper.servlet.JspServlet$JspServl etWrapper.loadIfNecessary (JspServlet. java:177) at org.apache.jasper.servlet.JspServlet$JspServletWrapper.service (JspServlet.java: 189) at org.apache.jasper.servlet.JspServlet.serviceJspFile (JspServlet.java:382) at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:474) at javax.servlet.http.HttpServlet.servic e(HttpServlet.java:853) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:247) at org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. java:193) at org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java: 243) at org.apache.catalina.core.StandardPipeline.invokeNext (StandardPipeline.java:566) .

Week 2 – Page 4

. .

org.apache.jasper.JasperException: Unable to compile class for JSP

Incompatible type for method. Can't convert int[] to int

doubler(array);

doubler

int array[] = {1, 2, 3, 4, 5}; . . . doubler(array); doubler

void doubler(int a) { for (int loopIndex = 0; loopIndex < a.length; loopIndex++) { a[loopIndex] *= 2; } } void doubler(int[] a)

javac

Week 2 – Page 5

Runtime Errors

ch08_02.jsp

<HTML> <HEAD> <TITLE>Causing a Runtime Error</TITLE> </HEAD> <BODY> <H1>Causing a Runtime Error</H1> <% int int1 = 1; int1 = int1 / 0; out.println("The answer is " + int1); %> </BODY> </HTML>

Week 2 – Page 6

java.lang.ArithmeticException: / by zero / by zero

/ by zero

Exceptions
Exception Throwable java.lang.Exception java.lang.Throwable

Throwable

getMessage

String

Week 2 – Page 7

java.lang.Throwable

Throwable() Throwable(String message)

Throwable Throwable

String getLocalizedMessage() String getMessage() Throwable void printStackTrace() Throwable

void printStackTrace(PrintStream s) void printStackTrace(PrintWriter s) String toString() Throwable

Exception

Throwable Throwable Throwable

Exception java.lang.Exception

Exception() Exception(String s)

Exception Exception

Exception

try/catch

Using try/catch Blocks
try catch

Week 2 – Page 8

try/catch

try { // Sensitive code } catch (Exception1Type e1) { // Handle exception1 type } catch (Exception1Type e1) { // Handle exception1 type } . . . [finally { // Code to be executed before try block ends }] try catch try/catch finally finally finally finally

catch catch

try/catch catch exception e getMessage try/catch ch08_03.jsp catch exception

<HTML> <HEAD> <TITLE>Using a try/catch Block</TITLE> </HEAD> <BODY> <H1>Using a try/catch Block</H1> <% try{ int int1 = 1; int1 = int1 / 0; out.println("The answer is " + int1); } catch (Exception e){ out.println("An exception occurred: " + e.getMessage()); } %> </BODY>

Week 2 – Page 9

</HTML>

/ by zero

getMessage Exception

Exception toString

out.println

Exception

toString

Week 2 – Page 10

Exception

ch08_04.jsp

<HTML> <HEAD> <TITLE>Using a try/catch Block</TITLE> </HEAD> <BODY> <H1>Using a try/catch Block</H1> <% try{ int int1 = 1; int1 = int1 / 0; out.println("The answer is " + int1); } catch (Exception e){ out.println("An exception occurred: " + e); } %> </BODY> </HTML>

java.lang.ArithmeticException

Handling Specific Exception Types

Week 2 – Page 11

Exception

                                     

AclNotFoundException ActivationException AlreadyBoundException ApplicationException ArithmeticException ArrayIndexOutOfBoundsException AWTException BadLocationException ClassNotFoundException CloneNotSupportedException DataFormatException ExpandVetoException FileException GeneralSecurityException IllegalAccessException InstantiationException InterruptedException IntrospectionException InvocationTargetException IOException LastOwnerException NoninvertibleTransformException NoSuchFieldException NoSuchMethodException NotBoundException NotOwnerException ParseException PrinterException PrivilegedActionException PropertyVetoException RemarshalException RuntimeException ServerNotActiveException SQLException TooManyListenersException UnsupportedFlavorException UnsupportedLookAndFeelException UserException Exception catch

Week 2 – Page 12

ArrayIndexOutOfBoundsException

try { . . . } catch (ArrayIndexOutOfBoundsException e) { out.println("Array index out of bounds"); }

array[0]

array[99] array[100] ArrayIndexOutOfBoundsException

ch08_05.jsp

<HTML> <HEAD> <TITLE>Catching an ArrayIndexOutOfBoundsException Exception</TITLE> </HEAD> <BODY> <H1>Catching an ArrayIndexOutOfBoundsException Exception</H1> <% try { int array[] = new int[100]; array[100] = 100; } catch (ArrayIndexOutOfBoundsException e) { out.println("Array index out of bounds."); } %> </BODY> </HTML>

ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException

Week 2 – Page 13

Catching Multiple Exceptions
catch catch try/catch

catch Exception

catch

Week 2 – Page 14

ch08_06.jsp

<HTML> <HEAD> <TITLE>Catching an ArrayIndexOutOfBoundsException Exception</TITLE> </HEAD> <BODY> <H1>Catching an ArrayIndexOutOfBoundsException Exception</H1> <% try { int array[] = new int[100]; array[100] = 100; } catch (ArrayIndexOutOfBoundsException e) { out.println("Array index out of bounds."); } catch(ArithmeticException e) { out.println("Arithmetic exception: " + e); } catch(Exception e) { out.println("An error occurred: " + e); } %> </BODY> </HTML> catch try/catch

Nesting try/catch Statements
try try catch catch catch try try try

try/catch

ch08_07.jsp

<HTML> <HEAD> <TITLE>Nesting try/catch Statements</TITLE> </HEAD>

Week 2 – Page 15

<BODY> <H1>Nesting try/catch Statements</H1> <% try { try { int c[] = {0, 1, 2, 3}; c[4] = 4; } catch(ArrayIndexOutOfBoundsException e) { out.println("Array index out of bounds: " + e); } } catch(ArithmeticException e) { out.println("Divide by zero: " + e); } %> </BODY> </HTML>

try/catch

Week 2 – Page 16

Throwing Exceptions Yourself
Exception catch Exception ArithmeticException throw

ch08_08.jsp

<HTML> <HEAD> <TITLE>Throwing an Exception</TITLE> </HEAD> <BODY> <H1>Throwing an Exception</H1> <% try { throw new ArithmeticException("Math Exception!"); } catch(ArithmeticException e) { out.println("Exception message: " + e); } %> </BODY> </HTML>

catch

Throwing Exceptions from Methods
out

Week 2 – Page 17

<HTML> <HEAD> <TITLE>Passing the out Object to a Method</TITLE> </HEAD> <BODY> <H1>Passing the out Object to a Method</H1> <%! void printem(javax.servlet.jsp.JspWriter out) throws java.io.IOException { out.println("Hello from JSP!"); } %> <% printem(out); %> </BODY> </HTML> out printem out java.io.IOException

throws

doWork ArrayIndexOutOfBoundsException

<%! void doWork() throws ArrayIndexOutOfBoundsException { int array[] = new int[100]; array[100] = 100; } %> doWork catch try

<% try {

Week 2 – Page 18

doWork(); } catch (ArrayIndexOutOfBoundsException e) { out.println("Array out of bounds exception"); } %>

ch08_09.jsp

<HTML> <HEAD> <TITLE>Throwing Exceptions From Methods</TITLE> </HEAD> <BODY> <H1>Throwing Exceptions From Methods</H1> <%! void doWork() throws ArrayIndexOutOfBoundsException { int array[] = new int[100]; array[100] = 100; } %> <% try { doWork(); } catch (ArrayIndexOutOfBoundsException e) { out.println("Array out of bounds exception"); } %> </BODY> </HTML>

doWork

Week 2 – Page 19

Creating a Custom Exception Object
Exception

NewException Exception extends

class NewException extends Exception { . . . } NewException Exception getMessage toString out.println toString

Week 2 – Page 20

class NewException extends Exception { int value; public String toString() { return "NewException " + value; } NewException(int v) { value = v; } } doWork NewException

0 doWork

ch08_10.jsp

<HTML> <HEAD> <TITLE>Creating a Custom Exception Object</TITLE> </HEAD> <BODY> <H1>Creating a Custom Exception Object</H1> <%! class NewException extends Exception { int value; public String toString() { return "NewException " + value; } NewException(int v) { value = v; } } void doWork(int value) throws NewException { if(value == 0){ throw new NewException(value); } } %> <% try {

Week 2 – Page 21

doWork(3); doWork(2); doWork(1); doWork(0); } catch (NewException e) { out.println("Exception: " + e); } %> </BODY> </HTML>

Printing to the Server Console
System.out.println out.println System.out.println

Week 2 – Page 22

ch08_11.jsp

<HTML> <HEAD> <TITLE>Printing to the Server Console</TITLE> </HEAD> <BODY> <H1>Printing to the Server Console</H1> <% try{ int value = 1; value = value / 0; } catch (Exception e){ System.out.println(e.getMessage()); } %> </BODY> </HTML>

/ by zero

Week 2 – Page 23

Exception

printStackTrace

ch08_12.jsp

<HTML> <HEAD> <TITLE>Printing a Stack Trace to the Server Console</TITLE> </HEAD> <BODY> <H1>Printing a Stack Trace to the Server Console</H1> <% try{ int value = 1; value = value / 0; } catch (Exception e){ e.printStackTrace(); } %> </BODY> </HTML>

Using Log Files

http://localhost:8080/examples/ server.xml jakarta-tomcat-4.0.3\conf

<!-- Tomcat Examples Context --> <Context path="/examples" docBase="examples" debug="0" reloadable="true" crossContext="true">

Week 2 – Page 24

<Logger className="org.apache.catalina.logger.FileLogger" prefix="localhost_examples_log." suffix=".txt" timestamp="true"/>

localhost_examples_log.2003-03-29.txt

2003-05-10 10:54:22 StandardWrapperValve[jsp]: Servlet.service() for servlet jsp threw exception java.lang.ArithmeticException: / by zero at org.apache.jsp.simple_0005ferror$jsp._jspService(simple_0005ferror$jsp. java:60) at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:107) at javax.servlet.http.HttpServlet.service(HttpSe rvlet.java:853) at org.apache.jasper.servlet.JspServlet$JspServletWrapper. service(JspServlet.java: 202) at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet. java:382) at org.apache.jasper.servlet.JspServlet.service(JspServlet.ja va:474) at javax.servlet.http.HttpServlet.service(HttpServlet.java:853) at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter ( ApplicationFilterChain.java:247) at org.apache.catalina.core.ApplicationFilterChain.doFilter (ApplicationFilterChain. java:193) at org.apache.catalina.core.StandardWrapperValve.invoke (StandardWrapperValve.java: 243) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:566) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline. java:472) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943) at org.apache.catalina.core.StandardContextValve.invoke (StandardContextValve.java: 190) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:566) at org.apache.catalina.authenticator.AuthenticatorBase.invoke (AuthenticatorBase.

Week 2 – Page 25

java:475) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:564) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline. java:472) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943) at org.apache.catalina.core.StandardContext.invoke(StandardContext. java:2343) at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve. java:180) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:566) at org.apache.catalina.valves.ErrorDispatcherValve.invoke (ErrorDispatcherValve.java: 170) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:564) at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve. java:170) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:564) at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve. java:468) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:564) at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline. java:472) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943) at org.apache.catalina.core.StandardEngineValve.invoke (StandardEngineValve.java:174) at org.apache.catalina.core.StandardPipeline.invokeNext(StandardPipeline. java:566) at org.apache.catalina.core.StandardPipeline.invoke(Standa rdPipeline. java:472) at org.apache.catalina.core.ContainerBase.invoke(ContainerBase.java:943) at org.apache.catalina.connector.http.HttpProcessor.process(HttpProcessor. java:1012) at org.apache.catalina.connector.http.HttpProcessor.run(HttpProcessor. java:1107) at java.lang.Thread.run(Thread.java:484)

Week 2 – Page 26

2002-05-10 10:56:13 SessionListener: contextDestroyed() 2002-05-10 10:56:13 ContextListener: contextDestroyed()

Using JSP Error Pages
page errorPage ch08_14.jps ch08_13.jsp

<%@ page errorPage="ch08_14.jsp" %> <HTML> <HEAD> <TITLE>Using an Error Page</TITLE> </HEAD> <BODY> <H1>Using an Error Page</H1> <% int value = 1; value = value / 0; %> </BODY> </HTML>

page "true" "false" ch08_14.jsp

isErrorPage

<%@ page isErrorPage="true" %> <HTML> <HEAD> <TITLE>An Error Page</TITLE> </HEAD> <BODY> <H1>An Error Page</H1> There was an error! Don't Panic!!! <BR> Consult your physician immediately. </BODY> </HTML>

Week 2 – Page 27

ch08_13.jsp

Using JSP Error Pages: The exception Object
request exception java.lang.Throwable ch08_16.jsp exception ch08_15.jsp toString

<%@ page errorPage="ch08_16.jsp" %> <HTML>

Week 2 – Page 28

<HEAD> <TITLE>Using the exception Object</TITLE> </HEAD> <BODY> <H1>Using the exception Object</H1> <% int value = 1; value = value / 0; %> </BODY> </HTML> ch06_16.jsp exception

exception ch08_16.jsp

<%@ page isErrorPage="true" %> <HTML> <HEAD> <TITLE>An Error Page Using the exception Object</TITLE> </HEAD> <BODY> <H1>An Error Page Using the exception Object</H1> An error occurred: <%= exception.toString() %> </BODY> </HTML>

ch08_15.jsp ch08_15.jsp exception

ch08_16.jsp

Week 2 – Page 29

Using JSP Error Pages: request Object Attributes
request String request "message" String setAttribute

request

ch08_17.jsp

<%@ page errorPage="ch08_18.jsp" %> <HTML> <HEAD> <TITLE>Using request Object Attributes</TITLE> </HEAD> <BODY> <H1>Using request Object Attributes</H1> <% request.setAttribute("message", "Divide by zero."); int value = 1;

Week 2 – Page 30

value = value / 0; %> </BODY> </HTML> getAttribute

exception ch08_18.jsp

<%@ page isErrorPage="true" %> <HTML> <HEAD> <TITLE>An Error Page Using Request Attributes</TITLE> </HEAD> <BODY> <H1>An Error Page Using the exception Object</H1> An error occurred: <%= request.getAttribute("message") %> </BODY> </HTML>

request

Week 2 – Page 31

Summary

try/catch try/catch

try/catch catch finally

try

Exception ArrayIndexOutOfBoundsException catch try try/catch throw catch Exception

page exception request

request

Q&A
try/catch

try/catch try/catch

Week 2 – Page 32

Workshop

Quiz

Exception finally Exception out.println request try/catch

Exercises

try/catch

+ - *

/

ArithmeticException

Week 2 – Page 33

Day 9. Using Custom JSP Tags
<% ... %> <jsp:getProperty>

       

Request

web.xml

Request

request response

<jsp:useBean> <jsp:getProperty> <jsp:setProperty>

Week 2 – Page 34

Tag Libraries

 

Application Taglib DateTime Taglib Date

       

Mailer Taglib Page Taglib Random Taglib Regexp Taglib Random Regexp

Request Taglib Response Taglib Session Taglib XSL Taglib

Week 2 – Page 35

Request

The Request Tag Library
Request request request

Request

<req:existsHeader name="User-Agent"> User-Agent=<req:header name="User-Agent"/> </req:existsHeader> <req:existsHeader> Request User-Agent <req:header> <req:header> <req:existsHeader> request

<% if(request.getHeader("User-Agent") != null) { out.println("User-Agent=" + request.getHeader("User-Agent"); } %>

Week 2 – Page 36

Downloading the Request Tag Library
Request

Request Request Taglib

Request jakarta-taglibs-request-1.0.zip 1.0.tar.gz

jakarta-taglibs-request-

Request  request.tld /WEB-INF  request.jar /WEB-INF/lib   request-doc.war

request-examples.war

Installing the Request Tag Library
Request

webapps\ch09 request.tld request.jar Request

webapps\ch09\WEB-INF webapps\ch09\WEB-INF\lib

request-

Week 2 – Page 37

examples.war

C:\directory>jar xvf request-examples.war Request index.html request.jsp web.xml

index.html web.xml

request.jsp webapps\ch09 webapps\ch09\WEB-INF index.html ch09_02.jsp

request.jsp

ch09_01.html

index.html ch09_01.html

Request

Week 2 – Page 38

Request Request

request ch09_01.html

<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=iso8859-1"> </head> <body bgcolor="#FFFFFF"> <center> <h1> Jakarta REQUEST Taglib Example</h1></center> <br> <p>This page includes a number of hidden input paramters that can then be seen when viewing the request.jsp example page.<br><br> <form action="request.jsp" method="POST"> <input type="hidden" name="test1" value="This is a test"> <input type="hidden" name="test2" value="This is another test"> <input type="hidden" name="test3" value="This is a third test"> <input type="hidden" name="test3" value="Third test with multiple values"> <input type="hidden" name="test4" value="AAbb"> Select the <input type="submit" name="submit" value="SUBMIT"> button to see the output from the request.jsp example page. </form> <br> See the source from the <a href="request.html">request.jsp</a> example page. </body> </html>

request.jar Request

Week 2 – Page 39

Jakarta REQUEST Taglib Example Cookies received with request: Cookie name: Comment: Domain: MaxAge: Path: Secure: Value: Version: JSESSIONID

-1 0 44454937C05623D4121E3B8ED9F36C75 0

Week 2 – Page 40

See if JSESSIONID Cookie exists JSESSIONID=44454937C05623D4121E3B8ED9F36C75 HTTP Headers received with request: accept = image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */* referer = http://localhost:8080/ch09/ch09_01.html accept-language = en-us content-type = application/x-www-form-urlencoded accept-encoding = gzip, deflate user-agent = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET CLR 1.0.3512) host = localhost:8080 content-length = 137 connection = Keep-Alive cache-control = no-cache cookie = JSESSIONID=44454937C05623D4121E3B8ED9F36C75 See if User-Agent Header exists User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET CLR 1.0.3512) GET or POST Parameters received with request: test4 = AAbb test3 = This is a third test test2 = This is another test test1 = This is a test submit = SUBMIT GET or POST Parameters received with request for test3: test3 = This is a third test test3 = Third test with multiple values See if test1 parameter exists test1=This is a test See if parameter test4 equals "aabb" Parameter test4 does not equal "aabb". See if test4 equals "aabb", ignoring case test4=AAbb Set an attribute named "myatt" See if myatt attribute exists myatt=AAbb Set an attribute named "myatt2" to the Header User-agent See if myatt equals "aabb" Attribute myatt does not equal "aabb". See if myatt equals "aabb", ignoring case myatt=AAbb

Week 2 – Page 41

Now loop through all the attributes myatt2 = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET CLR 1.0.3512) myatt = AAbb Now remove the attribute myatt See if myatt attribute exists Attribute myatt does not exist. Request Information: AuthType: ContextPath: /ch09 Method: POST PathInfo: PathTranslated: QueryString: RemoteUser: RequestedSessionId: 44454937C05623D4121E3B8ED9F36C75 RequestURI: /ch09/ch09_02.jsp RequestURL: http://localhost:8080/ch09/ch09_02.jsp ServletPath: /ch09_02.jsp CharacterEncoding: ContentLength: 137 ContentType: application/x-www-form-urlencoded Protocol: HTTP/1.1 RemoteAddr: 127.0.0.1 RemoteHost: 127.0.0.1 Scheme: http ServerName: localhost ServerPort: 8080 IsSecure? Session is not using HTTPS. IsSessionFromCookie? Session is using a cookie. IsSessionFromURL? Session is not using a URL. IsSessionValid? Session is not valid. IsUserInRole "admin"? User is not in role admin. Log a message to the servlet context log. ch09_02.jsp ch09_02.jsp Request lib ch09_02.jsp Request

<!doctype html public "-//w3c//dtd html 4.0 transitional//en"> <html> <head> <title>Jakarta REQUEST Taglib Example</title> </head> <body bgcolor="white"> <center> <h1> Jakarta REQUEST Taglib Example</h1></center> <br>

Week 2 – Page 42

<%@ taglib uri="http://jakarta.apache.org/taglibs/request-1.0" prefix="req" %> <p> <pre> Cookies received with request: <req:cookies id="oatmeal"> Cookie name: Comment: Domain: MaxAge: Path: Secure: Value: Version: </req:cookies> <jsp:getProperty <jsp:getProperty <jsp:getProperty <jsp:getProperty <jsp:getProperty <jsp:getProperty <jsp:getProperty <jsp:getProperty name="oatmeal" name="oatmeal" name="oatmeal" name="oatmeal" name="oatmeal" name="oatmeal" name="oatmeal" name="oatmeal" property="name"/> property="comment"/> property="domain"/> property="maxAge"/> property="path"/> property="secure"/> property="value"/> property="version"/>

See if JSESSIONID Cookie exists <req:existsCookie name="JSESSIONID"> JSESSIONID=<req:cookie name="JSESSIONID"/> </req:existsCookie> <req:existsCookie name="JSESSIONID" value="false"> Cookie JSESSIONID does not exist. </req:existsCookie> HTTP Headers received with request: <req:headers id="hdrs"> <jsp:getProperty name="hdrs" property="name"/> = <jsp:getProperty name="hdrs" property="header"/> </req:headers> See if User-Agent Header exists <req:existsHeader name="User-Agent"> User-Agent=<req:header name="User-Agent"/> </req:existsHeader> <req:existsHeader name="User-Agent" value="false"> Header User-Agent does not exist. </req:existsHeader> GET or POST Parameters received with request: <req:parameters id="param"> <jsp:getProperty name="param" property="name"/> = <jsp:getProperty name="param" property="value"/> </req:parameters> GET or POST Parameters received with request for test3: <req:parameters id="param" name="test3"> <req:parameterValues id="pv"> <jsp:getProperty name="param" property="name"/> = <jsp:getProperty name="pv" property="value"/> </req:parameterValues> </req:parameters>

Week 2 – Page 43

See if test1 parameter exists <req:existsParameter name="test1"> test1=<req:parameter name="test1"/> </req:existsParameter> <req:existsParameter name="test1" value="false"> Parameter test1 does not exist. </req:existsParameter> See if parameter test4 equals "aabb" <req:equalsParameter name="test4" match="aabb"> test4=<req:parameter name="test4"/> </req:equalsParameter> <req:equalsParameter name="test4" match="aabb" value="false"> Parameter test4 does not equal "aabb". </req:equalsParameter> See if test4 equals "aabb", ignoring case <req:equalsParameter name="test4" match="aabb" ignoreCase="true"> test4=<req:parameter name="test4"/> </req:equalsParameter> <req:equalsParameter name="test4" match="aabb" value="false" ignoreCase="true"> Parameter test4 does not equal "aabb", ignoring case. </req:equalsParameter> Set an attribute named "myatt" <req:setAttribute name="myatt">AAbb</req:setAttribute> See if myatt attribute exists <req:existsAttribute name="myatt"> myatt=<req:attribute name="myatt"/> </req:existsAttribute> <req:existsAttribute name="myatt" value="false"> Attribute myatt does not exist. </req:existsAttribute> Set an attribute named "myatt2" to the Header User-agent <req:setAttribute name="myatt2"><req:header name="UserAgent"/></req:setAttribute> See if myatt equals "aabb" <req:equalsAttribute name="myatt" match="aabb"> myatt=<req:attribute name="myatt"/> </req:equalsAttribute> <req:equalsAttribute name="myatt" match="aabb" value="false"> Attribute myatt does not equal "aabb". </req:equalsAttribute> See if myatt equals "aabb", ignoring case <req:equalsAttribute name="myatt" match="aabb" ignoreCase="true"> myatt=<req:attribute name="myatt"/> </req:equalsAttribute> <req:equalsAttribute name="myatt" match="aabb" value="false" ignoreCase="true"> Attribute myatt does not equal "aabb", ignoring case. </req:equalsAttribute> Now loop through all the attributes <req:attributes id="att"> <jsp:getProperty name="att" property="name"/> = <jsp:getProperty

Week 2 – Page 44

name="att" property="attribute"/> </req:attributes> Now remove the attribute myatt <req:removeAttribute name="myatt"/> See if myatt attribute exists <req:existsAttribute name="myatt"> myatt=<req:attribute name="myatt"/> </req:existsAttribute> <req:existsAttribute name="myatt" value="false"> Attribute myatt does not exist. </req:existsAttribute> <req:request id="rq"/> Request Information: AuthType: <jsp:getProperty name="rq" property="authType"/> ContextPath: <jsp:getProperty name="rq" property="contextPath"/> Method: <jsp:getProperty name="rq" property="method"/> PathInfo: <jsp:getProperty name="rq" property="pathInfo"/> PathTranslated: <jsp:getProperty name="rq" property="pathTranslated"/> QueryString: <jsp:getProperty name="rq" property="queryString"/> RemoteUser: <jsp:getProperty name="rq" property="remoteUser"/> RequestedSessionId: <jsp:getProperty name="rq" property="requestedSessionId"/> RequestURI: <jsp:getProperty name="rq" property="requestURI"/> RequestURL: <jsp:getProperty name="rq" property="requestURL"/> ServletPath: <jsp:getProperty name="rq" property="servletPath"/> CharacterEncoding: <jsp:getProperty name="rq" property="characterEncoding"/> ContentLength: <jsp:getProperty name="rq" property="contentLength"/> ContentType: <jsp:getProperty name="rq" property="contentType"/> Protocol: <jsp:getProperty name="rq" property="protocol"/> RemoteAddr: <jsp:getProperty name="rq" property="remoteAddr"/> RemoteHost: <jsp:getProperty name="rq" property="remoteHost"/> Scheme: <jsp:getProperty name="rq" property="scheme"/> ServerName: <jsp:getProperty name="rq" property="serverName"/> ServerPort: <jsp:getProperty name="rq" property="serverPort"/> </pre> <br><br> <p> IsSecure? <req:isSecure>Session is using HTTPS.</req:isSecure> <req:isSecure value="false">Session is not using HTTPS.</req:isSecure> <br><br> <p> IsSessionFromCookie? <req:isSessionFromCookie>Session is using a cookie.</req:isSessionFromCookie> <req:isSessionFromCookie value="false">Session is not using a cookie.</req: isSessionFromCookie> <br><br> <p> IsSessionFromURL? <req:isSessionFromUrl>Session is using a URL.</req:isSessionFromUrl> <req:isSessionFromUrl value="false">Session is not using a URL.</req:isSessionFromUrl>

Week 2 – Page 45

<br><br> <p> IsSessionValid? <req:isSessionValid>Session is valid.</req:isSessionValid> <req:isSessionValid value="false">Session is not valid.</req:isSessionValid> <br><br> <p> IsUserInRole "admin"? <req:isUserInRole role="admin">User is in role admin.</req:isUserInRole> <req:isUserInRole role="admin" value="false">User is not in role admin.</req:isUserInRole> <br><br> Log a message to the servlet context log. <req:log> Test of logging to your servlet context log by the request taglib. </req:log> </body> </html>

Using a Tag Library
Request taglib

<%@ taglib uri="http://jakarta.apache.org/taglibs/reques t-1.0" prefix="req" %> taglib

taglib req headers <req:headers id="hdrs"> . . . </req:headers> jsp req Request taglib <jsp:forward> jsp

Week 2 – Page 46

HTTP Headers
Request <req:headers> <jsp:getProperty> <req:headers> hdrs name value

HTTP Headers received with request: <req:headers id="hdrs"> <jsp:getProperty name="hdrs" property="name"/> = <jsp:getProperty name="hdrs" property="header"/> </req:headers>

HTTP Headers received with request: accept = image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/msword, application/vnd.ms-excel, application/vnd.ms-powerpoint, */* referer = http://localhost:8080/ch09/ch09_01.html accept-language = en-us content-type = application/x-www-form-urlencoded accept-encoding = gzip, deflate user-agent = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET CLR 1.0.3512) host = localhost:8080 content-length = 137 connection = Keep-Alive cache-control = no-cache cookie = JSESSIONID=44454937C05623D4121E3B8ED9F36C75 Request <req:headers> User-Agent <req:existsHeader> <req:header>

See if User-Agent Header exists <req:existsHeader name="User-Agent"> User-Agent=<req:header name="User-Agent"/> </req:existsHeader>

Week 2 – Page 47

<req:existsHeader name="User-Agent" value="false"> Header User-Agent does not exist. </req:existsHeader>

See if User-Agent Header exists User-Agent=Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET CLR 1.0.3512)

Request Parameters
request

<input type="hidden" <input type="hidden" <input type="hidden" <input type="hidden" values"> <input type="hidden"

name="test1" name="test2" name="test3" name="test3"

value="This is a test"> value="This is another test"> value="This is a third test"> value="Third test with multiple

name="test4" value="AAbb"> <req:parameters> <req:headers>

GET or POST Parameters received with request: <req:parameters id="param"> <jsp:getProperty name="param" property="name"/> = <jsp:getProperty name="param" property="value"/> </req:parameters> test3 <req:parameterValues> <jsp:getProperty>

GET or POST Parameters received with request for test3: <req:parameters id="param" name="test3"> <req:parameterValues id="pv"> <jsp:getProperty name="param" property="name"/> = <jsp:getProperty name="pv"

Week 2 – Page 48

property="value"/> </req:parameterValues> </req:parameters>

<req:parameter> <req:existsParameter>

See if test1 parameter exists <req:existsParameter name="test1"> test1=<req:parameter name="test1"/> </req:existsParameter> <req:existsParameter name="test1" value="false"> Parameter test1 does not exist. </req:existsParameter> See if parameter test4 equals "aabb" <req:equalsParameter name="test4" match="aabb"> test4=<req:parameter name="test4"/> </req:equalsParameter> <req:equalsParameter name="test4" match="aabb" value="false"> Parameter test4 does not equal "aabb". </req:equalsParameter> See if test4 equals "aabb", ignoring case <req:equalsParameter name="test4" match="aabb" ignoreCase="true"> test4=<req:parameter name="test4"/> </req:equalsParameter> <req:equalsParameter name="test4" match="aabb" value="false" ignoreCase="true"> Parameter test4 does not equal "aabb", ignoring case. </req:equalsParameter>

GET or POST Parameters received with request: test4 = AAbb test3 = This is a third test test2 = This is another test test1 = This is a test submit = SUBMIT GET or POST Parameters received with request for test3: test3 = This is a third test test3 = Third test with multiple values See if test1 parameter exists test1=This is a test See if parameter test4 equals "aabb" Parameter test4 does not equal "aabb". See if test4 equals "aabb", ignoring case

Week 2 – Page 49

test4=AAbb <req:parameter> getParameter getParameter

<req:parameters>

Setting Attributes
Request <req:setAttribute> <req:existsAttribute> <req:attribute> myatt2 request

myatt

Set an attribute named "myatt" <req:setAttribute name="myatt">AAbb</req:setAttribute> See if myatt attribute exists <req:existsAttribute name="myatt"> myatt=<req:attribute name="myatt"/> </req:existsAttribute> <req:existsAttribute name="myatt" value="false"> Attribute myatt does not exist. </req:existsAttribute> Set an attribute named "myatt2" to the Header User-agent <req:setAttribute name="myatt2"> <req:header name="UserAgent"/></req:setAttribute> See if myatt equals "aabb" <req:equalsAttribute name="myatt" match="aabb"> myatt=<req:attribute name="myatt"/> </req:equalsAttribute> <req:equalsAttribute name="myatt" match="aabb" value="false"> Attribute myatt does not equal "aabb". </req:equalsAttribute> See if myatt equals "aabb", ignoring case <req:equalsAttribute name="myatt" match="aabb" ignoreCase="true"> myatt=<req:attribute name="myatt"/> </req:equalsAttribute> <req:equalsAttribute name="myatt" match="aabb" value="false" ignoreCase="true"> Attribute myatt does not equal "aabb", ignoring case. </req:equalsAttribute> Now loop through all the attributes <req:attributes id="att"> <jsp:getProperty name="att" property="name"/> = <jsp:getProperty name="att" property="attribute"/> </req:attributes> Now remove the attribute myatt <req:removeAttribute name="myatt"/>

Week 2 – Page 50

See if myatt attribute exists <req:existsAttribute name="myatt"> myatt=<req:attribute name="myatt"/> </req:existsAttribute> <req:existsAttribute name="myatt" value="false"> Attribute myatt does not exist. </req:existsAttribute>

Set an attribute named "myatt" See if myatt attribute exists myatt=AAbb Set an attribute named "myatt2" to the Header User-agent See if myatt equals "aabb" Attribute myatt does not equal "aabb". See if myatt equals "aabb", ignoring case myatt=AAbb Now loop through all the attributes myatt2 = Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; COM+ 1.0.2204; .NET CLR 1. 0.3512) myatt = AAbb Now remove the attribute myatt See if myatt attribute exists Attribute myatt does not exist.

Request Properties
Request getRemoteUser <req:request> <jsp:getProperty> request getMethod ID <req:request>

<req:request id="rq"/> Request Information: AuthType: <jsp:getProperty name="rq" property="authType"/> ContextPath: <jsp:getProperty name="rq" property="contextPath"/> Method: <jsp:getProperty name="rq" property="method"/> PathInfo: <jsp:getProperty name="rq" property="pathInfo"/> PathTranslated: <jsp:getProperty name="rq" property="pathTranslated"/> QueryString: <jsp:getProperty name="rq" property="queryString"/> RemoteUser: <jsp:getProperty name="rq" property="remoteUser"/> RequestedSessionId: <jsp:getProperty name="rq"

Week 2 – Page 51

property="requestedSessionId"/> RequestURI: <jsp:getProperty name="rq" property="requestURI"/> RequestURL: <jsp:getProperty name="rq" property="requestURL"/> ServletPath: <jsp:getProperty name="rq" property="servletPath"/> CharacterEncoding: <jsp:getProperty name="rq" property="characterEncoding"/> ContentLength: <jsp:getProperty name="rq" property="contentLength"/> ContentType: <jsp:getProperty name="rq" property="contentType"/> Protocol: <jsp:getProperty name="rq" property="protocol"/> RemoteAddr: <jsp:getProperty name="rq" property="remoteAddr"/> RemoteHost: <jsp:getProperty name="rq" property="remoteHost"/> Scheme: <jsp:getProperty name="rq" property="scheme"/> ServerName: <jsp:getProperty name="rq" property="serverName"/> ServerPort: <jsp:getProperty name="rq" property="serverPort"/>

Request Information: AuthType: ContextPath: /ch09 Method: POST PathInfo: PathTranslated: QueryString: RemoteUser: RequestedSessionId: 44454937C05623D4121E3B8ED9F36C75 RequestURI: /ch09/ch09_02.jsp RequestURL: http://localhost:8080/ch09/ch09_02.jsp ServletPath: /ch09_02.jsp CharacterEncoding: ContentLength: 137 ContentType: application/x-www-form-urlencoded Protocol: HTTP/1.1 RemoteAddr: 127.0.0.1 RemoteHost: 127.0.0.1 Scheme: http ServerName: localhost ServerPort: 8080

<req:parameter> <req:parameters>

<req:xxxx>

Week 2 – Page 52

Tag Library Descriptor Files
Request req taglib

<%@ taglib uri="http://jakarta.apache.org/taglibs/reques t-1.0" prefix="req" %> web.xml web.xml request.tld <taglib> WEB-INF

<taglib> <taglib-uri>http://jakarta.apache.org/taglibs/request-1.0</tagliburi> <taglib-location>/WEB-INF/request.tld</taglib-location> </taglib> <taglib-uri> <taglib-location>

request.tld

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.1//EN" "http://java.sun.com/j2ee/dtds/web-jsptaglibrary_1_1.dtd"> <taglib> <tlibversion>1.0</tlibversion> <jspversion>1.1</jspversion> <shortname>request</shortname> <uri>http://jakarta.apache.org/taglibs/request-1.0</uri> <info>The REQUEST custom tag library contains tags which can be used to access all the information about the HTTP request for a JSP page. Tags are provided to access information in the HTTP request for HTTP input parameters from a POST or GET, HTTP Headers, Cookies, request attributes, and session information related to this request.</info> <tag> <name>log</name> <tagclass>org.apache.taglibs.request.LogTag</tagclass>

Week 2 – Page 53

<bodycontent>JSP</bodycontent> </tag> . . . <tag> <name>existsQueryString</name> <tagclass>org.apache.taglibs.request.ExistsQueryStringTag</tagclass> <bodycontent>JSP</bodycontent> <attribute> <name>name</name> <required>yes</required> <rtexprvalue>no</rtexprvalue> </attribute> <attribute> <name>value</name> <required>no</required> <rtexprvalue>no</rtexprvalue> </attribute> </tag> </taglib>

<tlib-version> <jspversion> version> <tagclass> <tag-class>

<tlibversion> <jsprequest.tld

<tag> <req:existsQueryString> <name>

<name> <tagclass>

<req:existsQueryString> org.apache.taglibs.request.ExistsQueryStringTa g request.jar ExistsQueryStringTag org.apache.taglibs.request lib org.apache.taglibs.request.ExistsQueryStringTag request.jar

name <attribute>

value

Week 2 – Page 54

Creating a Simple Tag

Hello! taglib "l"

log

<%@ taglib uri="http://starpowder.com/taglibs" prefix="l"%> <l:log>

<l:log> I'm sending some text to the server console! </l:log> I'm sending some text to the server console!

ch09_03.jsp

<%@ taglib uri="http://starpowder.com/taglibs" prefix="l"%> <HTML> <HEAD> <TITLE>Creating a Simple Custom Tag</TITLE> </HEAD> <BODY> <H1>Creating a Simple Custom Tag</H1> <l:log>

Week 2 – Page 55

I'm sending some text to the server console! </l:log> </BODY> </HTML> http://starpowder.com/taglibs <taglib> web.xml web.xml Request <taglib>

web.xml

ch09\WEB-INF

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN" "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd"> <web-app> <description> Example web application illustrating the use of tags in the "request" custom tag library, from the JAKARTA-TAGLIBS project. </description> <mime-mapping> <extension>txt</extension> <mime-type>text/plain</mime-type> </mime-mapping> . . . <taglib> <taglib-uri> http://jakarta.apache.org/tomcat/examples-taglib </taglib-uri> <taglib-location> /WEB-INF/example-taglib.tld </taglib-location> </taglib> <taglib> <taglib-uri>http://starpowder.com/taglibs</taglib-uri> <taglib-location>/WEB-INF/ch09_04.tld</taglib-location> </taglib> . . .

ch09_04.tld

Creating the Tag Descriptor Library File
ch09_04.tld <l:log> <!DOCTYPE> <!DOCTYPE>

Week 2 – Page 56

<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.tld"> <?xml version="1.0" encoding="ISO-8859-1" ?>

<taglib>

<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.tld"> <taglib> . . . </taglib> <tlib-version> <jsp-version> <short<uri> <description>

name>

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>ch09_05</short-name> <uri>http://starpowder.com/taglibs</uri> <description> A simple tag </description> . . . </taglib> <l:log> <name> <body-content> <description> <tag> <tag-class>

<taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version>

Week 2 – Page 57

<short-name>ch09_05</short-name> <uri>http://starpowder.com/taglibs</uri> <description> A simple tag </description> <!-- log tag --> <tag> <name>log</name> <tag-class>taglib.ch09_05</tag-class> <body-content>TAGDEPENDENT</body-content> <description> Log a message. </description> </tag> </taglib> ch09_04.tld ch09_04.tld

<?xml version="1.0" encoding="ISO-8859-1" ?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.tld"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>ch09_05</short-name> <uri>http://starpowder.com/taglibs</uri> <description> A simple tag </description> <!-- log tag --> <tag> <name>log</name> <tag-class>taglib.ch09_05</tag-class> <body-content>TAGDEPENDENT</body-content> <description> Log a message. </description> </tag> </taglib> <l:log> ch09_05.class

Week 2 – Page 58

Creating the Java Support
ch09_05.java

taglib

package taglib; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.IOException; . . . ch09_05 extends TagSupport TagSupport doStartTag TagSupport <l:log>

EVAL_BODY_INCLUDE

package taglib; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; import java.io.IOException; public class ch09_05 extends TagSupport { public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } . . . } doAfterBody <l:log> Hello! ch09_05.java

package taglib; import javax.servlet.jsp.*;

Week 2 – Page 59

import javax.servlet.jsp.tagext.*; import java.io.IOException; public class ch09_05 extends TagSupport { public int doStartTag() throws JspException { return EVAL_BODY_INCLUDE; } public int doAfterBody() throws JspException { System.out.println("Hello!"); return SKIP_BODY; } } servlet.jar jakarta-tomcat-4.0.3\common\lib CLASSPATH CLASSPATH servlet.jar servlet.jar servlet.jar

C:\>SET CLASSPATH=C:\tomcat\jakarta-tomcat-4.0.3\common\lib\servlet.jar ch09_05.java ch09_05.class javac taglib

ch09_05.class

webapps\ch09\WEB-INF\classes\taglib http://localhost:8080/ch09/ch09_03.js p

Week 2 – Page 60

ch09_03.jsp Hello!

<l:log>

Week 2 – Page 61

Summary

web.xml .class .jar taglib

Request request taglib <taglib> web.xml

TagSupport

Q&A

Week 2 – Page 62

Workshop

Quiz

<taglib>

<taglib>

Exercises
Request

Request

Week 2 – Page 63

Day 10. Creating Custom Tags

     

pageContext

pageContext

A Simple Text-Inserting Tag
<ch10:message>

<ch10:message /> ch10_01.jsp

<%@ taglib prefix="ch10" uri="WEB-INF/ch10_02.tld" %> <HTML>

Week 2 – Page 64

<HEAD> <TITLE>A Simple Tag That Inserts Text</TITLE> </HEAD> <BODY> <H1>A Simple Tag That Inserts Text</H1> <ch10:message /> </BODY> </HTML>

web.xml

<taglib>

WEB-INF

taglib

uri

<%@ taglib prefix="ch10" uri="WEB-INF/ch10_02.tld" %> <ch10:message> ch10_02.tld

Creating a TLD File
<ch10:message> ch10_02.tld <!DOCTYPE>

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> . . . </taglib> <taglib>

<taglib>

<tlib-version> <jsp-version>

Week 2 – Page 65

<short-name> <uri> <display-name> <small-icon> <large-icon> <description> <listener> <tag> <taglib> <ch10:message>

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>TagExamples</short-name> <description>Example tags.</description> <tag> . . . </tag> </taglib> <tag> <tag> <name> <tag-class> <tag>

<name> <tag-class> <tei-class> javax.servlet.jsp.tagext.TagExtraInfo <bodycontent> <displayname>

Week 2 – Page 66

<small-icon> <large-icon> <description> <variable> <attribute> ch10_02.tld message ch10_02.tld taglib.ch10_03

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>TagExamples</short-name> <description>Example tags.</description> <tag> <name>message</name> <tag-class>taglib.ch10_03</tag-class> </tag> </taglib> taglib.ch10_03

Creating the Java Support
taglib.ch10_03 ch10_03.java taglib

package taglib; . . . ch10_03 extends TagSupport

package taglib; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*;

Week 2 – Page 67

public class ch10_03 extends TagSupport { . . . } TagSupport

TagSupport

java.lang.String id PageContext pageContext PageContext TagSupport

TagSupport() int doAfterBody() int doEndTag() EVAL_PAGE int doStartTag() SKIP_BODY java.lang.String getId() Tag getParent() java.lang.Object getValue (java.lang.String k) java.util.Enumeration getValues() void removeValue(java.lang.String k) void setId(java.lang.String id) void setPageContext (PageContext pageContext) void setParent(Tag t) void setValue(java.lang.String k java.lang.Object o) String id

id

PageContext

Week 2 – Page 68

TagSupport javax.servlet.jsp.tagext.IterationTag javax.servlet.jsp.tagext.Tag

javax.servlet.jsp.tagext.IterationTag  int EVAL_BODY_AGAIN



int doAfterBody()

javax.servlet.jsp.tagext.Tag

javax.servlet.jsp.tagext.Tag

int EVAL_BODY_INCLUDE int EVAL_PAGE int SKIP_BODY t SKIP_PAGE javax.servlet.jsp.tagext.Tag

int doEndTag() int doStartTag() Tag getParent() void setPageContext(PageContext°pc) void setParent(Tag°t) <ch10:message> </ch10:message> TagSupport doEndTag

Week 2 – Page 69

package taglib; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; public class ch10_03 extends TagSupport { public int doEndTag() { . . . } "Hello from JSP!" out.println TagSupport pageContext

Working with the Page Context
out pageContext PageContext exception

pageContext

PageContext

java.lang.String APPLICATION int APPLICATION_SCOPE java.lang.String CONFIG java.lang.String EXCEPTION java.lang.String OUT java.lang.String PAGE int PAGE_SCOPE java.lang.String PAGECONTEXT java.lang.String REQUEST int REQUEST_SCOPE

ServletContext

JspWriter

PageContext ServletRequest

Week 2 – Page 70

java.lang.String RESPONSE java.lang.String SESSION int SESSION_SCOPE

ServletResponse PageContext HttpSession PageContext

javax.servlet.jsp.tagext.Tag

java.lang.Object findAttribute (java.lang.String name)

null void forward(java.lang.String relativeUrlPath) ServletRequest ServletResponse

java.lang.Object getAttribute (java.lang.String name) null java.lang.Object getAttribute (java.lang.String name, int scope) null java.util.Enumeration getAttributeNamesInScope (int scope) int getAttributesScope(java.lang.String name) java.lang.Exception getException() exception JspWriter getOut() out JspWriter page Servlet ServletRequest getRequest() request ServletRequest response ServletResponse

java.lang.Object getPage()

ServletResponse getResponse()

Week 2 – Page 71

ServletConfig getServletConfig()

ServletConfig

ServletContext getServletContext() HttpSession getSession()

ServletContext session HttpSession

void handlePageException(java.lang.Exception e) void handlePageException(java.lang.Throwable t) handlePageException (Exception) Throwable

void include(java.lang.String relativeUrlPath) ServletRequest ServletResponse void initialize(Servlet servlet, ServletRequest request, ServletResponse response, java.lang.String errorPageURL, boolean needsSession, int bufferSize, and boolean autoFlush) void release() PageContext void removeAttribute(java.lang.String name)

PageContext

void removeAttribute(java.lang.String name, int scope)

void setAttribute(java.lang.String name java.lang.Object attribute) void setAttribute(java.lang.String name java.lang.Object o, int scope)

pageContext out print println EVAL_PAGE

getOut

package taglib;

Week 2 – Page 72

import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; public class ch10_03 extends TagSupport { public int doEndTag() throws JspException { try { pageContext.getOut().print("Hello from JSP!"); . . . } return EVAL_PAGE; } } out

ch10_03.java

package taglib; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; public class ch10_03 extends TagSupport { public int doEndTag() throws JspException { try { pageContext.getOut().print("Hello from JSP!"); } catch (Exception e) { throw new JspException(e.toString()); } return EVAL_PAGE; } } ch10_01.jsp

Week 2 – Page 73

Creating and Supporting Attributes in Custom Tags
<ch10:message> text

The text is: <ch10:message text="Hello there!"/>

<attribute> <name>

Week 2 – Page 74

<attribute>

<name> <required> true false yes <rtexprvalue> true false yes <description> <type> java.lang.String String no no

<ch10:message>

ch10_04.jsp

<%@ taglib prefix="ch10" uri="WEB-INF/ch10_05.tld" %> <HTML> <HEAD> <TITLE>Supporting Attributes in Custom Tags</TITLE> </HEAD> <BODY> <H1>Supporting Attributes in Custom Tags</H1> The text is: <ch10:message text="Hello there!"/> </BODY> </HTML> text <attribute> java.lang.String <ch10:message>

ch10_05.tld

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>TagExamples</short-name> <description>Example tags.</description> <tag> <name>message</name>

Week 2 – Page 75

<tag-class>taglib.ch10_06</tag-class> <attribute> <name>text</name> <type>java.lang.String</type> </attribute> </tag> </taglib> <ch10:message> set String text setText

public class ch10_06 extends TagSupport { String text; public void setText(String s) { text = s; } public int doEndTag() throws JspException { try { . . . } return EVAL_PAGE; } } setText text pageContext.getOut().print ch10_06.java text

package taglib; import javax.servlet.jsp.tagext.*; import javax.servlet.jsp.*; public class ch10_06 extends TagSupport { String text; public void setText(String s) { text = s; }

Week 2 – Page 76

public int doEndTag() throws JspException { try { pageContext.getOut().print(text); } catch (Exception e) { throw new JspException(e.toString()); } return EVAL_PAGE; } }

Iterating Tags
Week 2 – Page 77

Cast Cast Cast Cast

member: member: member: member:

Ralph Alice Ed Trixie

<ch10:iterator>

<ch10:iterator> Cast member: </ch10:iterator>

pageContext

names setAttribute <ch10:iterator>

ch10_07.jsp

<%@ taglib prefix="ch10" uri="WEB-INF/ch10_08.tld" %> <HTML> <HEAD> <TITLE>Supporting Iterating Custom Tags</TITLE> </HEAD> <BODY> <H1>Supporting Iterating Custom Tags</H1> <% String[] names = new String[]{ "Ralph", "Alice", "Ed", "Trixie" }; pageContext.setAttribute("names", names); %> <ch10:iterator> Cast member: </ch10:iterator> </BODY> </HTML> <ch10:iterator>

Week 2 – Page 78

ch10_08.tld

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>TagExamples</short-name> <description>Example tags.</description> <tag> <name>message</name> <tag-class>taglib.ch10_06</tag-class> <attribute> <name>text</name> <type>javalang.String</type> </attribute> </tag> <tag> <name>iterator</name> <tag-class>taglib.ch10_09</tag-class> </tag> </taglib> pageContext getAttribute doStartTag

package taglib; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ch10_09 extends TagSupport { private String[] names = null; public int doStartTag() { names = (String[]) pageContext.getAttribute("names"); return EVAL_BODY_INCLUDE; } . . .

TagSupport IterationTag TagSupport

Week 2 – Page 79

IterationTag

IterationTag

doAfterBody "Cast member:"

IterationTag doAfterBody

EVAL_BODY_AGAIN SKIP_BODY

counter doAfterBody

public class ch10_09 extends TagSupport { private int counter = 0; private String[] names = null; . . . public int doAfterBody() throws JspException { try{ pageContext.getOut().print(" " + names[counter] + "<BR>"); } catch(Exception e){ throw new JspException(e.toString()); } counter++; if(counter >= names.length) { return SKIP_BODY; } return EVAL_BODY_AGAIN; } } } }

Week 2 – Page 80

ch10_09.html

package taglib; import javax.servlet.jsp.*; import javax.servlet.jsp.tagext.*; public class ch10_09 extends TagSupport { private int counter = 0; private String[] names = null; public int doStartTag() { names = (String[]) pageContext.getAttribute("names"); return EVAL_BODY_INCLUDE; } public int doAfterBody() throws JspException { try{ pageContext.getOut().print(" " + names[counter] + "<BR>"); } catch(Exception e){ throw new JspException(e.toString()); } counter++; if(counter >= names.length) { return SKIP_BODY; } return EVAL_BODY_AGAIN; } }

names

Week 2 – Page 81

pageContext

Cooperating Tags
pageContext names

<% String[] names = new String[]{ "Ralph", "Alice", "Ed", "Trixie" }; pageContext.setAttribute("names", names); %> pageContext <ch10:createCast> names names <ch10:createCast>

<ch10:iterator> <ch10:createCast>

Week 2 – Page 82

<ch10:iterator> ch10_10.jsp

<%@ taglib prefix="ch10" uri="WEB-INF/ch10_11.tld" %> <HTML> <HEAD> <TITLE>Supporting Cooperating Custom Tags</TITLE> </HEAD> <BODY> <H1>Supporting Cooperating Custom Tags</H1> <ch10:createCast/> <ch10:iterator> Cast member: </ch10:iterator> </BODY> </HTML>

ch10_11.tld

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>TagExamples</short-name> <description>Example tags.</description> <tag> <name>message</name> <tag-class>taglib.ch10_06</tag-class> <attribute> <name>text</name> <type>javalang.String</type> </attribute> </tag> <tag> <name>iterator</name> <tag-class>taglib.ch10_09</tag-class> </tag> <tag> <name>createCast</name> <tag-class>taglib.ch10_12</tag-class> </tag> </taglib> <ch10:createCast> <ch10:iterator>

names

Week 2 – Page 83

ch10_12.java

package taglib; import javax.servlet.jsp.tagext.*; public class ch10_12 extends TagSupport { public int doStartTag() { String[] names = new String[] {"Ralph", "Alice", "Ed", "Trixie"}; pageContext.setAttribute("names", names); return SKIP_BODY; } }

Week 2 – Page 84

Using Scripting Variables
pageContext names

<% String[] names = new String[]{ "Ralph", "Alice", "Ed", "Trixie" }; pageContext.setAttribute("names", names); %> <ch10:iterator> Cast member: </ch10:iterator>

<ch10:createCast/>

names

names

PageContext

ch10_13.jsp

<%@ taglib prefix="ch10" uri="WEB-INF/ch10_11.tld" %> <HTML> <HEAD> <TITLE>Using the pageContext Object</TITLE> </HEAD> <BODY> <H1>Using the pageContext Object</H1> <ch10:createCast/> <% String[] names = (String [])pageContext.getAttribute("names"); %> <% for(int loopIndex = 0; loopIndex < names.length; loopIndex++) { out.println("Cast member: " + names[loopInd ex] + "<BR>"); } %> </BODY> </HTML>

Week 2 – Page 85

names names

<% String[] names = (String [])pageContext.getAttribute("names"); %>

pageContext

<variable> <variable> <name-given> <name-from-attribute>

<variable>

<name-given>

Week 2 – Page 86

<name-fromattribute> <variable-class> java.lang.String <declare> true <scope> NESTED <scope> false

<variable>

NESTED AT_BEGIN AT_END

doInitBody doAfterBody doStartTag doInitBody doAfterBody doEndTag doStartTag doEndTag names pageContext

names <ch10:createCast> <ch10:createCast /> getAttribute

names

ch10_14.jsp

<%@ taglib prefix="ch10" uri="WEB-INF/ch10_15.tld" %> <HTML> <HEAD> <TITLE>Using Scripting Variables</TITLE> </HEAD> <BODY> <H1>Using Scripting Variables</H1> <ch10:createCast/> <% for(int loopIndex = 0; loopIndex < names.length; loopIndex++) {

Week 2 – Page 87

out.println("Cast member: " + names[loopIndex] + "<BR>"); } %> </BODY> </HTML> names

ch10_15.tld

<?xml version="1.0" encoding="ISO-8859-1"?> <!DOCTYPE taglib PUBLIC "-//Sun Microsystems, Inc.//DTD JSP Tag Library 1.2//EN" "http://java.sun.com/dtd/web-jsptaglibrary_1_2.dtd"> <taglib> <tlib-version>1.0</tlib-version> <jsp-version>1.2</jsp-version> <short-name>TagExamples</short-name> <description>Example tags.</description> <tag> <name>message</name> <tag-class>taglib.ch10_06</tag-class> <attribute> <name>text</name> <type>javalang.String</type> </attribute> </tag> <tag> <name>iterator</name> <tag-class>taglib.ch10_09</tag-class> </tag> <tag> <name>createCast</name> <tag-class>taglib.ch10_12</tag-class> <variable> <name-given>names</name-given> <variable-class>java.lang.String []</variable-class> <declare>true</declare> <scope>AT_END</scope> </variable> </tag> </taglib> names <ch10:createCast> names

Week 2 – Page 88

BodyTag

Summary
TagSupport

TagSupport doStartTag SKIP_BODY

EVAL_BODY_INCLUDE

<attribute>

set doAfterBody

Week 2 – Page 89

EVAL_BODY_AGAIN

SKIP_BODY

Q&A

.class

web.xml web.xml web.xml web.xml

Workshop

Quiz
<taglib> <tag> TagSupport

Week 2 – Page 90

String <attribute>

Exercises
<attribute> <required> text <required>true</required> <ch10:message>

<ch10:message> <LI> <ch10:iterator> <UL>

Day 11. Creating More Powerful JavaBeans

    

Week 2 – Page 91

  

<jsp:plugin>

Why Inheritance?

TagSupport

TagSupport

Using Inheritance
vehicle start "Starting...<BR>"

class vehicle { public void start()

Week 2 – Page 92

{ out.println("Starting...<BR>"); } } vehicle automobile automobile vehicle extends

class automobile extends vehicle { . . . } automobile start drive automobile vehicle vehicle

automobile

class automobile extends vehicle { public void drive() { out.println("Driving...<BR>"); } } start automobile ch11_01.jsp drive

<HTML> <HEAD> <TITLE>Using Inheritance</TITLE> </HEAD> <BODY> <H1>Using Inheritance</H1> <%! javax.servlet.jsp.JspWriter localOut; class vehicle { public void start() throws java.io.IOException { localOut.println("Starting...<BR>"); }

Week 2 – Page 93

} class automobile extends vehicle { public void drive() throws java.io.IOException { localOut.println("Driving...<BR>"); } } %> <% localOut = out; out.println("Creating an automobile...<BR>"); automobile a = new automobile(); a.start(); a.drive(); %> </BODY> </HTML> start automobile drive

Week 2 – Page 94

vehicle

automobile

class vehicle { public void start() throws java.io.IOException { System.out.println("Starting...<BR>"); } } class automobile extends vehicle { public void drive() throws java.io.IOException { System.out.println("Driving...<BR>"); } } public class application { automobile a = new automobile(); a.drive(); . . .

.java public

vehicle

.java vehicle.java

public class vehicle { public void start() throws java.io.IOException { System.out.println("Starting...<BR>"); } } vehicle.java vehicle vehicle.class javac .java

Week 2 – Page 95

import

import vehicle; class automobile extends vehicle { public void drive() throws java.io.IOException { System.out.println("Driving...<BR>"); } } public class application { automobile a = new automobile(); a.drive(); . . .

vehicle.class CLASSPATH SET CLASSPATH=c:\classes

C:\classes vehicle.class

Using Access Specifiers
start public drive

access class classname [extends ...] [implements ...] { [access] [static] type variable1; . .

Week 2 – Page 96

. [access] [static] type variableN; [access] [static] type method1 (parameter_list) { . . . } . . . [access] [static] type methodN (parameter_list) { . . . } } access protected private protected public private public

start

private

vehicle

class vehicle { private void start() {

throws java.io.IOException

Week 2 – Page 97

localOut.println("Starting...<BR>"); } } . . . out.println("Creating an automobile...<BR>"); automobile a = new automobile(); a.start(); // This won't work! a.drive(); private start protected

ch11_02.jsp

<HTML> <HEAD> <TITLE>Using Restricted Access</TITLE> </HEAD> <BODY> <H1>Using Restricted Access</H1> <%! javax.servlet.jsp.JspWriter localOut; class vehicle { protected void start() throws java.io.IOException { localOut.println("Starting...<BR>"); } } class automobile extends vehicle { public void drive() throws java.io.IOException { localOut.println("Driving...<BR>"); } } %> <% localOut = out; out.println("Creating an automobile...<BR>"); automobile a = new automobile(); a.start(); a.drive(); %>

Week 2 – Page 98

</BODY> </HTML> protected

Calling Superclass Constructors
int a void

Week 2 – Page 99

class a { a() { out.println("In a\'s constructor...<BR>"); } } b a

class b extends a { } b a

b newObject = new b();

b

ch11_03.jsp

<HTML> <HEAD> <TITLE>Calling Superclass Constructors</TITLE> </HEAD> <BODY> <H1>Calling Superclass Constructors</H1> <%! javax.servlet.jsp.JspWriter localOut; class a { a() throws java.io.IOException { localOut.println("In a\'s constructor...<BR>"); } } class b extends a { b() throws java.io.IOException {

Week 2 – Page 100

localOut.println("In b\'s constructor...<BR>"); } } %> <% localOut = out; b obj = new b(); %> </BODY> </HTML>

b

a

b

b

ch11_04.jsp

<HTML> <HEAD> <TITLE>Using Parameterized Constructors</TITLE>

Week 2 – Page 101

</HEAD> <BODY> <H1>Using Parameterized Constructors</H1> <%! javax.servlet.jsp.JspWriter localOut; class a { a() throws java.io.IOException { localOut.println("In a\'s constructor...<BR>"); } } class b extends a { b(String s) throws java.io.IOException { localOut.println("In b\'s String constructor...<BR>"); localOut.println(s); } } %> <% localOut = out; b obj = new b("Hello from JSP!<BR>"); %> </BODY> </HTML> a b b a

Week 2 – Page 102

a

class a { a() { out.println("In a\'s constructor...<BR>"); } a(String s) { out.println("In a\'s String constructor...<BR>"); out.println(s); } } a super b String

Week 2 – Page 103

ch11_05.jsp

<HTML> <HEAD> <TITLE>Working With Constructors and Inheritance</TITLE> </HEAD> <BODY> <H1>Working With Constructors and Inheritance</H1> <%! javax.servlet.jsp.JspWriter localOut; class a { a() throws java.io.IOException { localOut.println("In a\'s constructor...<BR>"); } a(String s) throws java.io.IOException { localOut.println("In a\'s String constructor...<BR>"); localOut.println(s); } } class b extends a { b(String s) throws java.io.IOException { super(s); localOut.println("In b\'s String constructor...<BR>"); localOut.println(s); } } %> <% localOut = out; b obj = new b("Hello from JSP!<BR>"); %> </BODY> </HTML> b String a

Week 2 – Page 104

String a super String

b(String s) throws java.io.IOException { super(s); localOut.println("In b\'s String constructor...<BR>"); localOut.println(s); }

super

Week 2 – Page 105

Overloading Methods

print        print(boolean b) print(char c) print(char[] s) print(double d) print(float f print(int i) print(long l) print

println

print

printText ch11_06.jsp

String

<HTML> <HEAD> <TITLE>Overloading Methods</TITLE> </HEAD> <BODY> <H1>Overloading Methods</H1> <%! javax.servlet.jsp.JspWriter localOut; void printText() throws java.io.IOException { localOut.println("Hello!<BR>"); } void printText(String s) throws java.io .IOException { localOut.println(s + "<BR>"); } %> <%

Week 2 – Page 106

localOut = out; printText(); printText("Hello from JSP!"); %> </BODY> </HTML>

Overriding Methods

final

breathe

breathe

animal Breathing...<BR>

class animal { public void breathe() { out.println("Breathing...<BR>"); } } animal trout Breathing...<BR> Gilling...<BR> trout

breathe

trout

breathe

class animal { public void breathe() { out.println("Breathing...<BR>"); } } class trout extends animal { public void breathe() {

Week 2 – Page 107

out.println("Gilling...<BR>"); } } breathe animal breathe ch11_07.jsp animal trout

<HTML> <HEAD> <TITLE>Overriding Methods</TITLE> </HEAD> <BODY> <H1>Overriding Methods</H1> <%! javax.servlet.jsp.JspWriter localOut; class animal { public void breathe() throws java.io.IOException { localOut.println("Breathing...<BR>"); } } class trout extends animal { public void breathe() throws java.io.IOException { localOut.println("Gilling...<BR>"); } } %> <% localOut = out; out.println("Creating an animal object...<BR>"); animal a = new animal(); a.breathe(); out.println(); out.println("Creating a trout object...<BR>"); trout t = new trout(); t.breathe(); %> </BODY> </HTML> breathe

Week 2 – Page 108

trout

Using Superclass Variables with Subclassed Objects
a a b a vehicle vehicle b

aircraft plane aircraft

class vehicle { public void start() {

Week 2 – Page 109

out.println("Starting...<BR>"); } } class aircraft extends vehicle { public void fly() { out.println("Flying...<BR>"); } } class plane extends aircraft { public void fly() { out.println("Flying...<BR>"); } } plane

out.println("Creating a plane...<BR>"); plane p = new plane(); p.start(); plane plane vehicle

ch11_08.jsp

<HTML> <HEAD> <TITLE>Using Superclass Variables With Subclassed Objects</TITLE> </HEAD> <BODY> <H1>Using Superclass Variables With Subclassed Objects</H1> <%! javax.servlet.jsp.JspWriter localOut; class vehicle { public void start() throws java.io.IOException { localOut.println("Starting...<BR>"); } }

Week 2 – Page 110

class aircraft extends vehicle { public void fly() throws java.io.IOException { localOut.println("Flying...<BR>"); } } class plane extends aircraft { public void fly() throws java.io.IOException { localOut.println("Flying...<BR>"); } } %> <% localOut = out; out.println("Creating a plane object...<BR>"); vehicle p = new plane(); p.start(); //p.fly(); %> </BODY> </HTML>

plane vehicle

Week 2 – Page 111

p.fly() fly vehicle vehicle a aircraft a b b plane

Using Runtime Polymorphism

a a b b c c d

Week 2 – Page 112

print

class a { public void print() { out.println("Hello from a...<BR>"); } } class b extends a { public void print() { out.println("Hello from b...<BR>"); } } class c extends a { public void print() { out.println("Hello from c...<BR>"); } } class d extends a { public void print() { out.println("Hello from d...<BR>"); } }

a b c d

a1 = b1 = c1 = d1 = . . .

new new new new

a(); b(); c(); d();

baseClassVariable

a

a b c d a

a1 = new a(); b1 = new b(); c1 = new c(); d1 = new d(); baseClassVariable;

Week 2 – Page 113

. . . baseClassVariable print print

out

ch11_09.jsp

<HTML> <HEAD> <TITLE>Runtime Polymorphism</TITLE> </HEAD> <BODY> <H1>Runtime Polymorphism</H1> <%! javax.servlet.jsp.JspWriter localOut; class a { public void print() throws java.io.IOException { localOut.println("Hello from a...<BR>"); } } class b extends a { public void print() throws java.io.IOException { localOut.println("Hello from b...<BR>"); } } class c extends a { public void print() throws java.io.IOException { localOut.println("Hello from c...<BR>"); } } class d extends a { public void print() throws java.io.IOException { localOut.println("Hello from d...<BR>"); } } %> <%

Week 2 – Page 114

localOut = out; a b c d a a1 = new a(); b1 = new b(); c1 = new c(); d1 = new d(); baseClassVariable;

baseClassVariable = a1; baseClassVariable.print(); baseClassVariable = b1; baseClassVariable.print(); baseClassVariable = c1; baseClassVariable.print(); baseClassVariable = d1; baseClassVariable.print(); %> </BODY> </HTML>

baseClassVariable

a b c

d

Week 2 – Page 115

a a a

Creating Abstract Classes
getMyName

abstract

a printem getText

printem

class a { String getText(); public void printem() { out.println(getText()); } } getText String getText()

Week 2 – Page 116

getText

abstract class a { abstract String getText(); public void printem() { out.println(getText()); } } a getText

class b extends a { String getText() { return "Hello from JSP!"; } }

ch11_10.jsp

<HTML> <HEAD> <TITLE>Using Abstract Classes</TITLE> </HEAD> <BODY> <H1>Using Abstract Classes</H1> <%! javax.servlet.jsp.JspWriter localOut;

Week 2 – Page 117

abstract class a { abstract String getText() throws java.io.IOException; public void printem() throws java.io.IOException { localOut.println(getText()); } } class b extends a { String getText() throws java.io.IOException { return "Hello from JSP!"; } } %> <% localOut = out; b bObject = new b(); bObject.printem(); %> </BODY> </HTML>

Week 2 – Page 118

Using Interfaces for Multiple Inheritance

extends

class a extends b, c { . . . }

// Will not work!

class a { .

Week 2 – Page 119

. . } class b extends a { . . . } class c extends b { . . . } c a b

interface

interface a { . . . } interface b { . . . } implements

class c implements a, b { . . . }

Week 2 – Page 120

printText

Printem interface

interface Printem { void printText(); } a

ch11_11.jsp

<HTML> <HEAD> <TITLE>Creating a Java Interface</TITLE> </HEAD> <BODY> <H1>Creating a Java Interface</H1> <%! javax.servlet.jsp.JspWriter localOut; interface Printem { void printText() throws java.io.IOException; } class a implements Printem { public void printText() throws java.io.IOException { localOut.println("Hello from JSP!"); } } %> <% localOut = out; a printer = new a(); printer.printText(); %> </BODY> </HTML>

Week 2 – Page 121

Summary
extends

public protected

private

Week 2 – Page 122

Q&A

super method1 super.method1

final

Workshop

Quiz

Week 2 – Page 123

class1 a d class2

a b e class1

c

class2

Exercises

SuperDuperCode getSupport SuperDuperCode SuperDuperCode

getSupport

a Printem Textem Printem Textem getText printText

Day 12. Creating Servlets

    

<jsp:plugin>

Week 2 – Page 124



<jsp:plugin>

Using <jsp:plugin>
.class <jsp:plugin>

+

<jsp:plugin type="bean|applet" code="classFileName" codebase="classFileDirectoryName" [name="Name"] [archive="ArchiveURL, ..."] [align="bottom|top|middle|left|right"] [height="{pixelMeasurement | <%= expression %>}"] [width="{pixelMeasurement | <%= expression %>}"] [hspace="leftRightPixels"] [vspace="topBottomPixels"] [jreversion="versionNumber | 1.2"] [nspluginurl="PluginURL"] [iepluginurl="PluginURL"]> [<jsp:params> [<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" /> ]+ </jsp:params> ] [<jsp:fallback> text </jsp:fallback> ] </jsp:plugin>

  

type="bean|applet" code="classFileName" codebase="classFileDirectoryName" <jsp:plugin>

Week 2 – Page 125

   

name="Name" archive="ArchiveURL, ..." align="bottom|top|middle|left|right" height="{pixelMeasurement | <%= expression %>}" width="{pixelMeasurement | <%= expression %>}" hspace="leftRightPixels" vspace="topBottomPixels"

    

jreversion="versionNumber|1.2" 1.2 nspluginurl="PluginURL" iepluginurl="PluginURL" <jsp:params> [<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />]+ </jsp:params> <jsp:param> <jsp:params>



<jsp:fallback> text </jsp:fallback>

ch01_04.java

import java.applet.Applet; import java.awt.*; public class ch01_04 extends Applet { public void paint(Graphics g) { g.drawString("Hello there!", 60, 100); } } <APPLET> <jsp:plugin> <jsp:plugin>

<jsp:plugin>

ch12_01.jsp

<HTML> element> <HEAD> <TITLE>Using &ltjsp:plugin&gt;</TITLE> </HEAD>

Week 2 – Page 126

<BODY> <H1>Using &ltjsp:plugin&gt;</H1> <jsp:plugin type="applet" code="ch01_04.class" width="200" height="200" > <jsp:fallback> Sorry, &lt;OBJECT&gt; or &lt;EMBED&gt; are not supported by your browser. </jsp:fallback> </jsp:plugin> </BODY> </HTML>

<jsp:plugin>

<jsp:plugin> .class

Week 2 – Page 127

Creating Java Servlets
webapps work work jakarta-tomcat-4.0.3\work ch01 ch02 webapps <jsp:plugin> ch12_01.jsp jakarta-tomcat-4.0.3\work\ch12 ch12_01.jsp ch12_0005f01$jsp.java ch12_01.jsp <jsp:plugin> work

package org.apache.jsp; import import import import javax.servlet.*; javax.servlet.http.*; javax.servlet.jsp.*; org.apache.jasper.runtime.*;

public class ch12_0005f01$jsp extends HttpJspBase { static { } public ch12_0005f01$jsp( ) { } private static boolean _jspx_inited = false; public final void _jspx_init() throws org.apache.jasper.runtime.JspException {} public void _jspService(HttpServletRequest request, HttpServletResponse response) throws java.io.IOException, ServletException { JspFactory _jspxFactory = null; PageContext pageContext = null; HttpSession session = null; ServletContext application = null; ServletConfig config = null; JspWriter out = null; Object page = this; String _value = null; try {

Week 2 – Page 128

if (_jspx_inited == false) { synchronized (this) { if (_jspx_inited == false) { _jspx_init(); _jspx_inited = true; } } } _jspxFactory = JspFactory.getDefaultFactory(); response.setContentType("text/html;charset=IS O-8859-1"); pageContext = _jspxFactory.getPageContext(this, request, response, "", true, 8192, true); application = pageContext.getServletContext(); config = pageContext.getServletConfig(); session = pageContext.getSession(); out = pageContext.getOut(); // HTML // begin [file="/ch12_01.jsp";from=(0,0);to=(7,8)] out.write("<HTML>\r\n <HEAD>\r\n <TITLE> Using &ltjsp:plugin&gt;</TITLE>\r\n </HEAD>\r\n\r\n <BODY>\r\n <H1>Using &ltjsp:plugin&gt;</H1>\r\n "); // end // begin [file="/ch12_01.jsp";from=(7,8);to=(12,21)] /*Code generated for plugin*/ { out.println ("<OBJECT classid=\"clsid: 8AD9C840-044E-11D1B3E9-00805F499D93\" width=\"200\" height=\"200\" codebase=\"http://java.sun.com/products/plugin/1.2.2/ jinstall-1_2_2-win. cab#Version=1,2,2,0\">"); out.println ("<PARAM name=\"java_code\" value=\"ch01_04.class\">"); out.println ("<PARAM name=\"type\" value=\" application/xjava-applet;\">"); String _jspxString = null; String [][] _jspxNSString = null; int i = 0; out.println ("<COMMENT>"); out.print ("<EMBED type=\"application/x-java-applet;\" width=\"200\" height=\"200\" pluginspage=\"http://java.sun. com/products/plugin/\" java_code=\"ch01_04.class\" "); if (_jspxNSString != null) { for (i = 0; i < _jspxNSString.length; i++) { out.println ( _jspxNSString [i][0] + "=" + _ jspxNSString[i][1]); } } out.println (">"); out.println ("<NOEMBED>"); out.println ("</COMMENT>");

Week 2 – Page 129

out.println ("Sorry, &lt;OBJECT&gt; or &lt; EMBED&gt; are not supported by your browser.\r\n"); out.println ("</NOEMBED></EMBED>"); out.println ("</OBJECT>"); } // end // HTML // begin [file="/ch12_01.jsp";from=(12,21);to=(14,7)] out.write("\r\n </BODY>\r\n</HTML>"); // end } catch (Throwable t) { if (out != null && out.getBufferSize() != 0) out.clearBuffer(); if (pageContext != null) pageContext.handlePageException(t); } finally { if (_jspxFactory != null) _jspxFactory.releasePageContext (pageContext); } } }

ch01_06.java ch12_02.java

ch12_02.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("A Web Page"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("Hello there!"); out.println("</BODY>");

Week 2 – Page 130

out.println("</HTML>"); } }

servlet.jar jakarta-tomcat-4.0.3\common\lib directory CLASSPATH CLASSPATH servlet.jar

servlet.jar servlet.jar

C:\>SET CLASSPATH=C:\tomcat\jakarta-tomcat-4.0.3\common\lib\servlet.jar CLASSPATH servlet.jar CLASSPATH

C:>set classpath=%CLASSPATH%;C:\tomcat\jakarta-tomcat4.0.3\common\lib\servlet. jar servlet.jar ch12_02.java javac

javac

ch12_02.class

C:\tomcat\jakarta-tomcat-4.0.3\webapps\ch12\WEB-INF\classes>javac ch12_02.java ch12_02.class jakarta-tomcat4.0.3\webapps\ch12\classes http://localhost:8080/ch12/servlet/ch12_02

Week 2 – Page 131

http://localhost:8080/ch12/servlet/ch12_02

http://localhost:8080/ch12/ch12_02

HttpServlet

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_02 extends HttpServlet { . . . }

Week 2 – Page 132

HttpServlet

GenericServlet GenericServlet HttpServlet

GenericServlet

void destroy()

java.lang.String getInitParameter(java. lang.String name) java.util.Enumeration getInitParameterNames()

String

Enumeration ServletConfig getServletConfig() ServletContext getServletContext() java.lang.String getServletInfo() java.lang.String getServletName() void init()

String ServletConfig

ServletContext

super.init(config) void init(ServletConfig config)

void log(java.lang.String msg) void log(java.lang.String message,java.lang.Throwable t) abstract void service(ServletRequest req, ServletResponse res) HttpServlet

protected void doDelete(HttpServletRequest req,HttpServletResponse resp)

DELETE

Week 2 – Page 133

protected void doGet(HttpServletRequest req,HttpServletResponse resp) GET protected void doHead(HttpServletRequest req,HttpServletResponse resp) HEAD

protected void doOptions(HttpServletRequest req,HttpServletResponse resp)

OPTIONS

protected void doPost(HttpServletRequest req,HttpServletResponse resp) POST protected void doPut(HttpServletRequest req,HttpServletResponse resp) PUT protected void doTrace(HttpServletRequest req,HttpServletResponse resp) protected long getLastModified(HttpServletRequest req)

TRACE HttpServletRequest

protected void service(HttpServletRequest req,HttpServletResponse resp)

doXXX

void service(ServletRequest req,ServletResponse res)

protected service

request

doGet response

GET

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Handle requests... . .

Week 2 – Page 134

. //Configure responses... } } doGet GET POST doPost doGet GET GET service POST doGet doPost doGet doPost POST doPost POST

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_02 extends HttpServlet { public void service(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { //Handle requests... . . . //Configure responses... } . . .

response

Using the response Object
goGet doPost service HttpServletRequest request request HttpServletRequest

Week 2 – Page 135

response goGet doPost service HttpServletResponse

HttpServletResponse

out PrintWriter getWriter

JSPWriter out

PrintWriter setContentType

out

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("A Web Page"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("Hello there!"); out.println("</BODY>"); out.println("</HTML>"); } } println JspWriter PrintWriter PrintWriter PrintWriter

Week 2 – Page 136

PrintWriter(OutputStream out) OutputStream PrintWriter(OutputStream out, boolean autoFlush PrintWriter(Writer out)

PrintWriter

PrintWriter OutputStream PrintWriter

PrintWriter(Writer out boolean autoFlush boolean checkError() void close() void flush() void print(boolean b) void print(char c) void print(char[] s) void print(double d) void print(float f) void print(int i) void print(long l) void print(Object obj) void print(String s) void println() void println(boolean x) void println(char x) void println(char[] x) void println(double x) void println(float x) void println(int x) void println(long x)

PrintWriter

Week 2 – Page 137

void println(Object x) void println(String x) protected void setError() void write(char[] buf) void write(char[] buf int off, int len) void write(int c) void write(String s) void write(String s int off, int len)

Object String

Using the request Object

GET

doGet

ch12_03.html

<HTML> <HEAD> <TITLE>Using Text Fields With Servlets</TITLE> </HEAD> <BODY> <H1>Using Text Fields With Servlets</H1> <FORM NAME="form1" ACTION="servlet/ch12_04" METHOD="GET"> Enter your name: <INPUT TYPE="TEXT" NAME="name"> <INPUT TYPE="SUBMIT" VALUE="Click Me!"> </FORM> </BODY> </HTML>

Week 2 – Page 138

ch12_04.class request request

ACTION getParameter

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_04 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name = request.getParameter("name"); . . .

ch12_04.java

Week 2 – Page 139

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_04 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { String name = request.getParameter("name"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using the request Object"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>"); out.println("Using the request Object"); out.println("</H1>"); out.println("Your name is " + name + "."); out.println("</BODY>"); out.println("</HTML>"); } }

Week 2 – Page 140

The Life Cycle of a Servlet
init destroy init

destroy

msg

init "Hello from Java servlets!"

String

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_05 extends HttpServlet { String msg = ""; public void init(ServletConfig config) {

Week 2 – Page 141

msg = "Hello from Java servlets!"; } . . . } msg msg ch12_05.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_05 extends HttpServlet { String msg = ""; public void init(ServletConfig config) { msg = "Hello from Java servlets!"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using the init Method"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using the init Method</H1>"); out.println(msg); out.println("</BODY>"); out.println("</HTML>"); } } msg

Week 2 – Page 142

Creating Web Applications with Servlets
http://localhost:8080/ch12/servlet/ch12_02 .class

web.xml app>

<webweb.xml

Week 2 – Page 143

<web-app> <display-name> <servlet> <servlet-mapping>

<web-app> <icon> <display-name> <description> <distributable> <context-param> <servlet> <servlet-mapping> <session-config> <mime-mapping> <welcome-file-list> <error-page> <taglib> <resource-ref> <security-constraint> <login-config> <security-role> <env-entry> <ejb-ref> </web-app> web.xml ch12\WEB-INF <display-name>

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/dtd/web-app_2_3.dtd"> <web-app> <display-name>Example Applications</display-name> . . .

<display-name> getServletContextName

Week 2 – Page 144

<servlet> <servlet-class>

<servlet-name>

<?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> <display-name>Example Applications</display-name> <servlet> <servlet-name>ch12_02</servlet-name> <servlet-class>ch12_02</servlet-class> </servlet> . . . <servlet-mapping> <url-pattern> <servlet-

name>

<?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> <display-name>Example Applications</display-name> <servlet> <servlet-name>ch12_02</servlet-name> <servlet-class>ch12_02</servlet-class> </servlet> <servlet-mapping> <servlet-name>ch12_02</servlet-name> <url-pattern>/ch12_02</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app> <url-pattern> "/ch12_02" * "/data/*" ch12_02

Week 2 – Page 145

http://localhost:8080/ch12/ch12_02 http://localhost:8080/ch12/servlet/ch12_02

web.xml

Using Servlet Configurations and Contexts
javax.servlet.ServletConfig ServletConfig ServletContext javax.servlet.ServletContext

Week 2 – Page 146

<init-param> <param-value>

web.xml <servlet> <init-param> firstName lastName

<param-name>

Cary

Grant

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/dtd/web-app_2_3.dtd"> <web-app> <display-name>Example Applications</display-name> <servlet> <servlet-name>ch12_02</servlet-name> <servlet-class>ch12_02</servlet-class> </servlet> <servlet> <servlet-name>ch12_06</servlet-name> <servlet-class>ch12_06</servlet-class> <init-param> <param-name>firstName</param-name> <param-value>Cary</param-value> </init-param> <init-param> <param-name>lastName</param-name> <param-value>Grant</param-value> </init-param> </servlet> . . . ServletConfig GenericServlet getInitParameter firstName

public class ch12_06 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter();

Week 2 – Page 147

String firstName = getInitParameter("firstName") ; . . . ServletConfig getServletConfig lastName

ServletConfig

public class ch12_06 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String firstName = getInitParameter("firstName"); ServletConfig configuration = getServletConfig(); String lastName = configuration.getInitParameter("lastName"); . . .

ServletContext

ServletContext

java.lang.Object getAttribute(java.lang.String name) java.util.Enumeration getAttributeNames()

Enumeration

ServletContext getContext(java.lang.String uripath)

ServletContext

java.lang.String getInitParameter(java.lang.String name)

String

Week 2 – Page 148

java.util.Enumeration getInitParameterNames() Enumeration int getMajorVersion() String

java.lang.String getMimeType (java.lang.String file) int getMinorVersion()

MIME

RequestDispatcher getNamedDispatcher(java.lang.String name) java.lang.String getRealPath(java.lang.String path)

RequestDispatcher String

RequestDispatcher getRequestDispatcher(java.lang.String path) java.net.URL getResource(java.lang.String path) java.io.InputStream getResourceAsStream(java.lang.String path) java.util.Set getResourcePaths(java.lang.String path)

RequestDispatcher

InputStream

java.lang.String getServerInfo() Servlet getServlet(java.lang.String name) java.lang.String getServletContextName() <display-name> java.util.Enumeration getServletNames() java.util.Enumeration getServlets()

Week 2 – Page 149

void log(java.lang.Exception exception java.lang.String msg)

log(String message, Throwable throwable)

void log(java.lang.String msg)

void log(java.lang.String message java.lang.Throwable throwable) void removeAttribute(java.lang.String name)

void setAttribute(java.lang.String name java.lang.Object object)

app>

web.xml <context-param>

<context-param> <web<param-name> <param-value> <init-param>

category Stars 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/dtd/web-app_2_3.dtd"> <web-app> <display-name>Example Applications</display-name> <context-param> <param-name>category</param-name> <param-value>Stars</param-value> </context-param> <servlet> <servlet-name>ch12_02</servlet-name> <servlet-class>ch12_02</servlet-class> </servlet> <servlet> <servlet-name>ch12_06</servlet-name> <servlet-class>ch12_06</servlet-class> <init-param> <param-name>firstName</param-name> <param-value>Cary</param-value> </init-param> <init-param> <param-name>lastName</param-name>

Week 2 – Page 150

<param-value>Grant</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>ch12_02</servlet-name> <url-pattern>/ch12_02</url-pattern> </servlet-mapping> <servlet-mapping> <servlet-name>ch12_06</servlet-name> <url-pattern>/ch12_06</url-pattern> </servlet-mapping> <session-config> <session-timeout>30</session-timeout> </session-config> </web-app>

GenericServlet ServletContext

getServletContext getInitParameter

ServletContext

firstName lastName category ch12_06.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch12_06 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); String firstName = getInitParameter("firstName"); ServletConfig configuration = getServletConfig(); String lastName = configuration.getInitParameter("lastName"); ServletContext context = getServletContext(); String category = context.getInitParameter("category"); out.println("<HTML>");

Week 2 – Page 151

out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using Initialization Parameters"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using Initialization Parameters</H1>"); out.println("First Name: " + firstName); out.println("<BR>"); out.println("Last Name: " + lastName); out.println("<BR>"); out.println("Category: " + category); out.println("<BR>"); out.println("</BODY>"); out.println("</HTML>"); } }

Week 2 – Page 152

Summary
<jsp:plugin>

GET

POST

PrintWriter

getParameter response

init destroy

web.xml

Q&A
<jsp:plugin> <APPLET>

Week 2 – Page 153

setAttribute getAttribute application removeAttribute

Workshop

Quiz
<jsp:plugin>

GET

POST

goGet

doPost

Exercises

Week 2 – Page 154

<servlet> getServletContext

<web-app> setAttribute

web.xml getAttribute

Day 13. Creating More Powerful Servlets

        

Sessions and Servlet Contexts
Week 2 – Page 155

HTTPSession

public class ch13_01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); . . .

getAttribute counter

public class ch13_01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); Integer counter = (Integer) session.getAttribute("counter"); . . . counter

public class ch13_01 extends HttpServlet

Week 2 – Page 156

{ public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); Integer counter = (Integer) session.getAttribute("counter"); if (counter == null) { counter = new Integer(1); } else { counter = new Integer(counter.intValue() + 1); } session.setAttribute("counter", counter); . . . isNew getLastAccessedTime getCreationTime getMaxInactiveInterval getID

ch13_01.java

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class ch13_01 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); Integer counter = (Integer) session.getAttribute("counter"); if (counter == null) { counter = new Integer(1);

Week 2 – Page 157

} else { counter = new Integer(counter.intValue() + 1); } session.setAttribute("counter", counter); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using Sessions"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using Sessions</H1>"); out.println("Welcome! You have been here " + counter + " times.<BR>"); if(session.isNew()){ out.println("This is a new session.<BR>"); } else { out.println("This is not a new session.< BR>"); } out.println("The session ID: " + session.getId() + "<BR>"); out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + " <BR>"); out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>"); out.println("Timeout length: " + session.getMaxInactiveInterval() + " s econds<BR>"); out.println("</BODY>"); out.println("</HTML>"); } }

Week 2 – Page 158

ServletContext

counter2 counter2 getServletContext getAttribute

public class ch13_02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); Integer counter2 = (Integer) getServletContext().getAttribute("counter2"); . . .

Week 2 – Page 159

counter2 counter2

public class ch13_02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true); Integer counter2 = (Integer) getServletContext().getAttribute("counter2"); if (counter2 == null) { counter2 = new Integer(1); } else { counter2 = new Integer(counter2.intValue() + 1); } getServletContext().setAttribute("counter2", counter2); . . .

ch13_02.java

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class ch13_02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); HttpSession session = request.getSession(true);

Week 2 – Page 160

Integer counter2 = (Integer) getServletContext().getAttribute("counter2"); if (counter2 == null) { counter2 = new Integer(1); } else { counter2 = new Integer(counter2.intValue() + 1); } getServletContext().setAttribute("counter2", counter2); Integer counter = (Integer) session.getAttribute("counter"); if (counter == null) { counter = new Integer(1); } else { counter = new Integer(counter.intValue() + 1); } session.setAttribute("counter", counter); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using Contexts"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using Contexts</H1>"); out.println("Welcome! You have been here " + counter + " times.<BR>"); out.println("Total page accesses: " + counter2 + "<BR>"); if(session.isNew()){ out.println("This is a new session.<BR>"); } else { out.println("This is not a new session.<BR>"); } out.println("The session ID: " + session.getId() + "<BR>"); out.println("Last time accessed: " + new Date(session.getLastAccessedTime()) + "<BR>"); out.println("Creation time: " + new Date(session.getCreationTime()) + "<BR>"); out.println("Timeout length: " + session.getMaxInactiveInterval() + " seconds<BR>"); out.println("</BODY>"); out.println("</HTML>"); } }

Week 2 – Page 161

Forwarding Requests to Other Web Resources

servletID

"1"

public class ch13_03 extends HttpServlet {

Week 2 – Page 162

String target = "ch13_05"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("servletID", "1"); . . . } }

RequestDispatcher HttpServletRequest getRequestDispatcher

ch13_05 http://localhost:8080/ch13/ch13_05 <servlet-mapping> web.xml

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch13_03 extends HttpServlet { String target = "ch13_05"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("servletID", "1"); RequestDispatcher dispatcher = request.getRequestDispatcher(target); . . . } }

RequestDispatcher   void forward(ServletRequest request, ServletResponse response)

void include(ServletRequest request, ServletResponse response)

Week 2 – Page 163

forward ch13_03.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch13_03 extends HttpServlet { String target = "ch13_05"; public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("servletID", "1"); RequestDispatcher dispatcher = request.getRequestDispatcher(target); dispatcher.forward(request, response); } } include

<jsp:forward>

<HTML> <HEAD> <TITLE>Forwarding</TITLE> </HEAD> <BODY> <H1>Forwarding</H1> <% request.setAttribute("servletID", "1"); %> <jsp:forward page="ch13_05"/> </BODY> </HTML>

Week 2 – Page 164

Including Output from Other Web Resources
RequestDispatcher servletID 2 RequestDispatcher ch13_05 include

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch13_04 extends HttpServlet { String target = "ch13_05"; public void doGet(HttpServletRequest request, Htt pServletResponse response) throws ServletException, IOException { request.setAttribute("servletID", "2"); RequestDispatcher dispatcher = request.getRequestDispatcher(target); dispatcher.include(request, response); . . .

ch13_05

ch13_04.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch13_04 extends HttpServlet { String target = "ch13_05";

Week 2 – Page 165

public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("servletID", "2"); RequestDispatcher dispatcher = request.getRequestDispatcher(target); dispatcher.include(request, response); PrintWriter out = response.getWriter(); out.println("Response was included.<BR>"); } } include <jsp:include>

<jsp:include page="{relativeURL | <%= expression %>}" flush="true| false" /> <jsp:param> <jsp:forward>

<jsp:param>

<jsp:include page="{relativeURL | <%= expression %>}" flush="true| false" > <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ </jsp:include>



page="{ relativeURL | <%= expression %> }" String



flush="true | false" true

flush



false <jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />+ <jsp:param>

<jsp:include>

<HTML> <HEAD> <TITLE>Includes</TITLE> </HEAD>

Week 2 – Page 166

<BODY> <H1>Includes</H1> <% request.setAttribute("servletID", "2"); %> <jsp:include page="ch13_05"/> Response was included. <BR> </BODY> </HTML>

Handling Forwards and Includes
ch13_03 ch13_04 servletID ch13_04 ch13_03

ch13_05.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch13_05 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String servletID = (String) request.getAttribute("servletID"); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using Sessions"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using Forwards and Includes</H1><BR>");

Week 2 – Page 167

if (servletID != null) { if (servletID.equals("1")) { out.println("Forwarding was successful!<BR>"); } if (servletID.equals("2")) { out.println("Including was successful!<BR>"); } } else { out.println("This example must be invoked with ch13_03 or ch13_04"); } out.println("</BODY>"); out.println("</HTML>"); } } ch13_03

ch13_04

include

Week 2 – Page 168

JSP Model 1 Architecture

Week 2 – Page 169

JSP Model 2 Architecture







The Controller
model msg

public class ch13_06 extends HttpServlet {

Week 2 – Page 170

ch13_07 model1 = new ch13_07(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("message", model1.msg()); . . .

ch13_06.java

import import import import

java.io.*; javax.servlet.*; javax.servlet.http.*; beans.ch13_07;

public class ch13_06 extends HttpServlet { String target = "ch13_08.jsp"; ch13_07 model1 = new ch13_07(); public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setAttribute("message", model1.msg()); RequestDispatcher dispatcher = request.getRequestDispatcher(target); dispatcher.forward(request, response); } }

The Model
msg "Hello from JSP!" ch13_07.java

Week 2 – Page 171

public class ch13_07 { public String msg() { return "Hello from JSP!"; } public ch13_07() { } }

The View
message

ch13_08.jsp

<HTML> <HEAD> <TITLE>Using MVC Architecture</TITLE> </HEAD> <BODY> <H1>Using MVC Architecture</H1> The message is <% out.println(request.getAttribute("message")); %> </BODY> </HTML> ch13_07.java ch13_06.class

ch13_07.class servlet.jar ch13_07.class

ch13_06.java

ch13_07.class WEB-INF\classes\beans

ch13 |____WEB-INF |____classes |____beans

ch13_08.jsp ch13_6.class ch13_07.class

. spath

classpath servlet.jar

Week 2 – Page 172

C:\tomcat\jakarta-tomcat-4.0.3\webapps\ch13\WEB-INF\classes>set classpath=spath\servlet. jar;. ch13_06.java ch13_6 web.xml javac

ch13_06 servlet

ch13_06 ch13_08

ch13_07

Week 2 – Page 173

Supporting User Authentication

web.xml users.xml web.xml <security-constraint> <web-app> <login-config>

tomcat-

<web-app> <icon> <display-name> <description> <distributable> <context-param> <servlet> <servlet-mapping> <session-config> <mime-mapping> <welcome-file-list> <error-page> <taglib> <resource-ref> <security-constraint> <login-config> <security-role> <env-entry> <ejb-ref> </web-app> <security-constraint>

<security-constraint> <web-resource-collection> <web-resource-name> <description> <url-pattern> <http-method> </web-resource-collection> <auth-constraint> <description> <role-name> </auth-constraint> <user-data-constraint> <description> <transport-guarantee> </user-data-constraint> </security-constraint>

Week 2 – Page 174

<login-config>

<login-config> <auth-method> <realm-name> </login-config>

tomcat-users.xml tomcat-users.xml

jakarta-tomcat-4.0.3\conf

<!-NOTE: By default, no user is included in the "manager" role required to operate the "/manager" web application. If you wish to use this app, you must define such a user - the username and password are arbitrary. --> <tomcat-users> <user name="tomcat" password="tomcat" roles="tomcat" /> <user name="role1" password="tomcat" roles="role1" /> <user name="both" password="tomcat" roles="tomcat,role1" /> <user name="steve" password="tomcat" roles="jsp" /> </tomcat-users> name <user> password roles

web.xml <security-constraint> <login-config>

<?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> <display-name>Example Applications</display-name> <servlet> <servlet-name>ch13_01</servlet-name> <servlet-class>ch13_01</servlet-class> </servlet> <servlet> <servlet-name>ch13_02</servlet-name>

Week 2 – Page 175

<servlet-class>ch13_02</servlet-class> </servlet> <servlet> <servlet-name>ch13_03</servlet-name> <servlet-class>ch13_03</servlet-class> </servlet> <servlet> <servlet-name>ch13_04</servlet-name> <servlet-class>ch13_04</servlet-class> </servlet> <servlet> <servlet-name>ch13_05</servlet-name> <servlet-class>ch13_05</servlet-class> </servlet> . . . <session-config> <session-timeout>30</session-timeout> </session-config> <security-constraint> <web-resource-collection> <web-resource-name>Secure Area</web-resource-name> <url-pattern>/ch13_09</url-pattern> </web-resource-collection> <auth-constraint> <role-name>jsp</role-name> </auth-constraint> </security-constraint> <login-config> <auth-method>BASIC</auth-method> <realm-name>JSP Area</realm-name> </login-config> </web-app> web.xml <url-pattern> ch13_09 /secure/* secure * ch13_09

getAuthType getUserPrincipal Steve

BASIC

Week 2 – Page 176

ch13_09.java

import import import import import

java.io.*; java.util.*; java.security.*; javax.servlet.*; javax.servlet.http.*;

public class ch13_09 extends HttpServlet { public void init(ServletConfig cfg) throws ServletException { super.init(cfg); } public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("User Authentication"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>User Authentication</H1>"); String type = request.getAuthType(); out.println("Welcome to this secure page.<BR>"); out.println("Authentication mechanism: " + type + "<BR>"); Principal principal = request.getUserPrincipal(); out.println("Your username is: " + principal.getName() + "<BR>"); out.println("</BODY>"); out.println("</HTML>"); } }

tomcat-users.xml

Week 2 – Page 177

Week 2 – Page 178

Using Cookies in Servlets

ch13_10.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch13_10 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("A Web Page"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY"); Cookie[] cookies = request.getCookies(); boolean foundCookie = false; for(int loopIndex = 0; loopIndex < cookies.length; loopIndex++) { Cookie cookie1 = cookies[loopIndex];

Week 2 – Page 179

if (cookie1.getName().equals("color")) { out.println("bgcolor = " + cookie1.getValue()); foundCookie = true; } } if (!foundCookie) { Cookie cookie1 = new Cookie("color", "cyan"); cookie1.setMaxAge(24*60*60); response.addCookie(cookie1); } out.println(">"); out.println("<H1>Setting and Reading Cookies</H1>"); out.println("This page will set its background color using a cookie when reloaded. "); out.println("</BODY>"); out.println("</HTML>"); } } color "cyan"

Week 2 – Page 180

Thread Safety

static

SingleThreadModel service

public class servlet1 extends HttpServlet implements SingleThreadModel { . . . } page isThreadSafe true

false

synchronized shared synchronized

class CustomThread { Shared shared; public CustomThread(Shared shared, String string)

Week 2 – Page 181

{ super(string); this.shared = shared; start(); } public void run() { synchronized(shared) { shared.doWork(); } } }

Summary

getCookies

addCookie

Week 2 – Page 182

Q&A

Workshop

Quiz

web.xml

Exercises

Week 2 – Page 183

String

toUpper

*

<url-pattern>

Day 14. Using Filters

       

Week 2 – Page 184

Understanding Filters
javax.servlet.Filter init destroy doFilter doFilter

init

FilterConfig

javax.servlet.Filter

void destroy() void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) void init(FilterConfig filterConfig)

Creating a Simple Filter

ch14_01.java "Leaving ch14_01."

"In ch14_01."

Filter

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch14_01 implements Filter { . .

Week 2 – Page 185

. } Filter doFilter init init destroy

destroy

public class ch14_01 implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { . . . } public void destroy() { } public void init(FilterConfig filterConfig) { } } doFilter web.xml System.out.println doFilter doFilter

FilterChain

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("In ch14_01."); chain.doFilter(request, response); System.out.println("Leaving ch14_01."); } chain.doFilter

chain.doFilter chain.doFilter

Week 2 – Page 186

"In ch14_01." "Leaving ch14_01."

ch14_01.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch14_01 implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("In ch14_01."); chain.doFilter(request, response); System.out.println("Leaving ch14_01."); } public void destroy() { } public void init(FilterConfig filterConfig) { } }

ch14_02.java

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

public class ch14_02 extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter out = response.getWriter();

Week 2 – Page 187

out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Using a Simple Filter"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Using a Simple Filter</H1>"); out.println("The simple filter will send text to the server console.<BR>"); out.println("</BODY>"); out.println("</HTML>"); } } servlet.jar classpath ch14\WEB-INF\classes ch14_02

ch14_01

web.xml web.xml <web-app> <filter> <filter-mapping>

<web-app> <icon> <display-name> <description> <distributable> <context-param> <filter> <filter-mapping> <servlet> <servlet-mapping> <session-config> <mime-mapping> <welcome-file-list> <error-page> <taglib> <resource-ref> <security-constraint> <login-config> <security-role> <env-entry> <ejb-ref> </web-app> <filter>

<filter> <filter-name> <filter-class>

Week 2 – Page 188

</filter> <filter-mapping>

<filter-mapping> <filter-name> <url-pattern> </filter-mapping> <filter>

<filter> <filter-name>Simple Filter</filter-name> <filter-class>ch14_01</filter-class> </filter> <filter-mapping> ch14_02

<filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_02</url-pattern> </filter-mapping> ch14_02 * ch14_02 <servlet-mapping>

<servlet> 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/j2ee/dtds/web-app_2_3.dtd"> <web-app> <filter> <filter-name>Simple Filter</filter-name> <filter-class>ch14_01</filter-class> </filter> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_02</url-pattern> </filter-mapping>

Week 2 – Page 189

<servlet> <servlet-name>ch14_02</servlet-name> <servlet-class>ch14_02</servlet-class> </servlet> <servlet-mapping> <servlet-name>ch14_02</servlet-name> <url-pattern>/ch14_02</url-pattern> </servlet-mapping> </web-app> ch14_02 http://localhost:8080/ch14/ch14_02

Week 2 – Page 190

Filtering JSP Pages

ch14_03.jsp

<HTML> <HEAD> <TITLE>Using a Simple Filter With JSP</TITLE> </HEAD> <BODY> <H1>Using a Simple Filter With JSP</H1> The simple filter will send text to the server console. <BR> </BODY> </HTML> ch14_01 ch14_03.jsp <filter-mapping> web.xml

<?xml version="1.0" encoding="ISO-8859-1"?>

Week 2 – Page 191

<!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN" "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd"> <web-app> <filter> <filter-name>Simple Filter</filter-name> <filter-class>ch14_01</filter-class> </filter> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_02</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_03.jsp</url-pattern> </filter-mapping> <servlet> <servlet-name>ch14_02</servlet-name> <servlet-class>ch14_02</servlet-class> </servlet> <servlet-mapping> <servlet-name>ch14_02</servlet-name> <url-pattern>/ch14_02</url-pattern> </servlet-mapping> </web-app>

http://localhost:8080/ch14/ch14_03.jsp

Week 2 – Page 192

Starting service Tomcat-Apache Apache Tomcat/4.0.3 In ch14_01. Leaving ch14_01.

Creating Filter Chains
doFilter FilterChain chain

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("In ch14_01."); chain.doFilter(request, response); System.out.println("Leaving ch14_01."); }

Week 2 – Page 193

doFilter doFilter FilterChain Filter

"In ch14_04."

"Leaving ch14_04." ch14_01 ch14_04.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch14_04 implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("In ch14_04."); chain.doFilter(request, response); System.out.println("Leaving ch14_04."); } public void destroy() { } public void init(FilterConfig filterConfig) { } } web.xml

ch14_05.jsp

<HTML> <HEAD> <TITLE>Chaining Filters</TITLE> </HEAD> <BODY> <H1>Chaining Filters</H1>

Week 2 – Page 194

Both chained filters will send text to the server console. <BR> </BODY> </HTML> ch14_01 ch14_04 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/j2ee/dtds/web-app_2_3.dtd"> <web-app> <filter> <filter-name>Simple Filter</filter-name> <filter-class>ch14_01</filter-class> </filter> <filter> <filter-name>Chained Filter</filter-name> <filter-class>ch14_04</filter-class> </filter> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_02</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_03.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_05.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Chained Filter</filter-name> <url-pattern>/ch14_05.jsp</url-pattern> </filter-mapping> <servlet> <servlet-name>ch14_02</servlet-name> <servlet-class>ch14_02</servlet-class> </servlet> <servlet-mapping> <servlet-name>ch14_02</servlet-name> <url-pattern>/ch14_02</url-pattern> </servlet-mapping>

Week 2 – Page 195

</web-app> web.xml http://localhost:8080/ch14/ch14_05.jsp ch14_01 ch14_04

Week 2 – Page 196

Starting service Tomcat-Apache Apache Tomcat/4.0.3 In ch14_01. In ch14_04. Leaving ch14_04. Leaving ch14_01. ch14_01 ch14_04 ch14_01 ch14_01 ch14_04 ch14_01 ch14_04 ch14_04

Using Initialization Parameters
web.xml javax.servlet.FilterConfig doFilter javax.servlet.FilterConfig

javax.servlet.FilterConfig

Week 2 – Page 197

java.lang.String getFilterName() java.lang.String getInitParameter (java.lang.String name) String

java.util.Enumeration getInitParameterNames() Enumeration ServletContext getServletContext() String

<init-param>

<param-name>

<param-value>

<init-param> <param-name> <param-value> </init-param> <init-param> <filter>

<filter> <filter-name> <filter-class> <init-param> <param-name> <param-value> </init-param> <init-param> <param-name> <param-value> </init-param> <init-param> <param-name> <param-value> </init-param> </filter> FilterConfig doFilter init

public class ch14_06 implements Filter { private FilterConfig filterConfig = null; . .

Week 2 – Page 198

. public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } } doFilter message ch14_06.java getInitParameter

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch14_06 implements Filter { private FilterConfig filterConfig = null; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { System.out.println("The message is: " + filterConfig.getInitParameter("message")); chain.doFilter(request, response); } public void destroy() { } public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } } message ch14_07.jsp

Hello!

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/j2ee/dtds/web-app_2_3.dtd"> <web-app> <filter> <filter-name>Simple Filter</filter-name>

Week 2 – Page 199

<filter-class>ch14_01</filter-class> </filter> <filter> <filter-name>Chained Filter</filter-name> <filter-class>ch14_04</filter-class> </filter> <filter> <filter-name>Init Parameters Filter</filter-name> <filter-class>ch14_06</filter-class> <init-param> <param-name>message</param-name> <param-value>Hello!</param-value> </init-param> </filter> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_02</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_03.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Simple Filter</filter-name> <url-pattern>/ch14_05.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Chained Filter</filter-name> <url-pattern>/ch14_05.jsp</url-pattern> </filter-mapping> <filter-mapping> <filter-name>Init Parameters Filter</filter-name> <url-pattern>/ch14_07.jsp</url-pattern> </filter-mapping> <servlet> <servlet-name>ch14_02</servlet-name> <servlet-class>ch14_02</servlet-class> </servlet> <servlet-mapping> <servlet-name>ch14_02</servlet-name> <url-pattern>/ch14_02</url-pattern> </servlet-mapping> </web-app> ch14_07.jsp

Week 2 – Page 200

ch14_07.jsp

<HTML> <HEAD> <TITLE>Filters And Initialization Parameters</TITLE> </HEAD> <BODY> <H1>Filters And Initialization Parameters</H1> The initialization parameter's value will be displayed on the server console. <BR> </BODY> </HTML> http://localhost:8080/ch14/ch14_07.jsp

Week 2 – Page 201

Inserting Text Into the Response
getWriter PrintWriter

ch14_08.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch14_08 implements Filter { private FilterConfig filterConfig = null; public void doFilter(ServletRequest request, ServletResponse response,

Week 2 – Page 202

FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("The filter got this message: " + filterConfig.getInitParameter( " message")); } public void destroy() { } public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } }

javax.servlet.http.HttpServletResponseWrapper

javax.servlet.http.HttpServletResponseWrapper

ch14_09.jsp

<HTML> <HEAD> <TITLE>Filters And Initialization Parameters</TITLE> </HEAD> <BODY> <H1>Filters And Initialization Parameters</H1> <BR> </BODY> </HTML>

Week 2 – Page 203

http://localhost:8080/ch14/ch14_09.jsp

Logging

ch14 <Context> server.xml <Context>

server.xml file <Host> <Context> server.xml

Week 2 – Page 204

<Context path="/ch14" docBase="ch14" debug="0" reloadable="true"> <Logger className="org.apache.catalina.logger.FileLogger" directory="logs" prefix="ch14." suffix=".txt" timestamp="true"/> </Context> <Context> ch14 28.txt log FilterConfig .txt ch14 jakarta-tomcat-4.0.3\logs ch14.2002-05-

getServletContext

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { chain.doFilter(request, response); filterConfig.getServletContext().log( . . . ); } request.getRemoteAddr request.getRequestURI doFilter doFilter

ch14_10.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class ch14_10 implements Filter { private FilterConfig filterConfig = null; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {

Week 2 – Page 205

long start = System.currentTimeMillis(); String address = request.getRemoteAddr(); String file = ((HttpServletRequest) request).getRequestURI(); chain.doFilter(request, response); filterConfig.getServletContext().log( "User access! " + " User IP: " + address + " Resource: " + file + " Milliseconds used: " + (System.currentTimeMillis( )start) ); } public void destroy() { } public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } }

ch14_11.jsp

<HTML> <HEAD> <TITLE>Filters And Logging</TITLE> </HEAD> <BODY> <H1>Filters And Logging</H1> This filter writes to a log file. <BR> </BODY> </HTML> http://localhost:8080/ch14/ch14_11.jsp

Week 2 – Page 206

jakarta-tomcat4.0.3\logs\ch14.2002-05-28.txt

2002-05-28 12:06:37 WebappLoader[/ch14]: Deploying class repositories to work directory D: \tomcat\jakarta-tomcat-4.0.3\work\localhost\ch14 2002-05-28 12:06:37 WebappLoader[/ch14]: Reloading checks are enabled for this Context 2002-05-28 12:06:37 StandardManager[/ch14]: Seeding random number generator class java. security.SecureRandom 2002-05-28 12:06:37 StandardManager[/ch14]: Seeding of random number generator has been completed 2002-05-28 12:06:37 StandardWrapper[/ch14:default]: Loading container servlet default 2002-05-28 12:06:37 default: init 2002-05-28 12:06:37 StandardWrapper[/ch14:invoker]: Loading container servlet invoker 2002-05-28 12:06:37 invoker: init 2002-05-28 12:06:37 jsp: init 2002-05-28 12:06:46 jsp: init 2002-05-28 12:06:46 User access! User IP: 127.0.0.1 Resource: /ch14/ch14_11.jsp M illiseconds used: 100

Week 2 – Page 207

/ch14/ch14_11.jsp

Using Filters for User Authentication

password opensesame doFilter

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String password = ((HttpServletRequest) request).getParameter("password"); if(password.equals("opensesame")) { chain.doFilter(request, response); } else { . . . } }

ch14_12.java

import java.io.*; import javax.servlet.*; import javax.servlet.http.*;

Week 2 – Page 208

public class ch14_12 implements Filter { private FilterConfig filterConfig = null; public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { String password = ((HttpServletRequest) request).getParameter("password"); if(password.equals("opensesame")) { chain.doFilter(request, response); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Incorrect Password"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Incorrect Password</H1>"); out.println("Sorry, that password was incorrect."); out.println("</BODY>"); out.println("</HTML>"); } } public void destroy() { } public void init(FilterConfig filterConfig) { this.filterConfig = filterConfig; } } ch14_13.html

ch14_13.html

<HTML> <HEAD> <TITLE>Using Passwords and Filters</TITLE> </HEAD> <BODY> <H1>Using Passwords and Filters</H1> <FORM ACTION="ch14_14.jsp" METHOD="POST"> Please enter your password: <INPUT TYPE="PASSWORD" NAME="password">

Week 2 – Page 209

<BR> <INPUT TYPE="SUBMIT" VALUE="Submit"> </FORM> </BODY> <HTML>

ch14_14.jsp

ch14_14.jsp

<HTML> <HEAD> <TITLE>Filters And User Authentication</TITLE> </HEAD> <BODY> <H1>Filters And User Authentication</H1> Congratulations, you're in! <BR> </BODY> </HTML>

http://localhost:8080/ch14/ch14_13.html

Week 2 – Page 210

ch14_14.jsp

Week 2 – Page 211

Restricting Access

Date

Calendar

ch14_15.java

import import import import

java.io.*; java.util.*; javax.servlet.*; javax.servlet.http.*;

Week 2 – Page 212

public class ch14_15 implements Filter { public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { GregorianCalendar calendar = new GregorianCalendar(); Date date1 = new Date(); calendar.setTime(date1); int hour = calendar.get(Calendar.HOUR_OF_DAY); if(hour < 9 || hour > 17) { chain.doFilter(request, response); } else { response.setContentType("text/html"); PrintWriter out = response.getWriter(); out.println("<HTML>"); out.println("<HEAD>"); out.println("<TITLE>"); out.println("Get Back to Work!"); out.println("</TITLE>"); out.println("</HEAD>"); out.println("<BODY>"); out.println("<H1>Get Back to Work!</H1>"); out.println("Sorry, that resource is not available now."); out.println("</BODY>"); out.println("</HTML>"); } } public void destroy() { } public void init(FilterConfig filterConfig) { } }

ch14_06.jsp ch14_16.jsp

<HTML> <HEAD> <TITLE>Using Filters to Restrict Access</TITLE> </HEAD> <BODY> <H1>Using Filters to Restrict Access</H1> Congratulations, you're in! <BR>

Week 2 – Page 213

</BODY> </HTML>

http://localhost:8080/ch14/ch14_16.jsp

Summary
web.xml

System.out.println

web.xml

Week 2 – Page 214

Q&A

Week 2 – Page 215

Workshop

Quiz
Filter

web.xml

Exercises

String toUpper

request.getHeader("User-Agent")

Week 2 – Page 216


				
DOCUMENT INFO
Shared By:
Categories:
Stats:
views:42
posted:10/8/2009
language:English
pages:216