环境
NetBean8.2, java-8
过程
- 创建Java EE工程。项目名demo1,next。
2. 选择demo1-ejb,创建Bean组件。
编写程序如下。注意如果也生成了EquationLocal的话,可以将其删掉。在Equation上添加@LocalBean即可。
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package com.mid.ejb;
import javax.ejb.Stateless;
import javax.ejb.LocalBean;
/**
*
* @author lenovo
*/
@Stateless
@LocalBean
public class Equation {
private double a, b, c, x1, x2;
private boolean flag;
Equation(){
super();
}
// 自己生成getter和setter
public void sove(){
double delter = b * b - 4 * a * c;
if(delter < 0){
this.flag = false;
}
else{
x1 =(-b + Math.sqrt(delter)) / 2.0;
x2 =(-b - Math.sqrt(delter)) / 2.0;
this.flag = true;
}
}
}
- 选择demo-war,右击新建-》servelet,填写如下信息。
- 右击,插入代码-》企业组件Bean,选择刚刚编写的Bean组件。会生成如下:
@EJB
private Equation equation;
在equation下面加入
private double a = 1.0, b = 2.0, c = 1.0;**// 这里应该用一个Jsp网页或者是小程序
// 定位到该类,提取网页中的abc,求解。**
在
out.println("
Servlet SSolve at " + request.getContextPath() + “
”);
下面添加
this.equation.setA(a);
this.equation.setB(b);
this.equation.setC(c);
this.equation.solve();
if(this.equation.isFlag()){
out.printf("<h2>x1 = " + this.equation.getX1() +
", x2 = " + this.equation.getX2() + "</h2>");
}
else{
out.printf("没有实根!");
}
- 清理并构建demo1-ejb。
- 选择demo1-war-》库-》添加Jar包,找到刚刚的demo1-ejb,向demo1-war中添加demo1-ejb.jar包。
同样清理并构建war。 - 部署demo1-ejb和demo1-war。右击,选择部署。
- 运行SSolve.java。
- 查看结果。