JBoss-IDE 1.2.2 教程 4:
'ComputeServlet' 的完整的代碼如下:
package tutorial.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import tutorial.interfaces.Fibo;
import tutorial.interfaces.FiboHome;
/**
* @author John Doe
*
* @web.servlet name = "ComputeServlet"
* display-name = "Computation Servlet"
* description = "Servlet that compute Fibonacci suite"
*
* @web.servlet-mapping url-pattern = "/Compute"
*
* @web.env-entry name = "Title"
* type = "java.lang.String"
* value = "Fibonacci computation"
* description = "Example of Env Entry"
*
* @web.ejb-ref name = "ejb/Fibo"
* type = "Session"
* home = "tutorial.interfaces.FiboHome"
* remote = "tutorial.interfaces.Fibo"
* description = "Reference to the Fibo EJB"
*
* @jboss.ejb-ref-jndi ref-name = "ejb/Fibo"
* jndi-name = "ejb/tutorial/Fibo"
*/
public class ComputeServlet extends HttpServlet {
private FiboHome home;
private String value;
public ComputeServlet() {
super();
}
public void init() throws ServletException {
try {
Context context = new InitialContext();
value = (String) context.lookup("java:/comp/env/Title");
Object ref = context.lookup("java:/comp/env/ejb/Fibo");
home = (FiboHome) PortableRemoteObject.narrow(ref, FiboHome.class);
} catch (Exception e) {
throw new ServletException("Lookup of java:/comp/env/ failed");
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html><head><title>");
out.println(value);
out.println("</title></head>");
out.println("<body>");
out.println("<h1>");
out.println(value);
out.println("</h1>");
try {
Fibo bean = home.create();
int limit = 0;
String value = request.getParameter("limit");
if (value != null) {
try {
limit = Integer.parseInt(value);
}
catch (Exception e) {
}
}
double[] result = bean.compute(limit);
bean.remove();
out.println("<p>");
out.print("The ");
out.print(limit);
out.print(" first Fibonacci numbers ");
for (int i = 0; i < result.length; i++) {
out.println("<br>");
out.println(i);
out.println(" : ");
out.println(result[i]);
}
out.println("</p>");
} catch (Exception e) {
out.println(e.getMessage());
e.printStackTrace(out);
} finally {
out.println("</body></html>");
out.close();
}
}
}
生成 Servlet 相關檔案:
要生成 Web 的配置文檔, 我們首先要設置一些 XDoclet 的設定. 就好像 EJB 一樣, 讓我們來定義 Web 自動生成的設定.
右擊選目選 ‘Properties’ -> ‘XDoclet configurations’, 在左上的視窗右擊選 ‘Add’, 填入 ‘Web’ 然後按 ‘OK’, 這樣就成功新增一個 XDoclet ‘Web’ 的生成設定.
接著選 ‘Web’, 在左下方視窗右擊選 ‘Add Doclet’ -> ‘webdoclet’, 再按 ‘OK’. 再在左手方的視窗的 ‘webdoclet’ 設置中設定 選 ‘destDir’ 填入 ‘src/WEB-INF’. 現在 XDoclet 的 ‘webdoclet’ 設定會在 ‘src/WEB-INF’ 資料夾中產生 Web 的檔案.