頁面上一個 Applet 呼叫 Servlet 更新伺服器端物件,另一個 Applet 即時取得最新物件。本文示範「Applet 主動輪詢 Servlet」的簡單實現,並涵蓋 JavaScript ↔ Applet 互呼。
Personpackage exapplet;
public class Person implements Serializable {
private String m_Name; private int m_Age;
// 建構子、getter、自訂 writeObject/readObject
public static void main(String[] args) { /* 本地序列化測試 */ }
}
關鍵: 必須實作 Serializable,並提供無參建構子。
MyServletpublic class MyServlet extends HttpServlet {
private static final String FILE_PATH = "H:\\XSchool\\WorkingRoom\\exapplet\\src\\java.obj";
public void doGet(HttpServletRequest req, HttpServletResponse res) throws IOException {
String act = req.getParameter("Action");
if ("UpdateObject".equals(act)) {
Person p = new Person("Liaoyuan", 26);
new ObjectOutputStream(new FileOutputStream(FILE_PATH)).writeObject(p);
res.getOutputStream().write("Server Java Object Updated OK!".getBytes());
} else if ("GetObject".equals(act)) {
res.setContentType("application/octet-stream");
Person p;
try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream(FILE_PATH))) {
p = (Person) ois.readObject();
} catch (ClassNotFoundException e) { p = new Person(); }
new ObjectOutputStream(res.getOutputStream()).writeObject(p);
}
}
}
以檔案作為簡易儲存介質,實際專案可換成資料庫或快取。
MyApplet (更新) / MyAppletB (讀取)invoke() 方法供 JavaScript 呼叫URLConnection 串接 ServletDataInputStream 讀取純文字回應ObjectInputStream 反序列化物件JSObject.getWindow(this).call("alert", ...) 回傳給網頁web.xml 設定<servlet>
<servlet-name>PostToApplet</servlet-name>
<servlet-class>exapplet.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PostToApplet</servlet-name>
<url-pattern>/exapplet/PostToApplet</url-pattern>
</servlet-mapping>
<APPLET id="obj_applet" code="exapplet.MyApplet" archive="BV7RFD3P.ZIP" width=400 height=300></APPLET>
<input type=button value="CallAppletMethod" onclick="callApplet()">
<script>function callApplet() { obj_applet.invoke(); }</script>
兩個 HTML 分別載入更新用與讀取用 Applet,達成雙向資料流。
Applet 技術已淘汰,現代專案建議改用 REST API + 前端框架 (React/Vue) 或 WebSocket 即時推播。