IfTag.java, IfConditionTag.java, IfThenTag.java, and IfElseTag.java, Custom tags that make use of tag nesting
IfTag.java
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;
/** A tag that acts like an if/then/else.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class IfTag extends TagSupport {
private boolean condition;
private boolean hasCondition = false;
public void setCondition(boolean condition) {
this.condition = condition;
hasCondition = true;
}
public boolean getCondition() {
return(condition);
}
public void setHasCondition(boolean flag) {
this.hasCondition = flag;
}
/** Has the condition field been explicitly set? */
public boolean hasCondition() {
return(hasCondition);
}
public int doStartTag() {
return(EVAL_BODY_INCLUDE);
}
}
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;
/** The condition part of an if tag.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class IfConditionTag extends BodyTagSupport {
public int doStartTag() throws JspTagException {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (parent == null) {
throw new JspTagException("condition not inside if");
}
return(EVAL_BODY_TAG);
}
public int doAfterBody() {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
String bodyString = getBodyContent().getString();
if (bodyString.trim().equals("true")) {
parent.setCondition(true);
} else {
parent.setCondition(false);
}
return(SKIP_BODY);
}
}
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;
/** The else part of an if tag.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class IfElseTag extends BodyTagSupport {
public int doStartTag() throws JspTagException {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (parent == null) {
throw new JspTagException("else not inside if");
} else if (!parent.hasCondition()) {
String warning =
"condition tag must come before else tag";
throw new JspTagException(warning);
}
return(EVAL_BODY_TAG);
}
public int doAfterBody() {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (!parent.getCondition()) {
try {
BodyContent body = getBodyContent();
JspWriter out = body.getEnclosingWriter();
out.print(body.getString());
} catch(IOException ioe) {
System.out.println("Error in IfElseTag: " + ioe);
}
}
return(SKIP_BODY);
}
}
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import javax.servlet.*;
/** The then part of an if tag.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class IfThenTag extends BodyTagSupport {
public int doStartTag() throws JspTagException {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (parent == null) {
throw new JspTagException("then not inside if");
} else if (!parent.hasCondition()) {
String warning =
"condition tag must come before then tag";
throw new JspTagException(warning);
}
return(EVAL_BODY_TAG);
}
public int doAfterBody() {
IfTag parent =
(IfTag)findAncestorWithClass(this, IfTag.class);
if (parent.getCondition()) {
try {
BodyContent body = getBodyContent();
JspWriter out = body.getEnclosingWriter();
out.print(body.getString());
} catch(IOException ioe) {
System.out.println("Error in IfThenTag: " + ioe);
}
}
return(SKIP_BODY);
}
}
Aug 28
IfTag.java, IfConditionTag.java, IfThenTag.java, and IfElseTag.java, Custom tags that make use of tag nesting
Aug 28
FilterExample.jsp Page that uses the FilterTag custom tag
FilterExample.jsp Page that uses the FilterTag custom tag
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of FilterTag tag.
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>HTML Logical Character Styles</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H1>HTML Logical Character Styles</H1>
Physical character styles (B, I, etc.) are rendered consistently
in different browsers. Logical character styles, however,
may be rendered differently by different browsers.
Here's how your browser
(<%= request.getHeader("User-Agent") %>)
renders the HTML 4.0 logical character styles:
<P>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<TABLE BORDER=1 ALIGN="CENTER">
<TR CLASS="COLORED"><TH>Example<TH>Result
<TR>
<TD><PRE><cwp:filter>
<EM>Some emphasized text.</EM><BR>
<STRONG>Some strongly emphasized text.</STRONG><BR>
<CODE>Some code.</CODE><BR>
<SAMP>Some sample text.</SAMP><BR>
<KBD>Some keyboard text.</KBD><BR>
<DFN>A term being defined.</DFN><BR>
<VAR>A variable.</VAR><BR>
<CITE>A citation or reference.</CITE>
</cwp:filter></PRE>
<TD>
<EM>Some emphasized text.</EM><BR>
<STRONG>Some strongly emphasized text.</STRONG><BR>
<CODE>Some code.</CODE><BR>
<SAMP>Some sample text.</SAMP><BR>
<KBD>Some keyboard text.</KBD><BR>
<DFN>A term being defined.</DFN><BR>
<VAR>A variable.</VAR><BR>
<CITE>A citation or reference.</CITE>
</TABLE>
</BODY>
</HTML>
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
import cwp.*;
/** A tag that replaces <, >, ", and & with their HTML
* character entities (<, >, ", and &).
* After filtering, arbitrary strings can be placed
* in either the page body or in HTML attributes.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class FilterTag extends BodyTagSupport {
public int doAfterBody() {
BodyContent body = getBodyContent();
String filteredBody =
ServletUtilities.filter(body.getString());
try {
JspWriter out = body.getEnclosingWriter();
out.print(filteredBody);
} catch(IOException ioe) {
System.out.println("Error in FilterTag: " + ioe);
}
// SKIP_BODY means we're done. If we wanted to evaluate
// and handle the body again, we'd return EVAL_BODY_TAG.
return(SKIP_BODY);
}
}
Aug 28
Demonstrates using a TexturePaint to fill an shape with a tiled image
^^^^^^^^^^^^^^^^^
TiledImages.java Demonstrates using a TexturePaint to fill an shape with a tiled image. Uses the following class and images:
* ImageUtilities.java Simplifies creating a BufferedImage from an image file.
~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;
import java.awt.image.*;
/** An example of using TexturePaint to fill objects with tiled
* images. Uses the getBufferedImage method of ImageUtilities
* to load an Image from a file and turn that into a
* BufferedImage.
*
****************
public class TiledImages extends JPanel {
private String dir = System.getProperty("user.dir");
private String imageFile1 = dir + "/images/marty.jpg";
private TexturePaint imagePaint1;
private Rectangle imageRect;
private String imageFile2 = dir + "/images/bluedrop.gif";
private TexturePaint imagePaint2;
private int[] xPoints = { 30, 700, 400 };
private int[] yPoints = { 30, 30, 600 };
private Polygon imageTriangle =
new Polygon(xPoints, yPoints, 3);
public TiledImages() {
BufferedImage image =
ImageUtilities.getBufferedImage(imageFile1, this);
imageRect = new Rectangle(235, 70, image.getWidth(),
image.getHeight());
imagePaint1 = new TexturePaint(image, imageRect);
image = ImageUtilities.getBufferedImage(imageFile2, this);
imagePaint2 =
new TexturePaint(image, new Rectangle(0, 0, 32, 32));
}
public void paintComponent(Graphics g) {
super.paintComponent(g);
Graphics2D g2d = (Graphics2D)g;
g2d.setPaint(imagePaint2);
g2d.fill(imageTriangle);
g2d.setPaint(Color.blue);
g2d.setStroke(new BasicStroke(5));
g2d.draw(imageTriangle);
g2d.setPaint(imagePaint1);
g2d.fill(imageRect);
g2d.setPaint(Color.black);
g2d.draw(imageRect);
}
public static void main(String[] args) {
WindowUtilities.openInJFrame(new TiledImages(), 750, 650);
}
}
>>>>>>>>>>>>>>
ImageUtilities.java Simplifies creating a BufferedImage from an image file.
>>>>>>>>>>>>>>>
import java.awt.*;
import java.awt.image.*;
/** A class that simplifies a few common image operations, in
* particular, creating a BufferedImage from an image file and
* using MediaTracker to wait until an image or several images
* are done loading.
*
********************
public class ImageUtilities {
/** Create Image from a file, then turn that into a
* BufferedImage.
*/
public static BufferedImage getBufferedImage(String imageFile,
Component c) {
Image image = c.getToolkit().getImage(imageFile);
waitForImage(image, c);
BufferedImage bufferedImage =
new BufferedImage(image.getWidth(c), image.getHeight(c),
BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = bufferedImage.createGraphics();
g2d.drawImage(image, 0, 0, c);
return(bufferedImage);
}
/** Take an Image associated with a file, and wait until it is
* done loading (just a simple application of MediaTracker).
* If you are loading multiple images, don't use this
* consecutive times; instead, use the version that takes
* an array of images.
*/
public static boolean waitForImage(Image image, Component c) {
MediaTracker tracker = new MediaTracker(c);
tracker.addImage(image, 0);
try {
tracker.waitForAll();
} catch(InterruptedException ie) {}
return(!tracker.isErrorAny());
}
/** Take some Images associated with files, and wait until they
* are done loading (just a simple application of
* MediaTracker).
*/
public static boolean waitForImages(Image[] images, Component c) {
MediaTracker tracker = new MediaTracker(c);
for(int i=0; i
Aug 28
Draws a filled ellipse
import javax.swing.*; // For JPanel, etc.
import java.awt.*; // For Graphics, etc.
import java.awt.geom.*; // For Ellipse2D, etc.
/** An example of drawing/filling shapes with Java 2D in
* Java 1.2 and later.
*
**************************
public class ShapeExample extends JPanel {
private Ellipse2D.Double circle =
new Ellipse2D.Double(10, 10, 350, 350);
private Rectangle2D.Double square =
new Rectangle2D.Double(10, 10, 350, 350);
public void paintComponent(Graphics g) {
clear(g);
Graphics2D g2d = (Graphics2D)g;
g2d.fill(circle);
g2d.draw(square);
}
// super.paintComponent clears off screen pixmap,
// since we're using double buffering by default.
protected void clear(Graphics g) {
super.paintComponent(g);
}
protected Ellipse2D.Double getCircle() {
return(circle);
}
public static void main(String[] args) {
WindowUtilities.openInJFrame(new ShapeExample(), 380, 400);
}
}
Aug 28
JavaTextField.java
import java.applet.Applet;
import java.awt.*;
/** Lets the user enter the name of any
* good programming language. Or does it?
*
*********************
public class JavaTextField extends Applet {
public void init() {
setFont(new Font("Serif", Font.BOLD, 14));
setLayout(new GridLayout(2, 1));
add(new Label("Enter a Good Programming Language",
Label.CENTER));
LanguageField langField = new LanguageField();
Font langFont = new Font("SansSerif", Font.BOLD, 18);
langField.setFont(langFont);
add(langField);
}
}
Aug 28
Applet that uses processXxx methods to print detailed reports on mouse events. Illustrates low-level alternative to handling events with listeners.
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
/** Prints non-detailed reports of mouse events.
* Uses the low-level processXxxEvent methods instead
* of the usual event listeners.
*
*****************
public class MouseReporter extends Applet {
public void init() {
setBackground(Color.blue); // So you can see applet in page
enableEvents(AWTEvent.MOUSE_EVENT_MASK |
AWTEvent.MOUSE_MOTION_EVENT_MASK);
}
public void processMouseEvent(MouseEvent event) {
System.out.println("Mouse enter/exit or click at (" +
event.getX() + "," +
event.getY() + ").");
// In case there are MouseListeners attached:
super.processMouseEvent(event);
}
public void processMouseMotionEvent(MouseEvent event) {
System.out.println("Mouse move/drag at (" +
event.getX() + "," +
event.getY() + ").");
// In case there are MouseMotionListeners attached:
super.processMouseMotionEvent(event);
}
}
Aug 28
HeadingExample.jsp Page that uses the HeadingTag custom tag
HeadingExample.jsp Page that uses the HeadingTag custom tag
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of HeadingTag tag.
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Some Tag-Generated Headings</TITLE>
</HEAD>
<BODY>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<cwp:heading bgColor="#C0C0C0">
Default Heading
</cwp:heading>
<P>
<cwp:heading bgColor="BLACK" color="WHITE">
White on Black Heading
</cwp:heading>
<P>
<cwp:heading bgColor="#EF8429" fontSize="60" border="5">
Large Bordered Heading
</cwp:heading>
<P>
<cwp:heading bgColor="CYAN" width="100%">
Heading with Full-Width Background
</cwp:heading>
<P>
<cwp:heading bgColor="CYAN" fontSize="60"
fontList="Brush Script MT, Times, serif">
Heading with Non-Standard Font
</cwp:heading>
</BODY>
</HTML>
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/** Generates an HTML heading with the specified background
* color, foreground color, alignment, font, and font size.
* You can also turn on a border around it, which normally
* just barely encloses the heading, but which can also
* stretch wider. All attributes except the background
* color are optional.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class HeadingTag extends TagSupport {
private String bgColor; // The one required attribute
private String color = null;
private String align="CENTER";
private String fontSize="36";
private String fontList="Arial, Helvetica, sans-serif";
private String border="0";
private String width=null;
public void setBgColor(String bgColor) {
this.bgColor = bgColor;
}
public void setColor(String color) {
this.color = color;
}
public void setAlign(String align) {
this.align = align;
}
public void setFontSize(String fontSize) {
this.fontSize = fontSize;
}
public void setFontList(String fontList) {
this.fontList = fontList;
}
public void setBorder(String border) {
this.border = border;
}
public void setWidth(String width) {
this.width = width;
}
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print("<TABLE BORDER=" + border +
" BGCOLOR=\"" + bgColor + "\"" +
" ALIGN=\"" + align + "\"");
if (width != null) {
out.print(" WIDTH=\"" + width + "\"");
}
out.print("><TR><TH>");
out.print("<SPAN STYLE=\"" +
"font-size: " + fontSize + "px; " +
"font-family: " + fontList + "; ");
if (color != null) {
out.println("color: " + color + ";");
}
out.print("\"> "); // End of <SPAN ...>
} catch(IOException ioe) {
System.out.println("Error in HeadingTag: " + ioe);
}
return(EVAL_BODY_INCLUDE); // Include tag body
}
public int doEndTag() {
try {
JspWriter out = pageContext.getOut();
out.print("</SPAN></TABLE>");
} catch(IOException ioe) {
System.out.println("Error in HeadingTag: " + ioe);
}
return(EVAL_PAGE); // Continue with rest of JSP page
}
}
Aug 28
PrimeExample.jsp Page that uses the PrimeTag custom tag
PrimeExample.jsp Page that uses the PrimeTag custom tag
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of PrimeTag tag.
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Some N-Digit Primes</TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H1>Some N-Digit Primes</H1>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<UL>
<LI>20-digit: <cwp:prime length="20" />
<LI>40-digit: <cwp:prime length="40" />
<LI>80-digit: <cwp:prime length="80" />
<LI>Default (50-digit): <cwp:prime />
</UL>
</BODY>
</HTML>
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/** Generates an N-digit random prime (default N = 50).
* Extends SimplePrimeTag, adding a length attribute
* to set the size of the prime. The doStartTag
* method of the parent class uses the len field
* to determine the approximate length of the prime.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class PrimeTag extends SimplePrimeTag {
public void setLength(String length) {
try {
len = Integer.parseInt(length);
} catch(NumberFormatException nfe) {
len = 50;
}
}
}
Aug 28
SimplePrimeExample.jsp Page that uses the SimplePrimeTag custom tag
SimplePrimeExample.jsp Page that uses the SimplePrimeTag custom tag <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"> <!-- Illustration of SimplePrimeTag tag. Taken from Core Web Programming Java 2 Edition from Prentice Hall and Sun Microsystems Press, . May be freely used or adapted. --> <HTML> <HEAD> <TITLE>Some 50-Digit Primes</TITLE> <LINK REL=STYLESHEET HREF="JSP-Styles.css" TYPE="text/css"> </HEAD> <BODY> <H1>Some 50-Digit Primes</H1> <%@ taglib uri="cwp-taglib.tld" prefix="cwp" %> <UL> <LI><cwp:simplePrime /> <LI><cwp:simplePrime /> <LI><cwp:simplePrime /> <LI><cwp:simplePrime /> </UL> </BODY> </HTML>
Aug 28
SimpleExample.jsp Page that uses the ExampleTag custom tag.
SimpleExample.jsp Page that uses the ExampleTag custom tag.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!--
Illustration of very simple JSP custom tag.
Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<TITLE><cwp:example /></TITLE>
<LINK REL=STYLESHEET
HREF="JSP-Styles.css"
TYPE="text/css">
</HEAD>
<BODY>
<H1><cwp:example /></H1>
<cwp:example />
</BODY>
</HTML>
ExampleTag
package cwp.tags;
import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;
/** Very simple JSP tag that just inserts a string
* ("Custom tag example...") into the output.
* The actual name of the tag is not defined here;
* that is given by the Tag Library Descriptor (TLD)
* file that is referenced by the taglib directive
* in the JSP file.
* <P>
* Taken from Core Web Programming Java 2 Edition
* from Prentice Hall and Sun Microsystems Press,
* .
* May be freely used or adapted.
*/
public class ExampleTag extends TagSupport {
public int doStartTag() {
try {
JspWriter out = pageContext.getOut();
out.print("Custom tag example " +
"(cwp.tags.ExampleTag)");
} catch(IOException ioe) {
System.out.println("Error in ExampleTag: " + ioe);
}
return(SKIP_BODY);
}
}
