stockclient.java
来自「weblogic应用全实例」· Java 代码 · 共 233 行
JAVA
233 行
//声明
package examples.xml.http;
import java.util.*;
import java.net.*;
import org.xml.sax.*;
import java.io.*;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.parsers.SAXParser;
/**
* 这个示例演示如何创建和操作 XML 数据,并把它从客户端传送到服务器端的servlet.
*/
public class StockClient extends HandlerBase {
/** 打印 writer. */
private PrintWriter out;
/** 缺省的构造器 */
public StockClient() {
try {
out = new PrintWriter(new OutputStreamWriter(System.out, "UTF8"));
} catch (UnsupportedEncodingException e) {
}
}
/**
* 从命令行运行这个示例
* <p>
* <tt>java xml.sax.StockClient t3://localhost:7001/stock BEAS</tt>
*/
public static void main(String[] args) {
if ((args.length < 1)|| (args[0].indexOf("StockServlet")== -1)) {
System.out.println("用法: java examples.xml.http.StockClient "
+ "ServletURL");
System.out.println("例如:Example:java examples.xml.http.StockClient "
+ "http://localhost:7001/StockServlet");
}
else {
try {
URL url = new URL(args[0]);
BufferedReader msgStream = new BufferedReader(new InputStreamReader(System.in));
String line=null;
boolean quitNow = false;
boolean buy = false;
boolean sell = false;
boolean beas = false;
boolean msft = false;
boolean transactionSent = false;
do {
transactionSent = false;
//从户用端获取动作
System.out.print("动作 (\"Buy\" or \"Sell\", \"quit\" to quit): ");
line = msgStream.readLine();
if (line != null && line.trim().length() != 0) {
quitNow = line.equalsIgnoreCase("quit");
buy = line.equalsIgnoreCase("buy");
sell = line.equalsIgnoreCase("sell");
if ((buy || sell) && !quitNow) {
do {
//获取股票代号
System.out.print("代码 (\"BEAS\" or \"MSFT\", \"quit\" to quit): ");
line = msgStream.readLine();
if (line != null && line.trim().length() != 0) {
quitNow = line.equalsIgnoreCase("quit");
beas = line.equalsIgnoreCase("BEAS");
msft = line.equalsIgnoreCase("MSFT");
if ((beas || msft) && !quitNow) {
do {
// 获取数量
System.out.print("股票笔数 (\"quit\" to quit): ");
line = msgStream.readLine();
if (line != null && line.trim().length() != 0) {
quitNow = line.equalsIgnoreCase("quit");
if (!quitNow) {
// 确保用户输入的是数字
boolean isInteger = false;
try {
Integer.parseInt(line);
isInteger = true;
} catch (NumberFormatException nfe) {
isInteger = false;
}
if (isInteger) {
System.out.println("发送信息...");
URLConnection urlc = url.openConnection();
urlc.setRequestProperty("Content-Type","text/xml");
urlc.setDoOutput(true);
urlc.setDoInput(true);
PrintWriter pw = new PrintWriter(new
OutputStreamWriter(urlc.getOutputStream()), true);
// 发送 xml 到 servlet
pw.println("<?xml version='1.0'?>");
// 声明文档类型
pw.println("<!DOCTYPE stocktrade PUBLIC 'examples.xml.http-stocktrade' 'stocktrade.dtd'>");
// 设置股票交易指令
pw.print("<stocktrade ");
pw.print("action = "+ (buy ? "'buy' " : "'sell' "));
pw.print("symbol = "+ (beas ? "'BEAS' " : "'MSFT' "));
pw.print("numShares = '"+ line +"'");
pw.println(" />");
// 解析servlet返回的XML
System.setProperty("javax.xml.parsers.SAXParserFactory",
"weblogic.apache.xerces.jaxp.SAXParserFactoryImpl");
SAXParserFactory fact = SAXParserFactory.newInstance();
SAXParser parser = fact.newSAXParser();
org.xml.sax.Parser saxp = parser.getParser();
HandlerBase handler = new StockClient();
saxp.setDocumentHandler(handler);
saxp.setErrorHandler(handler);
saxp.parse(new InputSource(new BufferedReader(
new InputStreamReader(urlc.getInputStream()))));
transactionSent = true;
}
}
}
} while ( !quitNow && !transactionSent);
}
}
} while ( !quitNow && !transactionSent);
}
}
} while (! quitNow);
}
catch (FileNotFoundException fnfe) {
System.out.println("[DTD not found] Please place the stocktrade.dtd "+
"file in the examplesXMLRegistry entity folder. "+
"See the example documentation for details.");
fnfe.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
//
// 文档处理方法
//
/** 文档开始 */
public void startDocument() throws SAXException {
out.println("");
out.println("Trade results:");
} // startDocument()
/** 元素开始 */
public void startElement(String name, AttributeList attrs) throws SAXException {
if (attrs != null) {
int len = attrs.getLength();
for (int i = 0; i < len; i++) {
out.print(attrs.getName(i));
out.print("=");
out.println(attrs.getValue(i));
}
out.println(" ");
}
}
/** 文档结束 */
public void endDocument() throws SAXException {
out.flush();
}
//
// 错误处理方法
//
/** 警告 */
public void warning(SAXParseException ex) {
System.err.println("[Warning] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** 可恢复错误 */
public void error(SAXParseException ex) {
System.err.println("[Error] "+
getLocationString(ex)+": "+
ex.getMessage());
}
/** 不可恢复错误 */
public void fatalError(SAXParseException ex) throws SAXException {
System.err.println("[Fatal Error] "+
getLocationString(ex)+": "+
ex.getMessage());
throw ex;
}
/** 返回位置字符串 */
private String getLocationString(SAXParseException ex) {
StringBuffer str = new StringBuffer();
String systemId = ex.getSystemId();
if (systemId != null) {
int index = systemId.lastIndexOf('/');
if (index != -1)
systemId = systemId.substring(index + 1);
str.append(systemId);
}
str.append(':');
str.append(ex.getLineNumber());
str.append(':');
str.append(ex.getColumnNumber());
return str.toString();
}
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?