Prediction類(javabean)
package predictions;
import java.io.Serializable;
/**
* Created by AlexY on 2016/6/28.
*/
public class Prediction implements Serializable {
private static final long serialVersionUID = 7570089771880396982L;
private String who; // 人
private String what; //他的prediction
public Prediction() {
}
public String getWhat() {
return what;
}
public void setWhat(String what) {
this.what = what;
}
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
}
Predictions類(javabean)
從predictions.db檔案中讀取常值內容到predictions數組,然後將數組序列化為xml
package predictions;
import javax.servlet.ServletContext;
import java.beans.XMLEncoder;
import java.io.*;
/**
* Created by AlexY on 2016/6/28.
*/
public class Predictions {
private int n = 32;
private Prediction[] predictions;
private ServletContext servletContext;
public Predictions() {
}
// Servlet被用來從war檔案中的text檔案中讀取資料
public ServletContext getServletContext() {
return servletContext;
}
public void setServletContext(ServletContext sctx) {
this.servletContext = sctx;
}
//空實現
public void setPredictions(Prediction[] ps){}
// getPredictions返回一個表示Predictions 數組的xml檔案
public String getPredictions(){
// 檢測是否設定了ServletContext
if ( getServletContext() == null){
return null;
}
// 檢測是否已經讀取了資料
if ( predictions ==null){
populate();
}
// 將Predictions數群組轉換為xml文檔
return toXML();
}
// 將Predictions數群組轉換為xml文檔
private String toXML() {
String xml = null;
ByteArrayOutputStream out = new ByteArrayOutputStream();
XMLEncoder encoder = new XMLEncoder(out);
encoder.writeObject(predictions); //序列化為xml
encoder.close();
xml = out.toString();
return xml;
}
// 將文本中的內容讀取到predictions數組
private void populate() {
String filename = "/WEB-INF/data/predictions.db";
InputStream in = servletContext.getResourceAsStream(filename);
// 將文字檔中的內容讀取到predictions數組
if ( null != in){
// 因為檔案中每條記錄就是一行,而每一行who和what欄位是通過"!"分隔的
InputStreamReader isr = new InputStreamReader(in);
BufferedReader reader = new BufferedReader(isr);
String line = null;
int i = 0;
try {
predictions = new Prediction[n];
while ( null != ( line = reader.readLine())){
String[] parts = line.split("!");
Prediction p = new Prediction();
p.setWho(parts[0]);
p.setWhat(parts[1]);
predictions[i++] = p;
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
predictions.db:
被讀取的文字檔,一條記錄一行,每行的內容都有"!"分隔為兩部分。
Cornelius Tillman!Managed holistic contingency will grow killer action-items.
Conner Kulas!Vision-oriented zero administration time-frame will generate back-end interfaces.
Loraine Ryan!Triple-buffered scalable function will productize visionary infomediaries.
Patricia Zulauf!Reactive radical knowledge base will aggregate extensible vortals.
River Wiza!Face to face client-server pricing structure will whiteboard robust communities.
Jarred Wehner!Future-proofed 5th generation protocol will strategize web-enabled networks.
Emily Roob!Cross-group fresh-thinking encoding will reinvent dot-com systems.
Elvis Ernser!Customizable assymetric database will visualize virtual action-items.
Kathryn Hilpert!User-centric non-volatile open architecture will iterate world-class vortals.
Tanner Dietrich!Enhanced zero tolerance system engine will evolve turn-key deliverables.
Linnie Funk!Distributed dynamic moratorium will iterate magnetic e-commerce.
Emery Ward!Synergistic demand-driven functionalities will visualize compelling vortals.
Craig Leuschke!Robust intermediate extranet will facilitate best-of-breed synergies.
Shayna Lehner!Digitized optimal conglomeration will exploit proactive relationships.
Hollis McCullough!Universal fault-tolerant architecture will synthesize bleeding-edge channels.
Mina Hayes!Cloned assymetric intranet will enable innovative functionalities.
River Friesen!Decentralized 24/7 hub will target robust web-readiness.
Carmel Becker!Synergistic disintermediate policy will expedite back-end experiences.
Bartholome Walsh!Triple-buffered didactic emulation will visualize integrated channels.
Russel Robel!Configurable intangible alliance will scale sexy ROI.
Charlene Mertz!Triple-buffered neutral collaboration will incubate B2B deliverables.
Letitia Pacocha!User-centric multi-state success will transform proactive convergence.
Lottie Marks!Open-source multi-tasking time-frame will monetize rich partnerships.
Kaden Crona!Optional static definition will unleash dynamic e-tailers.
Everardo Lind!De-engineered systematic emulation will deploy out-of-the-box partnerships.
Lilyan Thompson!Synergistic 24/7 website will transition 24/7 methodologies.
Alessia O'Connell!Reactive value-added middleware will engineer next-generation partnerships.
Reymundo Champlin!Self-enabling reciprocal synergy will generate seamless portals.
Immanuel Bergstrom!Assimilated intermediate superstructure will drive vertical methodologies.
Dahlia Robel!Proactive demand-driven open architecture will innovate impactful networks.
Deven Blanda!Balanced clear-thinking utilisation will expedite collaborative initiatives.
Hiram Gulgowski!Versatile tangible application will maximize rich e-business.
predictions.jsp:
顯示產生xml文檔,這裡去掉了html的body等內容。
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ page import="predictions.Prediction" %>
<jsp:useBean id="preds" class="predictions.Predictions" > </jsp:useBean>
<%
String verb = request.getMethod();
// 判斷用戶端http請求的類型
if (!verb.equalsIgnoreCase("GET")){
response.sendError(response.SC_METHOD_NOT_ALLOWED,"只允許GET請求");
}else {
// 設定prediction的ervletContext
preds.setServletContext(application);
// 輸出xml到網頁
out.print(preds.getPredictions());
}
%>
測試:使用curl訪問:
$ curl --request GET http://localhost:8080/predictions.jsp