Java EE 遠程客戶的訪問EJB實現實例(GlassFish)

這篇文章簡單實如今Java EE7 下實現遠程客戶端訪問Java EE服務器EJB的功能

準備工做:html

 

  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.4 Accessing 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/51527645java

兩個地方同步更新,都是本身的。git

客戶端完整代碼sql

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
相關文章
相關標籤/搜索