EJB3简单Demo

来源:互联网 发布:百度人工智能智库 编辑:程序博客网 时间:2024/05/20 00:15
开发工具及J2EE服务器:MyEclipse8.6 +Jboss 5.0

首先新建一个EJB项目,然后引用EJB所需的JAR包(%JBOSS_HOME%/client 下所有JAR包);

OK,下面开始开发:

package com.ejb.inter;import javax.ejb.Remote;/*标注为远程接口*/@Remotepublic interface HelloWord {    public String sayHello(String str);}


package com.ejb.session;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import javax.annotation.Resource;import javax.ejb.Remote;import javax.ejb.Stateless;import javax.sql.DataSource;import com.ejb.inter.HelloWord;/** * 查找数据源成功,能执行SQL * */@Stateless@Remote({HelloWord.class})public class HelloWordImpl implements HelloWord {    @Resource(mappedName="java:/MySqlDS")     // @Resource 注释来注入来自JNDI 的任何资源。DataSource ds;public String sayHello(String str) {    try {Connection con = ds.getConnection();PreparedStatement ps = con.prepareStatement("select * from Stu_Info");ResultSet set = ps.executeQuery();while(set.next()){System.out.println(set.getInt("stu_id")+"--"+set.getString("stu_name"));}set.close();ps.close();con.close();System.out.println("--------------");} catch (SQLException e) {// TODO Auto-generated catch blocke.printStackTrace();}return str+"欢迎使用EJB";}}

package com.ejb.test;import java.util.Hashtable;import javax.naming.Context;import javax.naming.InitialContext;import javax.rmi.PortableRemoteObject;import com.ejb.inter.HelloWord;public class TestClient {/** * @param args */private static Context context;public static void main(String[] args) {// TODO Auto-generated method stubtry {Context ctx =getInitialContext();Object obj = ctx.lookup("HelloWordImpl/remote");HelloWord hwImpl= (HelloWord)PortableRemoteObject.narrow(obj, HelloWord.class);    System.out.println(hwImpl.sayHello("中国"));} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}                  }    private static Context getInitialContext()throws Exception{if(context==null){Hashtable ht =new Hashtable();ht.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");ht.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");ht.put(Context.PROVIDER_URL, "jnp://localhost:1099");context = new InitialContext(ht);}return context;}}

开发完毕;

然后部署到JBOSS服务器上,运行TestClient.java 后台显示 "中国欢迎使用EJB"

注:在Jboss 后台管理jmx-console中 点击左边菜单Jboss.jca ,点击service=ManagerConnectionPool可以查看当前部署的数据源;