/*-------------------------------------------------------------------*/
/* Web Development with SAS by Example */
/* by Frederick E. Pratter */
/* Copyright(c) 2003 by SAS Institute Inc., Cary, NC, USA */
/* SAS Publications order # 58694 */
/* ISBN 1-59047-329-9 */
/*-------------------------------------------------------------------*/
/* */
/* This material is provided "as is" by SAS Institute Inc. There */
/* are no warranties, expressed or implied, as to merchantability or */
/* fitness for a particular purpose regarding the materials or code */
/* contained herein. The Institute is not responsible for errors */
/* in this material as it now exists or will exist, nor does the */
/* Institute provide technical support for it. */
/* */
/*-------------------------------------------------------------------*/
/* Questions or problem reports concerning this material may be */
/* addressed to the author: */
/* */
/* SAS Institute Inc. */
/* Books by Users */
/* Attn: Frederick Pratter */
/* SAS Campus Drive */
/* Cary, NC 27513 */
/* */
/* */
/* If you prefer, you can send email to: sasbbu@sas.com */
/* Use this for subject field: */
/* Comments for Frederick Pratter */
/* */
/*-------------------------------------------------------------------*/
/* Date Last Updated: August 20, 2003 */
/*-------------------------------------------------------------------*/
Chapter 2
Example 2.1
Example 3.3
options noovp nodate nonumber nocenter ls=80;
filename temp 'Example 3-3.lst';
filename out 'Example 3-3.html';
*** redirect procedure output ***;
proc printto new file=temp;
*** create table ***;
proc tabulate data=SASHELP.RETAIL
formchar='|----|+|---+=|-/\<>*';
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
*** turn off redirection ****;
proc printto;
*** generate HTML output ***;
data _null_;
infile temp end=eof;
input;
file out;
if (_n_ eq 1) then /* write header and title */
put ''/
''/
'' _infile_ ''/
''/
'
' _infile_ '
'/
'
';
else put _infile_;
if (eof) then /* write closing tags */
put '
'/ ''/' ';
run;
Example 3.4
options noovp nodate nonumber nocenter ls=80;
filename OUT 'Example 3-4.html';
%OUT2HTM(capture=on);
*** create table ***;
proc means data=SASHELP.RETAIL
n mean min max
nonobs fw=8 maxdec=2;
class YEAR/descending;
var SALES;
title;
run;
%OUT2HTM(capture=off, htmlfref=OUT);
Example 3.5
The MEANS Procedure
Analysis Variable : SALES Retail sales in millions of $
YEAR N Mean Minimum Maximum
--------------------------------------------------
Example 3.6
options noovp nodate nonumber nocenter ls=80;
filename OUT 'Example 3-6.html';
title "1994 Sales Total by Month";
%ds2htm (data=SASHELP.RETAIL,
where = YEAR gt 1990,
var = YEAR MONTH SALES,
htmlfref = out);
Example 3.7
1994 Sales Total By Month
MONTH
Retail sales in millions of $
1
$876
4
$998
Example 3.8
options noovp nodate nonumber nocenter ls=80;
filename OUT 'Example 3-8.html';
%TAB2HTM(capture=on);
*** create table ***;
proc tabulate data=SASHELP.RETAIL;
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
%TAB2HTM(capture=off, htmlfref=OUT);
Example 3.9
Retail Sales In Millions Of $
Year
Total Sales
Overall Percent
Number of Sales
Average Sale
Smallest Sale
Largest Sale
1994
$1,874
5.97
2
$937.00
$876
$998
[13 rows omitted]
1980
$1,030
3.28
4
$257.50
$220
$295
Total
$31,374
100.00
58
$540.93
$220
$998
Example 3.10
SAS Output
Retail Sales In Millions Of $
Year
Total Sales
Overall Percent
Number of Sales
Average Sale
Smallest Sale
Largest Sale
1994
$1,874
5.97
2
$937.00
$876
$998
[13 rows omitted]
1980
$1,030
3.28
4
$257.50
$220
$295
Total
$31,374
100.00
58
$540.93
$220
$998
Example 3.11
options noovp ls=80 nodate nonumber;
filename OUT "Example 3-11.html";
ods listing close;
ods html body=OUT;
proc tabulate data=SASHELP.RETAIL;
title "Retail Sales In Millions of $";
class YEAR/descending;
var SALES;
table YEAR="" all="Total", SALES="" *
(sum="Total Sales"*f=dollar8.
pctsum="Overall Percent"*f=8.2
n="Number of Sales"*f=8.
mean="Average Sale"*f=dollar8.2
min="Smallest Sale"*f=dollar8.
max="Largest Sale"*f=dollar8.)/
box="Year" rts=8;
run;
ods html close;
ods listing;
Example 3.12
options noovp nodate nonumber nocenter ls=80;
ods listing close;
ods html body="Example 3-9.html" newfile=proc;
***** Step #1 ****;
proc print data=SASHELP.RETAIL;
title "1994 Sales Total by Month";
where YEAR gt 1990;
var MONTH SALES;
id YEAR;
run;
***** Step #2 ****;
proc means data=SASHELP.RETAIL
n mean min max
nonobs fw=8 maxdec=2;
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
run;
***** Step #3 ****;
proc tabulate data=SASHELP.RETAIL;
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
ods html close;
ods listing;
Example 3.13
options noovp ls=80 nodate nonumber;
ods listing close;
ods html
path="c:\Documents and Settings\All Users\Documents"
(url="http://hrothgar/examples/")
body="Example 3-13.html"
contents="Contents 3-13.html"
frame="Frame 3-13.html";
***** Step #1 ****;
proc print data=SASHELP.RETAIL;
title "1994 Sales Total by Month";
where YEAR gt 1990;
var MONTH SALES;
id YEAR;
run;
***** Step #2 ****;
proc means data=SASHELP.RETAIL
n mean min max
nonobs fw=8 maxdec=2;
title 'Retail Sales In Millions Of $';
class YEAR/descending;
var SALES;
run;
***** Step #3 ****;
proc tabulate data=SASHELP.RETAIL;
class YEAR/descending;
var SALES;
table YEAR='' all='Total', SALES='' *
(sum='Total Sales'*f=dollar8.
pctsum='Overall Percent'*f=8.2
n='Number of Sales'*f=8.
mean='Average Sale'*f=dollar8.2
min='Smallest Sale'*f=dollar8.
max='Largest Sale'*f=dollar8.)/
box='Year' rts=8;
run;
ods html close;
ods listing;
Example 3.14
options ls=80 noovp nodate nonumber;
filename OUT "Example 3-14.html";
title "Sales Total by Month 1991-1994";
ods listing close;
ods html body=OUT;
data _null_;
set SASHELP.RETAIL;
where (YEAR gt 1990);
file print
ods=(variables=(YEAR MONTH SALES));
put _ods_;
run;
ods html close;
ods listing;
Example 3.15
proc template;
define style Styles.Default;
style fonts "Fonts used in the default style" /
'TitleFont2' = ("Arial, Helvetica, Helv",4,Bold Italic)
'TitleFont' = ("Arial, Helvetica, Helv",5,Bold Italic)
[more define statements...]
end;
run;
Example 3.16
options ls=80 noovp nodate nonumber;
filename OUT "Example 3-16.html";
title "Sales Total by Month 1991-1994";
ods listing close;
ods html body=OUT style=sasweb;
data _null_;
set SASHELP.RETAIL;
where (YEAR gt 1990);
file print
ods=(variables=(YEAR MONTH SALES));
put _ods_;
run;
ods html close;
ods listing;
Example 3.17
options noovp ls=80 nodate nonumber;
filename OUT "Example 3-17.html";
ods listing close;
ods markup body=OUT tagset=XHTML;
proc tabulate data=SASHELP.RETAIL;
title "Retail Sales In Millions Of $";
class YEAR/descending;
var SALES;
table YEAR="" all="Total", SALES="" *
(sum="Total Sales"*f=dollar8.
pctsum="Overall Percent"*f=8.2
n="Number of Sales"*f=8.
mean="Average Sale"*f=dollar8.2
min="Smallest Sale"*f=dollar8.
max="Largest Sale"*f=dollar8.)/
box="Year" rts=8;
run;
ods markup close;
ods listing;
Example 3.18
SAS Output
Retail Sales In Millions Of $
Year
Total Sales
Overall Percent
Number of Sales
Average Sale
Smallest Sale
Largest Sale
1994
$1,874
5.97
2
$937.00
$876
$998
[13 rows omitted]
1980
$1,030
3.28
4
$257.50
$220
$295
Total
$31,374
100.00
58
$540.93
$220
$998
Example 3.19
proc template;
define tagset Tagsets.xhtml / store = SASUSER.TEMPLAT;
define event cell_is_empty;
put %nrstr(" ");
end;
define event doc;
start:
put "" NL;
put "" NL;
put "" NL;
ndent;
finish:
xdent;
put "" NL;
end;
define event doc_head;
start:
put "" NL;
ndent;
finish:
xdent;
put "" NL;
end;
define event doc_body;
start:
put "" NL;
put TITLE;
finish:
/* add W3C logo to page */
put '
';
print end_html;
Chapter 6
Example 6.1
[root@hrothgar frederick]# cd /tmp/inet/websrv
[root@hrothgar websrv]# ksh INSTALL
Welcome to the SAS/IntrNet CGI Tools installation script.
You will be prompted for information about your Web server configuration and how you wish to install SAS/IntrNet. This installation script will move the files that were extracted from the CGI Tools package into a directory under your Web server. You will
be able to review and confirm your responses before any updates are made to your system.
The CGI Tools samples must be installed in the Web server directory corresponding to the URL http:///sasweb.
Enter the physical path corresponding to http:///sasweb.
If this directory does not exist, it will be created for you.
Path: /var/www/html/sasweb
Enter the physical path for SAS/IntrNet CGI executables. This can be a standard CGI directory or a new directory reserved for SAS/IntrNet. Setup will create this directory for you if it does not exist.
Path [/var/www/cgi-bin]: [CR] (This is a carriage return, not the text "CR" obtained by pressing the Enter key.)
The CGI executables and configuration files must be installed in a Web server directory with execute privilege. We suggest using the URL http:///cgi-bin for these files, although you may use any URL.
Enter the URL path corresponding to the physical path /var/www/cgi-bin.
CGI URL [http:///cgi-bin]: http://hrothgar/cgi-bin
The following steps will be performed:
- Sample files will be updated to use http:///cgi-bin for all CGI references.
- Sample files will be installed to /var/www/html/sasweb/IntrNet8. Existing files will be overwritten.
- CGI executables and configuration files will be installed to /var/www/cgi-bin. Existing executables will be renamed as a backup before the new executables are installed. New configuration files are installed with a .cfg_v8 extension so that existing conf
iguration files are not overwritten. If no existing configuration file is found the .cfg_v8 file is copied to create a new .cfg file.
- Java Graphics files will be moved to /var/www/html/sasweb/graph. Existing files will be renamed as a backup.
Do you wish to continue [Y]? [CR]
Modifying URL to CGI Tools in sample files
Moving samples to /var/www/html/sasweb/IntrNet8
Moving CGI files to /var/www/cgi-bin
Moving Java Graphics files to /var/www/html/sasweb/graph
The installation is complete. Verify that your Web server is configured to:
- map http:///cgi-bin to /var/www/cgi-bin
- allow CGI execution in http:///cgi-bin
- map http:///sasweb to /var/www/html/sasweb
Once your SAS Servers are configured and started, you can view SAS/IntrNet samples at http:///sasweb/IntrNet8/samples.html.
Example 6.2
[root@hrothgar]# cd /usr/local/SAS_8.2/utilities/bin
[root@hrothgar bin]# ./inetcfg.pl
Root directory for SAS/IntrNet services (/root/intrnet): /var/www/html/sasweb/IntrNet8
What kind of service do you wish to configure?
1 - Socket Service2 - Pool Service
3 - Launch Service
4 - Load Manager
5 - Spawner
Enter service type? (1): [CR]
This script will set up a service definition for the SAS/IntrNet Application Dispatcher. You should know the type of service you wish to create and the TCP port number(s) or name(s) you wish to use (socket service only) before continuing.
You will be asked to provide a directory name. The script will create this directory and place server startup and log files in it.
Name of the new service? (default): [CR]
How many servers would you like for this service (maximum 20)? (1):[CR]
Please enter TCP/IP port values for this service. You may use a service name such as appsrv or a port number such as 5001. If you use a name, please remember to include this name in your network services file along with a port number.
Port name or number for server 1 (5001): [CR]
Do you want to protect the administration of this service with a password? (N): [CR]
Service name : default
Service type : Socket
Root Directory : /var/www/html/sasweb/IntrNet8/default
Number of servers : 1
Server port(s) : 5001
Admin password : none
Create this service? (Y): [CR]
The service directory has been created.
To start the default service execute
/var/www/html/sasweb/IntrNet8/default/start.pl
The files necessary for this service have been created. To complete the configuration perform the steps outlined in this checklist.
* Install the Application Broker on your Web server machine.
* Create a service definition in your broker.cfg file for the
"default" service. For example:
SocketService default
ServiceAdmin "[your-name]"
ServiceAdminMail "[your-email]@[your-site]"
Server hrothgar.beowulf
Port 5001
FullDuplex True
Example 6.3
##-----------------------------------------------------------------
## Definitions for full-time ("socket") servers
##-----------------------------------------------------------------
# Supplied Directive Description
# ------------------ -----------
#
# SocketService Starts a service definition. Parameters are the service # name and short description. The name given here is the value
# specified in the "_service" hidden field submitted to the broker.
## ServiceDescription Longer description used when building a list
# of services. [optional, no default]
## ServiceAdmin Specifies the name of the service administrator.
# If omitted the global Administrator is used.
## ServiceAdminMail Specifies the email address of the administrator of
# this service. If omitted the global Administrator is used.
## Server DNS name or IP address of application server host
## Port TCP port number (256-65535)
#
# ServiceCompatibility Used to specify compatibility with Version 6 and 7
#
# Application Servers. Set to 1.0 for non-V8.
#
# FullDuplex Communicate with a V8.1 or later App Server over one
# bidirectional socket
#
# Consult the Application Dispatcher documentation for a complete list
# of directives. We recommend each site define a default service.
#
# There is nothing special about the name 'default', it is simply a
# convention you can use at your site.
SocketService default "Reuse existing session"
ServiceDescription "Pages reference this generic server when they don't care which service is used."
ServiceAdmin "Your Name"
ServiceAdminMail "yourname@yoursite"
Server appsrv.yourcomp.com
Port 5001
# Remove the following line for any servers before V8.1
FullDuplex True
Example 6.4
/**************************************************************/
/* S A S S A M P L E L I B R A R Y */
/* */
/* NAME: WEBHELLO */
/* TITLE: Hello World */
/* PRODUCT: SAS/IntrNet (Application Dispatcher) */
/* SYSTEM: ALL */
/* */
/* SUPPORT: Web Tools Group UPDATE: 13Oct2000 */
/* REF: http://www.sas.com/rnd/web/dispatch/ */
/**************************************************************/
/*simply write out a web page that says "Hello World!"*/
data _null_;
file _webout;
put '';
put 'Hello World!';
put '';
put '
Hello World!
';
put '';
put '';
run;
Example 6.5
/* sample SAS program to convert F to C and vice versa */
data _null_;
file _webout;
***** write generic XHTML header *****;
put ''/
''/
'';
***** write top of page *****;
put ''/
' SAS/IntrNet Temperature Conversion Calculator '/
''/
''/
'
'/
'
Temperature Conversion Calculator
';
**** create HTML form * with hidden text fields ***;
put ''/
'
'/
''/
'';
run;
Example 6.6
proc appsrv unsafe='&";%''' &sysparm ;
allocate file sample '!SASROOT/samples/intrnet';
allocate library samplib '!SASROOT/samples/intrnet' access=readonly;
allocate library sampdat '!SASROOT/samples/intrnet' access=readonly;
allocate library tmplib '';
allocate file logfile '../logs/%a_%p.log';
allocate file examples '/home/frederick/cgi-bin';
proglibs examples;
proglibs sample samplib %ifcexist(sashelp.webeis) sashelp.webprog;
proglibs sashelp.websdk1;
adminlibs sashelp.webadmn;
datalibs sampdat tmplib;
log file=logfile;
Example 6.7
%* Sales report Example - Display Product by Region;
%macro salesrpt;
%global region;
proc report data=sashelp.shoes;
by region;
%if (®ion ne ) %then %do;
where region="®ion";
%end;
title "Sales By Product";
footnote "Data are current as of &systime &sysdate9";
column product sales;
define product / group;
define sales / analysis sum;
quit;
%mend salesrpt;
/* prepend XHTML template */
libname userlib '/usr/local/SAS_8.2/users';
ods path (prepend) userlib.templat;
/* redirect output to client */
ods markup body=_webout tagset=xhtml;
%salesrpt
Chapter 7
Example 7.1
SAS IntrNet Examples: htmSQL
{query server="hygelac.shr1" sapw="user"}
{sql}
select product,
sum(sales) as total label="Total Sales" format=dollar8.
from sashelp.shoes
group by product
where region="Africa";
{/sql}
{norows}
Sales by Product
{/norows}
Region=Africa
{label var="{&sys.colname[*]}" before="
"
between="
" after="
"}
{eachrow}
{&{&sys.colname[*]} before="
"
between="
" after="
"}
{/eachrow}
{/query}
Data are current as of
{&sys.time}{&sys.ampm} {&sys.month} {&sys.monthday}, {&sys.year}
Example 7.2
SAS IntrNet Examples: htmSQL
{query server="hygelac.shr1" sapw="user"}
{sql}
select distinct region from sashelp.shoes;
{/sql}
{/query}
Chapter 8
Example 8.1
Display Date Using JavaScript
Example 8.2
html>
JavaScript Temperature Conversion Calculator
Temperature Conversion Calculator
Example 8.3
Java Temperature Conversion Applet
Temperature Conversion Calculator
Example 8.4
// Temperature Conversion Applet
import java.applet.*;
import java.awt.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class calculator
extends Applet
implements ActionListener
{
private TextField tfInput, tfResult;
private Button btF2C, btC2F;
private final String F2C = new String("Fahrenheit to Centigrade");
private final String C2F = new String("Centigrade to Fahrenheit");
//initialize user interface
public void init()
{
//set layout and foreground colors
setLayout(new BorderLayout());
setBackground(Color.white);
setFont(new Font("Times New Roman", Font.PLAIN, 14));
//create text fields
tfInput = new TextField(6);
tfResult = new TextField(6);
//set result field read only
tfResult.setEditable(false);
//create buttons
btF2C = new Button(F2C);
btC2F = new Button(C2F);
//register listeners
btF2C.addActionListener(this);
btC2F.addActionListener(this);
//create 3 panels
Panel p1 = new Panel();
p1.add(new Label(
"Enter a temperature and select conversion type:"));
p1.add(tfInput);
Panel p2 = new Panel();
p2.add(new Label("Result:"));
p2.add(tfResult);
Panel p3 = new Panel();
p3.add(btF2C);
p3.add(btC2F);
// add panels to frame
add(BorderLayout.NORTH, p1);
add(BorderLayout.CENTER, p2);
add(BorderLayout.SOUTH, p3);
}
//event handler for buttons
public void actionPerformed(ActionEvent e)
{
String actionCommand = e.getActionCommand();
double t1, t2;
// get input temp
t1=(Double.valueOf(tfInput.getText())).doubleValue();
// compute result
t2=actionCommand.equals(F2C) ? 5*(t1-32)/9 : 9*t1/5 + 32 ;
// display result
tfResult.setText(String.valueOf(t2));
}
}
Example 8.5
import javax.swing.*;
import java.awt.*; // include font, colors, layouts
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Jcalc
extends JApplet
implements ActionListener
{
private JTextField tfInput, tfResult;
private JButton btF2C, btC2F;
private final String F2C = new String
("Fahrenheit to Centigrade");
private final String C2F = new String
("Centigrade to Fahrenheit");
//initialize user interface
public void init()
{
//format the applet's content pane
getContentPane().setLayout(new BorderLayout());
getContentPane().setBackground(Color.white);
getContentPane().setFont
new Font("Times New Roman", Font.PLAIN, 14));
//create text fields
tfInput = new JTextField(6);
tfResult = new JTextField(12);
//set result field read only
tfResult.setEditable(false);
//create buttons
btF2C = new JButton(F2C);
btC2F = new JButton(C2F);
//register listeners
btF2C.addActionListener(this);
btC2F.addActionListener(this);
//create 3 panels
JPanel p1 = new JPanel();
p1.add(new JLabel
("Enter a temperature and select conversion type:"));
p1.add(tfInput);
JPanel p2 = new JPanel();
p2.add(new JLabel("Result:"));
p2.add(tfResult);
JPanel p3 = new JPanel();
p3.add(btF2C);
p3.add(btC2F);
// add panels to content pane
getContentPane().add(BorderLayout.NORTH, p1);
getContentPane().add(BorderLayout.CENTER, p2);
getContentPane().add(BorderLayout.SOUTH, p3);
}
}
Example 8.6
Java Temperature Conversion Applet (JDK 1.2 Plugin)
Temperature Conversion Calculator
Example 8.7
// A simple Bean
import java.io.Serializable;
public class TestBean
implements Serializable
{
private int num;
public void setValue(int n)
{
num = n;
}
public int getValue()
{
return num;
}
}
Chapter 9
Example 9.1
Calculator
Example 9.2
Threaded connection test starting...
Telnet session established on Tue Apr 09 19:48:36 PDT 2002
Telnet client: com.sas.net.connect.SASTelnetClient
Host: ETHELREDPort: 2323
Looking for message from host containing one of the following
Hello>
Received: Hello>
Sent: sas
Looking for message from host containing one of the following
PORT=
Received:
SAS(R) TCPIP REMOTE LINK PORT=Fetching SAS port number
NOTE: Copyright (c) 1999-2001 by SAS Institute Inc., Cary, NC, USA.
NOTE: SAS (r) Proprietary Software Release 8.2 (TS2M0)
Licensed to FREDERICK PRATTER.
NOTE: This session is executing on the WIN_98 platform.
NOTE: SAS initialization used:
real time 1.80 seconds
1 %put RemoteSASInfoStart &SYSVER RemoteSASInfoEnd;
RemoteSASInfoStart 8.2 RemoteSASInfoEnd
NOTE: PROCEDURE PRINTTO used:
real time 0.00 seconds
NOTE: SAS Server: Authorization commencing...
NOTE: SAS Server: Client LOGON
NOTE: NEW task=3 factory=8387 oid=8425 class=sashelp.prdauth.userinfo.class
NOTE: NEW task=3 factory=8387 oid=8505 class=SASHELP.RSASMOD.SRVINFO.CLASS
NOTE: Ofactory : _term
NOTE: TERM task=3 factory=8387 oid=8505
NOTE: TERM task=3 factory=8387 oid=8425
NOTE: SAS Server: Client LOGOFF
NOTE: Stopping task taskid=3 curtask=1
Success!!
Example 9.3
libname corehelp "d:\sas\core\sashelp";
filename updates
"d:\AppDevStudio\ads203Deployment\SASUpdates\V8\appdev.cpo";
proc cimport force library=corehelp infile=updates;
run;
Example 9.4
TableViewExample
Example 9.5
Chapter 10
Example 10.1
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class SimpleServlet extends HttpServlet
{
public void doGet (HttpServletRequest request,
HttpServletResponse response)
throws ServletException, IOException
{
PrintWriter out;
String title = "Simple Servlet Output";
response.setContentType("text/html");
out = response.getWriter();
out.println("");
out.println(title);
out.println("");
out.println("
<% out.print("Hello World!"); %>
The time now is <%= new java.util.Date() %>
Example 10.3
package org.apache.jsp;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import org.apache.jasper.runtime.*;
public class example1$jsp extends HttpJspBase
{
static {} public example1$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
{
if (_jspx_inited == false)
{
synchronized (this)
{
if (_jspx_inited == false)
{
_jspx_init();
_jspx_inited = true;
}
}
}
_jspxFactory = JspFactory.getDefaultFactory();
response.setContentType("text/html;charset=ISO-8859-1");
pageContext = _jspxFactory.getPageContext
(this, request, response,"", true, 8192, true);
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
ses sion = pageContext.getSession();
out = pageContext.getOut();
// HTML
// begin [file="/jsp/example1.jsp";from=(0,0); to=(13,1)]
out.write ("\r\n
\r\n
\r\n
\r\n
\tJSP Examples\r\n
\t\r\n\r\n
\r\n
\t
Example 1. Simple JavaServer Page
\r\n
\t");
// end
// begin [file="/jsp/example1.jsp";from=(13,3);to=(13,33)]
out.println("Hello World!");
// end
// begin [file="/jsp/example1.jsp";from=(13,35);to=(14,17)]
out.write("\r\n\tThe time now is ");
// end
// begin [file="/jsp/example1.jsp";from=(14,20);to=(14,42)]
out.print( new java.util.Date() );
// end
// begin [file="/jsp/example1.jsp";from=(14,44);to=(18,0)]
out.write("\r\n\r\n\r\n\r\n");
// 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);
}
}
}
Example 10.4
li> Day of month: is
Year: is
Month: is
Time: is
Date: is
Day: is
Day Of Year: is
Week Of Year: is
era: is
DST Offset: is
Zone Offset: is
Example 10.5
package examples;
import java.util.Date;import javax.servlet.jsp.*;
import javax.servlet.jsp.tagext.*;
public class SimpleTag
extends TagSupport
{
public int doStartTag() throws JspException
{
try
{
pageContext.getOut().print
("Hello World." + "The time now is " +
new Date());
}
catch (Exception ex)
{
throw new JspTagException
("SimpleTag: " + ex.getMessage());
}
return SKIP_BODY;
}
public int doEndTag()
{
return EVAL_PAGE;
}
}
Example 10.6
1.01.2Sample tag libraryLibrary for simple tag exampleSayHelloexamples.SimpleTagEMPTYHello world example
Example 10.7
<%@ taglib URL="simple.tld" prefix="test" %>
JSP Examples - Custom Tag Library
Example 10-7. JavaServer Page
Custom Tag Example
Example 10.8
import java.sql.*;
public class ODBCTest
{
public static void main(String[] args)
{
Connection con = null;
try // open connection to database
{
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:Northwind");
// print connection information
DatabaseMetaData dma = con.getMetaData();
System.out.println("\nConnected to " + dma.getURI());
System.out.println("Driver " + dma.getDriverName());
System.out.println("Version " + dma.getDriverVersion());
}
catch(Exception e)
{
e.printStackTrace();
}
finally // make sure connection gets closed properly
{
try
{
if (null != con) con.close();
}
catch (SQLException e) {}
}
}
}
Example 10.9
<%@ taglib URL=http://jakarta.apache.org/taglibs/dbtags
prefix="sql" %>
JSP Examples - JDBC
Example 10.9. JavaServer Page
JDBC Example
Category = 1
ProductID
ProductName
<%-- open a database connection --%>
sun.jdbc.odbc.JdbcOdbcDriver
jdbc:odbc:Northwind
<%-- open a database query --%>
select ProductID, ProductName
from products
where CategoryID = 1
<%-- loop through the rows of your query --%>
No records were selected.
<%-- close database connection --%>
Chapter 11
Example 11.1
// start java webserver
-Morg.apache.tomcat.startup.Tomcat
-Dtomcat.home=d:\Apache\htdocs\sasweb
-Djava.class.path=d:\Apache\htdocs\sasweb;
D:\AppDevStudio\webaf\projects;
D:\AppDevStudio\java\webserver\webserver.jar;
D:\AppDevStudio\java\webserver\jasper.jar;
D:\AppDevStudio\java\misc\servlet.jar;
D:\AppDevStudio\java\misc\xerces.jar;
D:\jdk1.3.0_01\lib\tools.jar;
D:\AppDevStudio\java\misc\webAFServerPages.jar
Example 11.2
Starting tomcat. Check logs/tomcat.log for error messages
2002-08-07 01:24:53 - ContextManager: Adding context Ctx( /examples )
2002-08-07 01:24:53 - ContextManager: Adding context Ctx( )
2002-08-07 01:24:53 - ContextManager: JspClassDebugInfo: Enabling inclusion of class debugging information in JSP servlets for context "/examples".
2002-08-07 01:24:53 - path="/examples" :jsp: init
2002-08-07 01:24:54 - Scratch dir for the JSP engine is: D:\AppDevStudio\WebAppDev\work\localhost_8082%2Fexamples
2002-08-07 01:24:54 - IMPORTANT: Do not modify the generated servlets
2002-08-07 01:24:54 - ContextManager: JspClassDebugInfo: Enabling inclusion of class debugging information in JSP servlets for context "".
2002-08-07 01:24:54 - path="" :jsp: init
2002-08-07 01:24:54 - PoolTcpConnector: Starting HttpConnectionHandler on 8082
2002-08-07 01:24:54 - PoolTcpConnector: Starting Ajp12ConnectionHandler on 8083
Example 11.3
<%@taglib URL="http://www.sas.com/taglib/sasads" prefix="sasads"%>
JSP Examples
Temperature Conversion Calculator
[Java scriptlet comes next]
[HTML form code follows]
Example 11.4
<% // Java scriptlet to calculate temperature conversion
String temp = request.getParameter("input");
String type = request.getParameter("convert");
String result = new String();
// make sure that we have values for the parameters
if (null != temp && null != type)
{
double dt = new Double(temp).doubleValue();
if (type.charAt(0) == 'F')
result = String.valueOf(5d * (dt - 32d)/9d);
else if (type.charAt(0) == 'C')
result = String.valueOf((9d * dt) / 5d + 32d);
}
%>
Example 11.5
<%-- JSP Temperature Conversion Calculator --%>
<%@ include file="JSPheader.html" %>
<% // Java scriptlet to calculate temperature
String temp = request.getParameter("input");
String type = request.getParameter("convert");
String result = new String();
// make sure that we have values for the parameters
if (null != temp && null != type)
{
double dt = new Double(temp).doubleValue();
if (type.charAt(0) == 'F')
result = String.valueOf(5d * (dt - 32d)/9d);
else if (type.charAt(0) == 'C')
result = String.valueOf((9d * dt) / 5d + 32d);
}
%>
Temperature Conversion Calculator
Fahrenheit to Centigrade
Centigrade to Fahrenheit
<%@ include file="JSPfooter.html" %>
Example 11.6
<%@ page import="com.sas.collection.OrderedCollection" %>
<% // Java scriptlet to calculate temperature
String temp = request.getParameter("input");
String type = request.getParameter("convert");
String result = new String();
// default is 1st radio button
int checked = 0;
// add the labels for the radio buttons to the page context
pageContext.setAttribute
( "values", new OrderedCollection("F,C") );
pageContext.setAttribute
( "labels", new OrderedCollection
("Fahrenheit to Centigrade, Centigrade to Fahrenheit") );
if (null != temp && null != type)
{
double dt = new Double(temp).doubleValue();
if (type.charAt(0) == 'F')
{
result = String.valueOf(5d * (dt - 32d)/9d);
}
else if (type.charAt(0) == 'C')
{
result = String.valueOf((9d * dt) / 5d + 32d);
checked = 1;
}
}
%>
Example 11.7
JSP Examples
Temperature Conversion Calculator
Example 11.8
options nodate nonumber noovp;
/* Sample Program: shoes.sas */
%macro salesrpt(region);
proc report data=sashelp.shoes;
by region;
%if (®ion ne ) %then %do;
where region="®ion";
%end;
title "
Shoe Sales by Region x Product
";
footnote "Data are current as of &systime &sysdate9";
column product sales;
define product / group;
define sales / analysis sum;
quit;
%mend salesrpt;
Example 11.9
<%@taglib URL="http://www.sas.com/taglib/sasads" prefix="sasads"%>
<%@ include file="JSPheader.html" %>
<%@ include file="shoes.sas" %>
%salesrpt(<%= request.getParameter("region") %>)
<%@ include file="JSPfooter.html" %>
Example 11.10
<%@ include file="JSPheader.html" %>
<%@ taglib URL="http://www.sas.com/taglib/sasads" prefix="sasads"%>
<%@ page import="com.sas.sasserver.datasetinfo.DataSetInfoInterface" %>
<%@ page import="com.sas.collection.OrderedCollection" %>
<% // Java scriptlet
DataSetInfoInterface dsinfo = (DataSetInfoInterface)
com.sas.servlet.util.Util.newInstance
(connection1.getClassFactory(),
connection1, DataSetInfoInterface.class);
dsinfo.setDataSet("SASHELP.SHOES");
// display unique values of region
int index = dsinfo.getVariableIndex("REGION");
String[] values = dsinfo.getVariableUniqueValues(index);
pageContext.setAttribute("values",new OrderedCollection(values));
%>
International Shoe Sales Data
<%@ include file="JSPfooter.html" %>
Example 11.11
<%@taglib uri="http://www.sas.com/taglib/sasads" prefix="sasads"%>
<%@ page import="com.sas.collection.StringCollection" %>
<% // Get unique test names and codes from data set,
// add collections to page context
pageContext.setAttribute ("codes",
new StringCollection(table1.getFormattedColumn(1)));
pageContext.setAttribute ("labels",
new StringCollection(table1.getFormattedColumn(2)));
%>
<%-- begin HTML --%>
JSP Examples
On-line Exam Demo
Example 11.12
<%@taglib URL="http://www.sas.com/taglib/sasads" prefix="sasads"%>
<%@ include file="JSPheader.html" %>
SASHELP.RETAIL Data Set
Range: 1990 to 1994
<%@ include file="JSPfooter.html" %>
Example 11.13
JSP Examples
SASHELP.RETAIL Data Set
Range: 1990 to 1994
SALES
DATE
YEAR
MONTH
DAY
$606
90Q1
1990
1
1
$674
90Q2
1990
4
1
$705
90Q3
1990
7
1
$749
90Q4
1990
10
1
$703
91Q1
1991
1
1
$709
91Q2
1991
4
1
$728
91Q3
1991
7
1
$807
91Q4
1991
10
1
$692
92Q1
1992
1
1
$797
92Q2
1992
4
1
$826
92Q3
1992
7
1
$889
92Q4
1992
10
1
$758
93Q1
1993
1
1
$909
93Q2
1993
4
1
$920
93Q3
1993
7
1
$991
93Q4
1993
10
1
$876
94Q1
1994
1
1
$998
94Q2
1994
4
1
Example 11.14
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import com.sas.rmi.*;
import com.sas.sasserver.dataset.*;
public class ServletExample extends HttpServlet
{
public void doPost(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException
{
// retrieve the current session identifer
HttpSession session = request.getSession();
// Setup the connection to SAS
Connection connection1 = new Connection();
connection1.setHost("ethelred");
connection1.setUsernamePrompt("Username:");
connection1.setUsername("IUSR_ETHELRED");
connection1.setPasswordPrompt("Password:");
connection1.setPassword("");
try
{
Rocf rocf = new Rocf();
DataSetInterface dataset1 = (DataSetInterface)
rocf.newInstance(DataSetInterface.class,connection1);
dataset1.setDataSet("sashelp.shoes");
RequestDispatcher rd = getServletContext().getRequestDispatcher("/table.jsp");
session.setAttribute("dataset1", dataset1);
rd.forward(request, response);
}
catch (Exception ex) {}
}
}
Example 11.15
<%@ taglib URL="http://www.sas.com/taglib/sasads" prefix="sasads" %>
<%@ include file="JSPheader.html" %>
International Shoes Database
<%@ include file="JSPfooter.html" %>
Chapter 12
Example 12.1
Chapter 13
Example 13.1
SAS Design Time Controls Example
SAS Design Time Controls Example
DTC Table Control: SASHELP.RETAIL
Retail sales in millions of $
DATE
YEAR
MONTH
DAY
$876
94Q1
1994
1
1
$998
94Q2
1994
4
1
Example 13.2
<%
{ appserver.AppServer IappServer = new appserver.AppServer();
IappServer.setURL(null);
IappServer.setURL("http://hrothgar/cgi-bin/broker");
String queryString = "_service=default&
_debug=0&
_program=sashelp.websdk1.ds2htm2.scl&
data=SASHELP.RETAIL&
pagepart=body&
where=year%20eq%201994&
twidth=0&
twunits=Percent&
border=Y&
formats=Y&
labels=Y&
obsnum=N&
talign=default&
vface=Arial,Helvetica,sans-serif&
sface=Arial,Helvetica,sans-serif&
clface=Arial,Helvetica,sans-serif&
iface=Arial,Helvetica,sans-serif&
oface=Arial,Helvetica,sans-serif&
cface=Arial,Helvetica,sans-serif&
bface=Arial,Helvetica,sans-serif";
java.io.OutputStream os = IappServer.getOutputStream();
os.write(queryString.getBytes());
os.close();
String HTML = IappServer.getHTML();
int responseCode = IappServer.getResponseCode();
if (responseCode >= 200 && responseCode < 300)
out.println(HTML);
else if (responseCode == 401)
{
HTML = "
ERROR: Authenticated sites are not supported.
" + HTML;
IappServer.printDTCError
(new PrintWriter(out, true), responseCode, HTML);
}
else
IappServer.printDTCError
(new PrintWriter(out, true), responseCode, HTML);
}
%>
Example 13.3
<%
sub displayURL(URL)
Dim AppServer, HTML
Set AppServer = CreateObject("SAS.AppServerPostURL")
AppServer.webServer = "hrothgar"
AppServer.URL = "/cgi-bin/broker"
AppServer.queryString = URL
HTML = AppServer.openURL()
Response.Write HTML
End sub
displayURL("_service=default&
_debug=0&
_program=sashelp.websdk1.ds2htm2.scl&
data=SASHELP.RETAIL&
pagepart=body&
where=year%20eq%201994&
twidth=0&
twunits=Percent&
border=Y&
formats=Y&
labels=Y&
obsnum=N&
talign=default&
vface=Arial,Helvetica,sans-serif&
sface=Arial,Helvetica,sans-serif&
clface=Arial,Helvetica,sans-serif&
iface=Arial,Helvetica,sans-serif&
oface=Arial,Helvetica,sans-serif&
cface=Arial,Helvetica,sans-serif&
bface=Arial,Helvetica,sans-serif")
%>