Java EE 远程客户的访问EJB实现实例(GlassFish)

这篇文章简单实现在Java EE7 下实现远程客户端访问Java EE服务器EJB的功能

准备工作:

 

  1. JDK9(jdk-8u92)
  2. netbeans-8.1
  3. Java ee sdk (java_ee_sdk-7u2)
  4. 全部安装完成
  5. netbeans启用Java SE 和 Java EE相关插件
创建Enterprise Application
  1. 服务->服务器右键添加服务服务器->选择GlassFish Server->安装位置选择java_ee_sdk解压缩目录下glassfish4文件夹->输入管理员账户密码(先通过bin目录目录下asadmin 启动服务,浏览器访问localhost:4848 进入管理页面,默认账户密码是admin,changit  进入管理页面,在domain ->Administrator Password 页面下可直接修改密码)
  2. 新建项目->Java EE-> 企业应用程序->项目名称输入 CCEnterpriseApplication->服务器选择添加的GlassFish Server,Java EE 版本 Java EE 7,创建 EJB 模块和Web应用程序模块
 
 
 
 
 
 
 
 
3.创建EJB远端方法接口类库,新建项目->Java->Java类库->名称 CCLibrary。
 
 
 
 
4.创建SessionBean,在CCEnterpriseApplication-ejb项目->新建会话 Bean->EJB 名称 CCSessionBean,包 cc.test.ejb ,回话状态 无状态 ,勾选本地和远程接口,远程方式位于项目选择CCLibrary
 
5.添加EJB 方法 ,在CCLibrary中的CCSessionBeanRemote.java中添加checkConn方法,在CCEnterpriseApplication-ejb项目的cc.test.ejb.CCSessionBeanLocal.java中添加localInfo方法。在CCSessionBean中实现2个方法。后续添加EJB方法可以在EJB的代码右键插入代码->添加 Business 代码 来添加新方法。

 
@Remote  
public interface CCSessionBeanRemote {  
    /** 
     * 检测连接 
     * @return  
     */  
    public String checkConn();  
}  


 

import javax.ejb.Local;  
  
/** 
 * 
 * @author dev 
 */  
@Local  
public interface CCSessionBeanLocal {  
    public String localInfo();  
}  

 

import javax.ejb.Stateless;  
  
/** 
 * 
 * @author dev 
 */  
@Stateless  
public class CCSessionBean implements CCSessionBeanRemote, CCSessionBeanLocal {  
  
    @Override  
    public String checkConn() {  
       return "checkConn";  
    }  
  
    @Override  
    public String localInfo() {  
        return "localInfo";  
    }  
  
}  

 

 
 
6.创建client,新建项目->Java->Java 应用程式->项目名称 CCClient ,添加JFrame,名称LoginJFrame。添加一个JButton和一个JLabel,JButton添加点击事件
 
 
 
  
private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {                                        
        try {           
             Date d = new Date();  
            Hashtable env = new Hashtable();  
           env.put("org.omg.CORBA.ORBInitialHost", "localhost");  
           env.put("org.omg.CORBA.ORBInitialPort", "3700");    
           InitialContext context = new InitialContext(env);             
           Logger.getLogger(LoginJFrame.class.getName()).log(Level.INFO,String.valueOf(new Date().getTime()-d.getTime()));  
            /** 
             * 1."cc.test.ejb.CCSessionBeanRemote" 
             * 2.CCSessionBeanRemote.class.getName() 
             * 3.java:global/CCEnterpriseApplication/CCSessionBean 
             */  
            CCSessionBeanRemote ccSession = (CCSessionBeanRemote)context.lookup(CCSessionBeanRemote.class.getName());  
            Logger.getLogger(LoginJFrame.class.getName()).log(Level.INFO,String.valueOf(new Date().getTime()-d.getTime()));  
            this.messageLabel.setText(ccSession.checkConn());  
            Logger.getLogger(LoginJFrame.class.getName()).log(Level.INFO,String.valueOf(new Date().getTime()-d.getTime()));  
            CCSessionBeanRemote ccSession2 = (CCSessionBeanRemote)context.lookup(CCSessionBeanRemote.class.getName());  
            Logger.getLogger(LoginJFrame.class.getName()).log(Level.INFO,String.valueOf(new Date().getTime()-d.getTime()));  
        } catch (NamingException ex) {  
            Logger.getLogger(LoginJFrame.class.getName()).log(Level.SEVERE, null, ex);  
        }  
    }            

 

 

7.添加库,在CCClient项目中库添加CCLibrary项目,添加gf-client.jar 文件(在 java_ee_sdk-7u2\glassfish4\glassfish\lib\) ,这篇实例客户端和服务器端在同一台机子上。
 
 
 
 
8.启动GlassFish Server,部署CCEnterpriseApplication,运行CCClient ,点击CCClient界面按钮,查看连接结果。如果连接成功可以点击2次按钮,对比运行速度,
可以看出new InitialContext用了1s多,获取EJB 用了3s ,调用EJB返回结果基本在个毫秒(本机无延时),第二次执行new InitialContext已经不耗时间说明没有重新创建,获取EJB对象也没有耗时,说明本地已经有缓存了,跟着Context一起的。
 
五月 29, 2016 1:46:35 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 1197  
五月 29, 2016 1:46:39 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 4502  
五月 29, 2016 1:46:39 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 4548  
五月 29, 2016 1:46:39 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 4564  
五月 29, 2016 1:46:40 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 0  
五月 29, 2016 1:46:40 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 16  
五月 29, 2016 1:46:40 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 32  
五月 29, 2016 1:46:40 上午 cc.test.client.LoginJFrame jButton1MouseClicked  
信息: 32  

 



最后说明下EJB对象名称问题,在GlassFish文档中使用的是第一种,可以正常使用;第二种写法是我个人推荐写法,值和第一种是一样的,在写代码的时候更方便;第三种是Java EE 7Tutorial第32.4Accessing Enterprise Beans介绍使用的方法,在此实例中没有调用成功,使用GlassFish不推荐。
 
 
/** 
             * 1."cc.test.ejb.CCSessionBeanRemote" 
             * 2.CCSessionBeanRemote.class.getName() 
             * 3.java:global/CCEnterpriseApplication/CCSessionBean 
             */  

 

csdn地址:http://blog.csdn.net/qq_31417619/article/details/51527645

两个地方同步更新,都是自己的。

客户端完整代码

package cc.test.client;

import cc.test.ejb.CCSessionBeanRemote;
import java.sql.Time;
import java.util.Date;
import java.util.Hashtable;
import java.util.Locale;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.naming.Context;

/**
 *
 * @author dev
 */
public class LoginJFrame extends javax.swing.JFrame {

    /**
     * Creates new form JFrame
     */
    public LoginJFrame() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        messageLabel = new javax.swing.JLabel();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("EJB连接测试");

        jButton1.setText("连接EJB glassfish");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(129, 129, 129)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(messageLabel)
                            .addComponent(jLabel1)))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(92, 92, 92)
                        .addComponent(jButton1)))
                .addContainerGap(173, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel1)
                .addGap(107, 107, 107)
                .addComponent(messageLabel)
                .addGap(40, 40, 40)
                .addComponent(jButton1)
                .addContainerGap(105, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_jButton1MouseClicked
        try {         
             Date d = new Date();
            Hashtable env = new Hashtable();
            //GlassFish
           env.put("org.omg.CORBA.ORBInitialHost", "localhost");
           env.put("org.omg.CORBA.ORBInitialPort", "3700");  
           //Jboss 
        /*   env.put(Context.URL_PKG_PREFIXES, "org.jboss.ejb.client.naming");
           env.put(Context.INITIAL_CONTEXT_FACTORY,"org.jboss.naming.remote.client.InitialContextFactory");
           env.put(Context.PROVIDER_URL, "http-remoting://localhost:8080");
           env.put(Context.SECURITY_PRINCIPAL,"user");//用户名
           env.put(Context.SECURITY_CREDENTIALS, "user");//密码
           env.put("jboss.naming.client.ejb.context", true);
           */
           Context  context = new InitialContext(env);           
           Logger.getLogger(LoginJFrame.class.getName()).log(Level.WARNING,String.valueOf(new Date().getTime()-d.getTime()));
            /**
             * 1."cc.test.ejb.CCSessionBeanRemote"
             * 2.CCSessionBeanRemote.class.getName()
             * 3.java:global/CCEnterpriseApplication/CCSessionBean
             * 4.CCEnterpriseApplication/CCEnterpriseApplication-ejb/CCSessionBean!cc.test.ejb.CCSessionBeanRemote"
             * 
             */
           // CCSessionBeanRemote ccSession = (CCSessionBeanRemote)context.lookup("CCEnterpriseApplication/CCEnterpriseApplication-ejb/CCSessionBean!"+CCSessionBeanRemote.class.getName());
             CCSessionBeanRemote ccSession = (CCSessionBeanRemote)context.lookup(CCSessionBeanRemote.class.getName());
           Logger.getLogger(LoginJFrame.class.getName()).log(Level.WARNING,String.valueOf(new Date().getTime()-d.getTime()));
            this.messageLabel.setText(ccSession.checkConn());
            Logger.getLogger(LoginJFrame.class.getName()).log(Level.WARNING,String.valueOf(new Date().getTime()-d.getTime()));
           // CCSessionBeanRemote ccSession2 = (CCSessionBeanRemote)context.lookup("CCEnterpriseApplication/CCEnterpriseApplication-ejb/CCSessionBean!"+CCSessionBeanRemote.class.getName());
            Logger.getLogger(LoginJFrame.class.getName()).log(Level.WARNING,String.valueOf(new Date().getTime()-d.getTime()));
        } catch (NamingException ex) {
            Logger.getLogger(LoginJFrame.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_jButton1MouseClicked

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(LoginJFrame.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new LoginJFrame().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel messageLabel;
    // End of variables declaration//GEN-END:variables
}
View Code

 

posted @ 2016-05-29 13:25  NZuoF  阅读(1411)  评论(0编辑  收藏  举报