JBoss-IDE 1.2.2 教程 3

类别:Java 点击:0 评论:0 推荐:

JBoss-IDE 1.2.2 教程 3

Servlet 和 Web-App

只有 EJB 還是不足夠的, 我們要寫一個 Servlet 去使用 EJB 計算斐波納契數列.

 

在項目中新增一個 class, package 輸入 ‘tutorial.web’ 和名稱輸入為 ‘ComputeServlet’. 按下 ‘Browse…’ 在 superclass 新增 ‘HTTPServlet’. 選 ‘Constructors from superclass’ 和 ‘Inherited abstract methods’.

 

按 ‘Finish’ 後應可看到以下畫面.

 

開啟 ‘ComputeServlet.java’ 檔案. 右擊右手方視窗選 ‘Source’ -> ‘Override/Implement Methods…’. 選 ‘init’ 和 ‘doPost’ 方法再按 ‘OK’, 這兩個方法會自動生成.

 

接著加上兩個 private 成員:

private FiboHome home;

private String value;

 

定義 ‘init’ 方法如下, 這是將 EJB Home 接口初始化:

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");

}

}

 

定義 ‘doPost’ 方法如下, 這是得到一個 ‘limit’ 要求後, 新增一個 EJB 實例計算後將結果輸出致 HTML:

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 XDoclet javadoc 相關的標籤. 在 javadoc 裏寫入 ‘@web’ 和按下 CTRL+Space. 應看到自動完成功能. 而其他的屬性亦一樣做法, 代碼如下:

*

* @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 {

 

本文地址:http://com.8s8s.com/it/it16763.htm