Chapter 10: Using Java Server Pages to Generate Programs

Summary

JSP (Java Server Pages) is a technology for producing Web pages. In this book JSP is used to generate Java programs from templates. Templates have embedded Java code to determine the dynamic parts of the generated output. JSP provides a convenient way to build program generators and at the same time make them available over the Internet. The JSP engine itself is an example program generator, which translates JSP files to Java programs.



Chapter 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13

Example 10-1: A Servlet Creating a Simple HTML Page
Example 10-9: newchart.jsp File for Creating a Custom Chart Applet
Example 10-10: MyChart.java (with Orientation Set to Vertical)
Example 10-13: Play Domain Program Generator Using JSP

Example 10-1: A Servlet Creating a Simple HTML Page

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

public class Example10 extends HttpServlet
{
    /** Handle the GET method by building a simple Web page. */
    public void doGet (HttpServletRequest request,
                       HttpServletResponse response)
        throws ServletException, IOException {
            PrintWriter out;

            // set content type
            response.setContentType("text/html");

            // write the Web page
            out = response.getWriter();

            out.println("<HTML><HEAD><TITLE>");
            out.println("Example Servlet");
            out.println("</TITLE></HEAD>");
            out.println("<BODY>");
            out.println("<H3>The time is " + new Date() + "</H3>");
            String x = request.getParameter("x");
            if (x==null) {
                out.println("There is no x parameter");
            } else {
                out.println("The x parameter is "+x);
            }
            out.println("</BODY></HTML>");
            out.close();
        }
}

Example 10-9: newchart.jsp File for Creating a Custom Chart Applet

<pre>
<%
	String name = request.getParameter("name");
	String type = request.getParameter("type");
	String orient = request.getParameter("orient");
	String scale = request.getParameter("scale");
	String gap = request.getParameter("gap");
	String border = request.getParameter("border");
	String data = request.getParameter("data");
	String label = request.getParameter("label");
	String datasource = request.getParameter("datasource");
	String labelsource = request.getParameter("labelsource");
	String color1 = request.getParameter("color1");
	String color2 = request.getParameter("color2");
	String color3 = request.getParameter("color3");
	String color4 = request.getParameter("color4");
%>
import java.awt.*;
import java.awt.event.*;
import java.applet.*;

public class <%=name%> extends Applet {
    
    String[] labels = {};
    int[] data = {};
    int maxValue = 0;
  <% if (orient.equals("3")) { %>boolean vertical = true;
    <% } %>
    
    public void init() {
     <% if (orient.equals("3")) { %>
        // set up mouse action to switch graph orientation
        addMouseListener(new MouseAdapter() {
            public void mouseClicked(MouseEvent e) {
                vertical = !vertical;
                repaint();
            }
        });
    <% } %>

    <% if (data.equals("4")) { %>
        // fake data
        int[] fakeData = { 14, 20, 34, 30 };
        data = fakeData;
        maxValue = 35;
    <% } else { %>
        error("Other data sources not yet implemented");
    <% } %>

    <% if (label.equals("2")) { %>   
        // read labels from applet parameters
        labels = new String[data.length];
        for (int j=0; j&lt;labels.length; ++j) {
            labels[j] = getParameter("label"+j);
            if (labels[j]==null || labels[j].equals("")) {
                labels[j] = "?";
            }
        }
    <% } else { %>
        error("Other label sources not yet implemented.");
    <% } %>
    }
    
    public void paint(Graphics g) {
        int w = getSize().width;
        int h = getSize().height;
        
        g.setColor(Color.black);
        g.drawRect(0, 0, w-1, h-1);
    
    <% if (type.equals("1")) { %>
        // Create Bar Chart    
        int gap = <%=gap%>;
        int border = <%=border%>;
        int ndata = data.length;
        if (ndata==0) {
            g.setColor(Color.black);
            g.drawString("No Data Available for Charting", border, h/2);
            return;
        }
    <% if (orient.equals("3")) { %>
        if (vertical) {
    <% }
       if (orient.equals("3") || orient.equals("2")) {
    %>
            // Vertical Bar chart
            int ctop = 0;
            int cbot = h-20;
            int ch = cbot - ctop;
            int cwid = (w-2*border-(ndata-1)*gap)/ndata;
            
            for (int j=0; j&lt;ndata; ++j) {
                if (labels.length>j) {
                    g.setColor(Color.<%=color3%>);
                    g.drawString(labels[j],
                       border+cwid/3+j*(gap+cwid), h-5);
                }
                g.setColor(Color.<%=color1%>);
                int colh = ch*data[j]/maxValue;
                g.fillRect(border+j*(gap+cwid), cbot-colh, cwid, colh);
            }
    <% }
       if (orient.equals("3")) {
    %>
        } else {
    <% }
       if (orient.equals("3") || orient.equals("1")) {
    %>
            // Horizontal Bar Chart
            int rleft = border;
            int rright = w-border;
            int rwid = rright - rleft;
            int rht = (h-2*border-(ndata-1)*gap)/ndata;
            
            for (int j=0; j&lt;ndata; ++j) {
                g.setColor(Color.<%=color2%>);
                int rowwid = rwid*data[j]/maxValue;
                g.fillRect(border, border+j*(gap+rht), rowwid, rht);
                if (labels.length>j) {
                    g.setColor(Color.<%=color4%>);
                    g.drawString(labels[j], border*2,
                        border+j*(gap+rht)+rht*2/3);
                }
            }
    <% }
       if (orient.equals("3")) {
    %>
        }
    <% } %>
    <% } else { %>
        g.setColor(Color.black);
        g.drawString("Chart Style not yet implemented.", border, h/2);
    <% } %>
    }

    public void error(String m) {
        errmess = m;
        System.out.println(m);
        status(m);
    }
}

Example 10-10: MyChart.java (with Orientation Set to Vertical)

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

public class MyChart extends Applet {
    
    String[] labels = {};
    int[] data = {};
    int maxValue = 0;
    
    public void init() {
        // fake data
        int[] fakeData = { 14, 20, 34, 30 };
        data = fakeData;
        maxValue = 35;
    
        // read labels from applet parameters
        labels = new String[data.length];
        for (int j=0; j<labels.length; ++j) {
            labels[j] = getParameter("label"+j);
            if (labels[j]==null || labels[j].equals("")) {
                labels[j] = "?";
            }
        }
    }
    
    public void paint(Graphics g) {
        int w = getSize().width;
        int h = getSize().height;
        
        g.setColor(Color.black);
        g.drawRect(0, 0, w-1, h-1);
    
    
        // Create Bar Chart    
        int gap = 5;
        int border = 10;
        int ndata = data.length;
        if (ndata==0) {
            g.setColor(Color.black);
            g.drawString("No Data Available for Charting", border, h/2);
            return;
        }
    
            // Vertical Bar chart
            int ctop = 0;
            int cbot = h-20;
            int ch = cbot - ctop;
            int cwid = (w-2*border-(ndata-1)*gap)/ndata;
            
            for (int j=0; j<ndata; ++j) {
                if (labels.length>j) {
                    g.setColor(Color.black);
                    g.drawString(labels[j],
                           border+cwid/3+j*(gap+cwid), h-5);
                }
                g.setColor(Color.red);
                int colh = ch*data[j]/maxValue;
                g.fillRect(border+j*(gap+cwid), cbot-colh, cwid, colh);
            }
    
    
    }

    public void error(String m) {
        errmess = m;
        System.out.println(m);
        status(m);
    }
}

Example 10-13: Play Domain Program Generator Using JSP

<pre>
<%@ import = "java.io.*" %>
<% PlayData1 d = null;
   String filename = request.getParameter("xmlfile");
   if (filename==null || filename.equals("")) {
	filename = "/home/craig/progen/play/play1.xml";
   }
   try {
      // read and parse Play specification
      d = new PlayData1(filename);
   } catch (Exception e) {
      out.println("Exception: "+e.getMessage());
      e.printStackTrace(out);
   }
%>


import java.awt.*;
import java.awt.event.*;

class <%=d.name%>Play2 extends Frame {
    /* The Props for <%=d.name%> ****************/

<% for (int j=0; j<d.props.length; ++j) {
       PlayData1.PropData prop = d.props[j];
%>
    Button <%=prop.name%>Prop = new Button("<%=prop.label%>");
<% } %>

    /* The Events in the <%=d.name%> ***************/

    class PropEvent implements ActionListener {
        public void actionPerformed(ActionEvent evt) {
            Object prop = evt.getSource();
<% for (int j=0; j<d.props.length; ++j) {
       PlayData1.PropData prop = d.props[j];
       out.print("            ");
       if (j!=0) {
           out.print("} else ");
       }
       out.println("if (prop=="+prop.name+"Prop) {");
       if (prop.script!=null) {
           for (int k=0; k<prop.script.traits.length; ++k) {
                String pname = prop.script.traits[k].prop==null
                        ? prop.name : prop.script.traits[k].prop.name;
                out.println("                "
                        +pname+"Prop.setLabel(\""
                        +prop.script.traits[k].newValue+"\");");
            }
            if (prop.script.nextScene!=null) {
                out.println("                enterNewScene(\""
                         +prop.script.nextScene.name+"\");");
            }
       }
   }
%>
            } else {
                System.out.println("Invalid prop");
            }
        }
    }

    /* Creating and starting up the <%=d.name%> ****/

    String currentScene;

    public <%=d.name%>Play2() {
        super("<%=d.title%>");
        setSize(<%=d.width%>, <%=d.height%>);
        setLayout(new FlowLayout());

        // initialize props
        PropEvent a = new PropEvent();
<% for (int j=0; j<d.props.length; ++j) {
       PlayData1.PropData prop = d.props[j];
%>
        <%=prop.name%>Prop.addActionListener(a);
<% } %>

        // start scene
        enterNewScene("<%=d.startScene.name%>");
    }

    public void enterNewScene(String scene) {
        removeAll();  // remove previous scene
        currentScene = scene;
<% for (int k=0; k<d.scenes.length; ++k) {
       PlayData1.SceneData scene = d.scenes[k];
       out.print("        ");
       if (k!=0) {
           out.print("} else ");
       }
       out.println("if (scene.equals(\""+scene.name+"\")) {");
       for (int p2=0; p2<scene.addprops.length; ++p2) {
            PlayData1.PropData prop2 = scene.addprops[p2];
            out.println("            add("+prop2.name+"Prop);");
      }
%>
            setBackground(Color.decode("<%=scene.color%>"));
<% } %>
        } else {
            System.out.println("Invalid scene: "+scene);
        }
        show();
    }

    public static void main(String[] args) {
        new <%=d.name%>Play2();
    }
}