我們將創建一個web頁面,它有一個輸入表單,用戶可以輸入一個股票代號以獲得出當前股票價格(有20分鐘延遲)。如果輸入有誤,則顯示錯誤提示頁面。
quote.jsp
首先,用以下代碼創建quote.jsp頁面并將其保存在jswdk安裝目錄下的web 目錄中。大多數的頁面是含jsp代碼的標準html。第六行是一個頁面指令,表明將把所有錯誤發送到“errorpage.jsp”文中。第13到15行是一個腳本段,主要說明僅當有“symbol”參數時才顯示表格?!癷f”代碼段在32到34行結束。第17行定義了所用的javabean,第18行根據參數加載其符號屬性。第27行到29行顯示bean的屬性。除了"if"段,實際上并不涉及其它java代碼。
<html>
<head>
<title>stock quotes</title>
</head>
<body>
<%@ page errorpage="errorpage.jsp" %>
<form action="quote.jsp"
method="get"> <p>enter symbol: <input size="20" name="symbol"><input
type="submit" value="submit"></p>
</form>
<%
if (request.getparameter("symbol") != null) {
%>
<jsp:usebean id="quotes" scope="page" class="com.jguru.quotes" />
<jsp:setproperty name="quotes" property="*" />
<table border="1">
<tr>
<th align="left">symbol</th>
<th align="left">name</th>
<th align="left">price</th>
</tr>
<tr>
<td><jsp:getproperty name="quotes" property="symbol" /></td>
<td><jsp:getproperty name="quotes" property="name" /></td>
<td><jsp:getproperty name="quotes" property="price" /></td>
</tr>
</table>
<%
}
%>
</body>
</html>
errorpage.jsp
下一步,將下面的jsp源代碼保存到web頁面目錄中的“errorpage.jsp”文件中。提示“this is an error page”為第一行,它將頁面指令iserrorpage屬性設置為真。上一頁面說明了錯誤網頁的位置,本頁則說明這就是錯誤網頁。jsp文件中的其它jsp專用代碼用來訪問隱含例外對象。頁面只顯示其值:
<%@ page iserrorpage="true" %>
<html>
<head>
<title>error page</title>
</head>
<body>
<h1>our error page</h1></font>
<!-- print exception -->
we got ourselves an exception:
<%= exception %>
<a href="quote.jsp">restart</a>
</body>
</html>
quotes.java
quotes javabean 通過yahoo資源獲取股票價格。需將源代碼quotes.java保存到jswdk安裝目錄下“classes/com/jguru”目錄中的“quotes.java”文件中。從這一步起,將由jsdk中的javac編譯器來編譯它。
package com.jguru;
import java.util.*;
import java.net.*;
import java.io.*;
public class quotes {
string symbol;
string name;
string price;
public void setsymbol(string symbol) {
this.symbol = symbol;
getsymbolvalue(symbol);
}
public string getsymbol() {
return symbol;
}
public string getname() {
return name;
}
public string getprice() {
return price;
}
private void getsymbolvalue(string symbol) {
string urlstring =
"http://quote.yahoo.com/download/javasoft.beans?symbols=" +
symbol + "&format=nl";
try {
url url = new url(urlstring);
urlconnection con = url.openconnection();
inputstream is = con.getinputstream();
inputstreamreader isr = new inputstreamreader(is);
bufferedreader br = new bufferedreader(isr);
string line = br.readline();
stringtokenizer tokenizer = new stringtokenizer(line,",");
name = tokenizer.nexttoken();
name = name.substring(1, name.length()-2); // remove quotes
price = tokenizer.nexttoken();
price = price.substring(1, price.length()-2); // remove quotes
} catch (ioexception exception) {
system.err.println("ioexception: " + exception);
}
}
}
當創建了這兩個jsp文件,以及建立了javabean源代碼文件并將其編譯后,你就可以從http://localhost:8080/quote.jsp裝載“quote.jsp”文件以查看結果(假設你沒有更改jswdk設置以使用不同的端口)。這個頁面當然可以做得更加漂亮,但它的確已經達到了預定目的,同時很好地演示了jsp的功能。
新聞熱點
疑難解答