今天使用NetBeans5.5和Sun Java System Application Server 创建了一个很简单的企业应用程序。包含一个EJB模块和一个Web应用程序模块。实现的功能是加减,乘除的运算,如果出现错误,例如数字转换失败,除数为0将跳转到错误页面,并将错误信息输出到页面上。
实现方法:用无状态的EJB实现运算的核心方法,然后在Web应用程序中使用Servlet调用EJB,完成计算的任务。jsp页面负责和用户交互,例如用户输入操作数,显示运算结果等等。如果出现错误,由Servlet控制,跳转到错误页面。
实现步骤:
1. 建立Web应用程序的组件,主要是index.jsp,CalculateServlet.java,error.jsp的编写。
首先,在index.jsp中接收servlet传过来的参数,显示在页面中,主要是两个操作数的值,运算符,运算结果。第一次进入该页面时参数均为null,所以使用默认值代替。
其次,在CalculateServlet.java中接收index.jsp传过来的计算信息,调用EJB的本地接口的计算方法,完成计算。核心代码如下所示:
private CalculateLocal calculator; // 调用本地EJB接口
/** */ /** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
* @param request servlet request
* @param response servlet response
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException ... {
response.setContentType("text/html;charset=UTF-8");
request.setCharacterEncoding("UTF-8");
String str1 = (String)request.getParameter("num1");//从JSP页面中获得两个操作数和运算符
String oper = (String)request.getParameter("operator");
String str2 = (String)request.getParameter("num2");
String strResult = null;
try ...{
strResult = calculator.getResult(str1,oper,str2);
request.setAttribute("result",strResult);
request.setAttribute("num1",str1);
request.setAttribute("operator",oper);
request.setAttribute("num2",str2);
/**//*如果使用response的跳转路径方法,则无法保存request对象中设置过的属性
*那么JSP页面就无法收到结果
*/
request.getRequestDispatcher("index.jsp").forward(request,response);
} catch(Exception e) ...{
request.getRequestDispatcher("error.jsp?errorType="+e.getCause().getMessage()).forward(request,response);
}
}
最后,编写error.jsp,收到错误信息errorType,并显示在页面中。
至此Web应用程序部分编写结束。需要强调的是:
a. request对象设置字符编码,否则JSP页面将显示乱码。
b.跳转页面时 不能使用response.sendRedirect,因为要传送参数,而response.sendRedirect方法无法保存request对象的属性和参数。
c.获得异常的信息,使用e.getCause().getMessage()才能获得信息,如果使用e.getMessage()为null,具体原因尚未查出。
d.调用EJB。使用EJB3.0的方法,首先创建一个EJB本地接口的局部变量,使用@EJB(name="CalculateLocal")标注即可。然后就可以直接使用该接口的方法。其中的查询,实例化均已自动完成。