SaleEntry1.jsp Page that uses the SaleEntry bean, using explicit Java code to read request parameters and assign them to bean properties.

SaleEntry1.jsp Page that uses the SaleEntry bean, using explicit Java code to read request parameters and assign them to bean properties.

 

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Example of using jsp:setProperty with an explicit value
supplied to the "value" attribute. See SaleEntry2.jsp
and SaleEntry3.jsp for alternatives. 

Taken from Core Web Programming Java 2 Edition
from Prentice Hall and Sun Microsystems Press,
.
May be freely used or adapted.
-->
<HTML>
<HEAD>
<TITLE>Using jsp:setProperty</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>

<BODY>
<TABLE BORDER=5 ALIGN="CENTER">
  <TR><TH CLASS="TITLE">
      Using jsp:setProperty</TABLE>
<jsp:useBean id="entry" class="cwp.SaleEntry" />
<jsp:setProperty 
    name="entry" 
    property="itemID"
    value='<%= request.getParameter("itemID") %>' />
<%
int numItemsOrdered = 1;
try {
  numItemsOrdered = 
    Integer.parseInt(request.getParameter("numItems"));
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty 
    name="entry" 
    property="numItems"
    value="<%= numItemsOrdered %>" />
<% 
double discountCode = 1.0;
try {
  String discountString = 
    request.getParameter("discountCode");
  // Double.parseDouble not available in JDK 1.1.
  discountCode = 
    Double.valueOf(discountString).doubleValue();
} catch(NumberFormatException nfe) {}
%>
<jsp:setProperty 
    name="entry" 
    property="discountCode"
    value="<%= discountCode %>" />
<BR>
<TABLE ALIGN="CENTER" BORDER=1>
<TR CLASS="COLORED">
  <TH>Item ID<TH>Unit Price<TH>Number Ordered<TH>Total Price
<TR ALIGN="RIGHT">
  <TD><jsp:getProperty name="entry" property="itemID" />
  <TD>$<jsp:getProperty name="entry" property="itemCost" />
  <TD><jsp:getProperty name="entry" property="numItems" />
  <TD>$<jsp:getProperty name="entry" property="totalCost" />
</TABLE>       
</BODY>
</HTML>


SaleEntry.Java //sale entry bean

package cwp;

/** Simple bean to illustrate the various forms
 *  of jsp:setProperty.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class SaleEntry {
  private String itemID = "unknown";
  private double discountCode = 1.0;
  private int numItems = 0;

  public String getItemID() {
    return(itemID);
  }

  public void setItemID(String itemID) {
    if (itemID != null) {
      this.itemID = itemID;
    } else {
      this.itemID = "unknown";
    }
  }

  public double getDiscountCode() {
    return(discountCode);
  }

  public void setDiscountCode(double discountCode) {
    this.discountCode = discountCode;
  }

  public int getNumItems() {
    return(numItems);
  }

  public void setNumItems(int numItems) {
    this.numItems = numItems;
  }

  // In real life, replace this with database lookup.

  public double getItemCost() {
    double cost;
    if (itemID.equals("a1234")) {
      cost = 12.99*getDiscountCode();
    } else {
      cost = -9999;
    }
    return(roundToPennies(cost));
  }

  private double roundToPennies(double cost) {
    return(Math.floor(cost*100)/100.0);
  }

  public double getTotalCost() {
    return(getItemCost() * getNumItems());
  }
}

StringBean.jsp Page that manipulates the StringBean bean with both jsp:useBean (i.e., XML-style) syntax

StringBean.jsp Page that manipulates the StringBean bean with both jsp:useBean (i.e., XML-style) syntax


package cwp;

/** Simple bean to illustrate sharing beans through
 *  use of the scope attribute of jsp:useBean.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class AccessCountBean {
  private String firstPage;
  private int accessCount = 1;

  public String getFirstPage() {
    return(firstPage);
  }

  public void setFirstPage(String firstPage) {
    this.firstPage = firstPage;
  }

  public int getAccessCount() {
    return(accessCount++);
  }
}

RepeatTag.java Custom tag that repeats the tag body a specified number of times

RepeatTag.java Custom tag that repeats the tag body a specified number of times

package cwp.tags;

import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
import java.io.*;

/** A tag that repeats the body the specified
 *  number of times.
 *  <P>
 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
 *  .
 *  May be freely used or adapted.
 */

public class RepeatTag extends BodyTagSupport {
  private int reps;

  public void setReps(String repeats) {
    try {
      reps = Integer.parseInt(repeats);
    } catch(NumberFormatException nfe) {
      reps = 1;
    }
  }

  public int doAfterBody() {
    if (reps-- >= 1) {
      BodyContent body = getBodyContent();
      try {
        JspWriter out = body.getEnclosingWriter();
        out.println(body.getString());
        body.clearBody(); // Clear for next evaluation
      } catch(IOException ioe) {
        System.out.println("Error in RepeatTag: " + ioe);
      }
      return(EVAL_BODY_TAG);
    } else {
      return(SKIP_BODY);
    }
  }
}

RepeatExample.jsp


<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<!-- 
Illustration of RepeatTag 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 40-Digit Primes</TITLE>
<LINK REL=STYLESHEET
      HREF="JSP-Styles.css"
      TYPE="text/css">
</HEAD>
<BODY>
<H1>Some 40-Digit Primes</H1>
Each entry in the following list is the first prime number 
higher than a randomly selected 40-digit number.
<%@ taglib uri="cwp-taglib.tld" prefix="cwp" %>
<OL>
<!-- Repeats N times. A null reps value means repeat once. -->
<cwp:repeat reps='<%= request.getParameter("repeats") %>'>
  <LI><cwp:prime length="40" />
</cwp:repeat>
</OL>
</BODY>
</HTML>

An applet that reads arrays of strings packaged inside a QueryCollection and places them in a scrolling TextArea.

import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;

/** Applet reads arrays of strings packaged inside
 *  a QueryCollection and places them in a scrolling
 *  TextArea. The QueryCollection obtains the strings
 *  by means of a serialized object input stream
 *  connected to the QueryGenerator servlet.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,
  *  May be freely used or adapted.
 */

public class ShowQueries extends Applet
                         implements ActionListener, Runnable {
  private TextArea queryArea;
  private Button startButton, stopButton, clearButton;
  private QueryCollection currentQueries;
  private QueryCollection nextQueries;
  private boolean isRunning = false;
  private String address =
    "/servlet/cwp.QueryGenerator";
  private URL currentPage;
  
  public void init() {
    setBackground(Color.white);
    setLayout(new BorderLayout());
    queryArea = new TextArea();
    queryArea.setFont(new Font("Serif", Font.PLAIN, 14));
    add(queryArea, BorderLayout.CENTER);
    Panel buttonPanel = new Panel();
    Font buttonFont = new Font("SansSerif", Font.BOLD, 16);
    startButton = new Button("Start");
    startButton.setFont(buttonFont);
    startButton.addActionListener(this);
    buttonPanel.add(startButton);
    stopButton = new Button("Stop");
    stopButton.setFont(buttonFont);
    stopButton.addActionListener(this);
    buttonPanel.add(stopButton);
    clearButton = new Button("Clear TextArea");
    clearButton.setFont(buttonFont);
    clearButton.addActionListener(this);
    buttonPanel.add(clearButton);
    add(buttonPanel, BorderLayout.SOUTH);
    currentPage = getCodeBase();
    // Request a set of sample queries. They
    // are loaded in a background thread, and
    // the applet checks to see if they have finished
    // loading before trying to extract the strings.
    currentQueries = new QueryCollection(address, currentPage);
    nextQueries = new QueryCollection(address, currentPage);
  }

  /** If you press the "Start" button, the system
   *  starts a background thread that displays
   *  the queries in the TextArea. Pressing "Stop"
   *  halts the process, and "Clear" empties the
   *  TextArea.
   */
 
  public void actionPerformed(ActionEvent event) {
    if (event.getSource() == startButton) {
      if (!isRunning) {
        Thread queryDisplayer = new Thread(this);
        isRunning = true;
        queryArea.setText("");
        queryDisplayer.start();
        showStatus("Started display thread...");
      } else {
        showStatus("Display thread already running...");
      }
    } else if (event.getSource() == stopButton) {
      isRunning = false;
      showStatus("Stopped display thread...");
    } else if (event.getSource() == clearButton) {
      queryArea.setText("");
    }
  }

  /** The background thread takes the currentQueries
   *  object and every half-second places one of the queries
   *  the object holds into the bottom of the TextArea. When
   *  all of the queries have been shown, the thread copies
   *  the value of the nextQueries object into
   *  currentQueries, sends a new request to the server
   *  in order to repopulate nextQueries, and repeats
   *  the process.
   */

  public void run() {
    while(isRunning) {
      showQueries(currentQueries);
      currentQueries = nextQueries;
      nextQueries = new QueryCollection(address, currentPage);
    }
  }

  private void showQueries(QueryCollection queryEntry) {
    // If request has been sent to server but the result
    // isn't back yet, poll every second. This should
    // happen rarely but is possible with a slow network
    // connection or an overloaded server.
    while(!queryEntry.isDone()) {
      showStatus("Waiting for data from server...");
      pause(1);
    }
    showStatus("Received data from server...");
    String[] queries = queryEntry.getQueries();
    String linefeed = "\n";
    // Put a string into TextArea every half-second.
    for(int i=0; i
                                

FilterTag.java Custom tag that modifies the tag body

FilterTag.java Custom tag that modifies the tag body

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);
  }
}

An applet that searches multiple search engines, displaying the results in side-by-side frame cells.

Using Applets as Front Ends to Server-Side Programs
**************************************************
SearchApplet.java An applet that searches multiple search engines,
 displaying the results in side-by-side frame cells. Uses the following files: 
SearchSpec.javaParallelSearches.htmlSearchAppletFrame.htmlGoogleResultsFrame.htmlInfoseekResultsFrame.htmlLycosResultsFrame.html
***************************************************
//
import java.applet.Applet;
import java.awt.*;
import java.awt.event.*;
import java.net.*;
//

/** An applet that reads a value from a TextField,
 *  then uses it to build three distinct URLs with embedded
 *  GET data: one each for Google, Infoseek, and Lycos.
 *  The browser is directed to retrieve each of these
 *  URLs, displaying them in side-by-side frame cells.
 *  Note that standard HTML forms cannot automatically
 *  perform multiple submissions in this manner.
 *  


 *  Taken from Core Web Programming Java 2 Edition
 *  from Prentice Hall and Sun Microsystems Press,

 *  May be freely used or adapted.
 */

public class SearchApplet extends Applet
                          implements ActionListener {
  private TextField queryField;
  private Button submitButton;

  public void init() {
    setBackground(Color.white);
    setFont(new Font("Serif", Font.BOLD, 18));
    add(new Label("Search String:"));
    queryField = new TextField(40);
    queryField.addActionListener(this);
    add(queryField);
    submitButton = new Button("Send to Search Engines");
    submitButton.addActionListener(this);
    add(submitButton);
  }

  /** Submit data when button is pressed or
   *  user presses Return in the TextField.
   */
  
  public void actionPerformed(ActionEvent event) {
    String query = URLEncoder.encode(queryField.getText());
    SearchSpec[] commonSpecs = SearchSpec.getCommonSpecs();
    // Omitting HotBot (last entry), as they use JavaScript to
    // pop result to top-level frame. Thus the length-1 below.
    for(int i=0; i
                                

RotationExample.java An example of translating and rotating the coordinate system prior to drawing

import java.awt.*;

/** An example of translating and rotating the coordinate
 *  system before each drawing.
 *
 *******************************

public class RotationExample extends StrokeThicknessExample {
  private Color[] colors = { Color.white, Color.black };

  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
    drawThickCircleOutline(g2d);
    // Move the origin to the center of the circle.
    g2d.translate(185.0, 185.0);
    for (int i=0; i<16; i++) {
      // Rotate the coordinate system around current
      // origin, which is at the center of the circle.
      g2d.rotate(Math.PI/8.0);
      g2d.setPaint(colors[i%2]);
      g2d.drawString("Java", 0, 0);
    }
  }

public static void main(String[] args) {
    WindowUtilities.openInJFrame(new RotationExample(),
                                 380, 400);
  }
}

Demonstrates setting the pen width (in pixels) using a BasicStroke prior to drawing. Inherits from FontExample.java.

StrokeThicknessExample.java 
>>>>>>>>>>>>>>>>>>>>>>>>>>>
import java.awt.*;

/** An example of controlling the Stroke (pen) widths when
 *  drawing.
 *
 ******************
 */

public class StrokeThicknessExample extends FontExample {
  public void paintComponent(Graphics g) {
    clear(g);
    Graphics2D g2d = (Graphics2D)g;
    drawGradientCircle(g2d);
    drawBigString(g2d);
    drawThickCircleOutline(g2d);
  }

  protected void drawThickCircleOutline(Graphics2D g2d) {
    g2d.setPaint(Color.blue);
    g2d.setStroke(new BasicStroke(8)); // 8-pixel wide pen
    g2d.draw(getCircle());
  }

  public static void main(String[] args) {
    WindowUtilities.openInJFrame(new StrokeThicknessExample(),
                                 380, 400);
  }
}

ListFonts.java Lists all local fonts available for graphical drawing.

ListFonts.java Lists all local fonts available for graphical drawing. 
***********************
import java.awt.*;

/** Lists the names of all available fonts. 
 *
 ******************

public class ListFonts {
  public static void main(String[] args) {
    GraphicsEnvironment env =
      GraphicsEnvironment.getLocalGraphicsEnvironment();
    String[] fontNames = env.getAvailableFontFamilyNames();
    System.out.println("Available Fonts:");
    for(int i=0; i>>>>>>>>>>>>>>>>>>>>>>>

Illustrates the effect of different transparency

~~~~~~~~~~~~~~~~~~~
TransparencyExample.java Illustrates the effect of different transparency (alpha) values when drawing a shape.
~~~~~~~~~~~~~~~~~~~
import javax.swing.*;
import java.awt.*;
import java.awt.geom.*;

/** An illustration of the use of AlphaComposite to make
 *  partially transparent drawings.
 *
 **********************************

public class TransparencyExample extends JPanel {
  private static int gap=10, width=60, offset=20,
                     deltaX=gap+width+offset;
  private Rectangle
    blueSquare = new Rectangle(gap+offset, gap+offset, width,
                               width),
    redSquare = new Rectangle(gap, gap, width, width);

  private AlphaComposite makeComposite(float alpha) {
    int type = AlphaComposite.SRC_OVER;
    return(AlphaComposite.getInstance(type, alpha));
  }

  private void drawSquares(Graphics2D g2d, float alpha) {
    Composite originalComposite = g2d.getComposite();
    g2d.setPaint(Color.blue);
    g2d.fill(blueSquare);
    g2d.setComposite(makeComposite(alpha));
    g2d.setPaint(Color.red);
    g2d.fill(redSquare);
    g2d.setComposite(originalComposite);
  }

  public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D)g;
    for(int i=0; i<11; i++) {
      drawSquares(g2d, i*0.1F);
      g2d.translate(deltaX, 0);
    }
  }

  public static void main(String[] args) {
    String title = "Transparency example: alpha of the top " +
                   "(red) square ranges from 0.0 at the left " +
                   "to 1.0 at the right. Bottom (blue) square " + 
                   "is opaque.";
    WindowUtilities.openInJFrame(new TransparencyExample(),
                                 11*deltaX + 2*gap,
                                 deltaX + 3*gap,
                                 title, Color.lightGray);
  }
}
>>>>>>>>>>>>>>>>>>