一个简单的javaee企业应用程序(二)

 

2.上次主要介绍了Web应用程序的开发过程,并给出了调用EJB的方法。这次主要讲述的是EJB3.0标准下的无状态会话EJB的创建。

a.首先创建EJB的bean类,类定义前用@Stateless标注,并实现本地和远程的接口中的业务方法。核心代码如下:

类的定义:

@Stateless
public   class  CalculateBean  implements  com.lilijun.calculator.bean.CalculateRemote, com.lilijun.calculator.bean.CalculateLocal  { 业务方法的实现,对传进来的两个操作数进行计算,如果有错则抛出异常:

 

 

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即可。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值