2.上次主要介绍了Web应用程序的开发过程,并给出了调用EJB的方法。这次主要讲述的是EJB3.0标准下的无状态会话EJB的创建。
a.首先创建EJB的bean类,类定义前用@Stateless标注,并实现本地和远程的接口中的业务方法。核心代码如下:
类的定义:
public
String getResult(String str1, String oper, String str2)
throws
NumberFormatException,NullPointerException,ArithmeticException
...
{ String resultStr = null ; if (str1 == null || oper == null || str2 == null ) ... { throw new NullPointerException( " 操作数不能为空! " ); } float num1, num2, result; num1 = 0 ; num2 = 0 ; try ... { num1 = Float.parseFloat(str1); num2 = Float.parseFloat(str2); } catch (NumberFormatException ex) ... { throw new NumberFormatException( " 操作数转换数字失败! " ); } switch (oper.charAt( 0 )) ... { case ' + ' : result = num1 + num2; break ; case ' - ' : result = num1 - num2; break ; case ' * ' : result = num1 * num2; break ; case ' / ' : if (num2 != 0 ) ... { result = num1 / num2; break ; } else ... { throw new ArithmeticException( " 除数不能为0! " ); } default : result = 0 ; } resultStr = Float.toString(result); return resultStr; }
b.在本地接口和远程接口中分别添加业务方法接口,分别用@Local和@Remote标注。
@Local
public
interface
CalculateLocal
...
{ java.lang.String getResult(String str1, String oper, String str2) throws NumberFormatException, NullPointerException,ArithmeticException; }
@Remote
public
interface
CalculateRemote
...
{ java.lang.String getResult(String str1, String oper, String str2) throws NumberFormatException, NullPointerException,ArithmeticException; }
c.当要调用EJB时,首先部署EJB,导入EJB的java文件所在的包,然后导入java.xejb.EJB,最后调用EJB即可。