中国IT动力,最新最全的IT技术教程
最新100篇 | 推荐100篇 | 专题100篇 | 排行榜 | 搜索 | 在线API文档 | 网通镜像
首 页 | 程序开发 | 操作系统 | 软件应用 | 图形图象 | 网络应用 | 精文荟萃 | 教育认证 | 硬件维护 | 未整理篇 | 站长教程
ASP JS PHP工程 ASP.NET 网站建设 UML J2EESUN .NET VC VB VFP 网络维护 数据库 DB2 SQL2000 Oracle Mysql
服务器 Win2000 Office C DreamWeaver FireWorks Flash PhotoShop 上网宝典 CorelDraw 协议大全 网络安全 微软认证
硬件维护  CPU  主板  硬盘  内存  显卡  显示器  键盘鼠标  声卡音箱  打印机  机箱电源  BIOS  网卡  C#  Java  Delphi  vs.net2005
  当前位置:> 程序开发 > Web开发 > JavaScripts > 综合文章
使用JBoss和PostgreSQL-----快速开发EJB和J2EEWebApplication
作者:佚名 时间:2005-02-20 11:03 出处:互连网 责编:chinaitpower
              摘要:使用JBoss和PostgreSQL-----快速开发EJB和J2EEWebApplication
 作者:Han QW, 转载请指明出处 如有不当之处,敬请指出

先安装JSDK,再安装JBoss.
安装JSDK,必须获得一套对应于用户的操作系统的JDK,
我的安装的文件目录是
WINDOWS2000:    d:\s1studio_jdk\j2sdk1.4.1
linux:         /root/s1studio_jdk/j2sdk1.4.1
为了用EJB, 需要一个j2ee-1.3.jar或者j2ee-1.2.jar,
如果安装了Sun One Studio 或者 J2EE (www.sun.com )这个文件已经有.
把这个文件放在classpath路径上.
或者使用jboss-j2ee.jar, 安装JBoss后在$JBoss\client中可找到. 
建议安装Sun One Studio, 用Sun One Studio编译JAVA源程序, 
不用设置classpath, 省去不少过程.

安装JBoss:
把JBoss的压缩包解开,放在任一目录上,
我的安装的文件目录是
/dose/jboss-3.0.4_tomcat-4.1.12 (REDHAT8.0)
E:\jboss-3.0.4_tomcat-4.1.12    (WINDOWS2000)
 WINDOWS2000, linux共用同一套JBoss.

配置JBoss:
启动JBoss需要执行一个脚本文件:
linux:run.sh
WINDOWS对应的是:run.bat

(1)
在JBoss\bin\run.bat (for Windows)开头插入一行
set JAVA_HOME = d:\s1studio_jdk\j2sdk1.4.1
在JBoss\bin\run.sh (for Linux)开头插入一行
JAVA_HOME="/root/s1studio_jdk/j2sdk1.4.1"

或者
(2)设置系统环境变量JAVA_HOME,指向JDK

运行JBoss, run.sh或者run.bat 
当看到启动JBoss的信息时,说明启动了.
服务器简单的测试:
JBoss默认的WEB端口为8080,我们可以在打开一个浏览器输入地址
http://localhost:8080/jmx-console
当在浏览器看到JBoss的信息时,说明安装配置JBoss成功了.



建立下面的目录和文件(注意大小写).

FIRST.EAR
|
|-----META-INF (application.xml)
|
|-----First.jar
|        |-----META-INF (ejb-jar.xml,jboss.xml)
|        `-----Dev
|               |-----First(FirstSession.java, FirstSessionHome.java, FirstSessionBean.java)
|               |-----Delegate(NewDelegate.java)
|               `-----Dao(MysqlDao.java)
|
`-----First.war(index.jsp)
        |
        `-----WEB-INF (jboss-web.xml, web.xml)
                |-----classes
                `-----lib

/*
**
**MysqlDao.java 
**
*/



  1. package Dev.Dao;


  2. import java.sql.Connection;

  3. import java.sql.SQLException;

  4. import java.sql.Statement;

  5. import java.sql.ResultSet;


  6. import javax.naming.InitialContext;

  7. import javax.sql.DataSource;



  8. public class MysqlDao {


  9.     public Connection getConnection() throws Exception {


  10.         InitialContext ctx = new InitialContext();


  11.         DataSource ds = (DataSource) ctx.lookup("java:/PostgresDS");



  12.         Connection conn = null;

  13.         Statement stmt = null;


  14.         try {

  15.             conn = ds.getConnection();


  16.         } catch (SQLException sqlEx) {

  17.             System.out.println("Error connect to pool.");

  18.         }


  19.         return conn;

  20.     }


  21.     public String getName(String id) throws Exception {


  22.         Connection conn = null;

  23.         Statement stmt = null;

  24.         ResultSet rs = null;

  25.         String name = "";


  26.         try {

  27.             conn = getConnection();

  28.             if ( conn !=null )System.out.println("Get conecttion. "+ conn.toString());

  29.             stmt = conn.createStatement();

  30.             if ( stmt !=null )System.out.println("Get Statement. "+ stmt.toString());

  31.             String sql = "SELECT * from users where id = '"+id+"'";

  32.             System.out.println("Sql from getId(): "+sql);

  33.            rs = stmt.executeQuery(sql);

  34.             if ( rs !=null )System.out.println("Get result. ");

  35.            if (rs.next()){

  36.             name = rs.getString("name");

  37.                }


  38.         } catch (Exception sqlEx) {

  39.         System.out.println("Error from getName().");

  40.                 System.out.println("Error from DAO.getName() :" + sqlEx.getMessage());

  41.         }finally {

  42.             if (conn != null) {

  43.                try { conn.close(); } catch (Exception sqlEx) { }

  44.             }

  45.         }

  46.         return name;

  47.     }


  48.     public String getCountry(String id) throws Exception {


  49.         Connection conn = null;

  50.         Statement stmt = null;

  51.         String name = "";


  52.         try {

  53.             conn = getConnection();

  54.             stmt = conn.createStatement();

  55.             String sql = "SELECT * from users where id = '"+id+"'";

  56.             System.out.println("Sql from getCountry(): "+sql);

  57.                java.sql.ResultSet rs = stmt.executeQuery(sql);

  58.                if (rs.next())

  59.             {

  60.                    name = rs.getString("Country");

  61.               }


  62.         } catch (SQLException sqlEx) {

  63.             System.out.println("Error from getCountry().");

  64.         }finally {

  65.             if (conn != null) {

  66.                try { conn.close(); } catch (Exception sqlEx) { }

  67.             }

  68.         }

  69.         return name;

  70.     }


  71. }


/*
**
**NewDelegate.java 
**
*/



  1. package Dev.Delegate;


  2. import java.lang.*;

  3. import Dev.First.*;



  4. public class NewDelegate {


  5.     Dev.First.FirstSession bean = null;

  6.     

  7.     public NewDelegate( ){

  8.        try {

  9.        javax.naming.InitialContext ctx = new javax.naming.InitialContext();

  10.        Object objref = ctx.lookup("ejb/FirstSession");

  11.        Dev.First.FirstSessionHome testBean = (Dev.First.FirstSessionHome)

  12.           javax.rmi.PortableRemoteObject.narrow

  13.           (objref,Dev.First.FirstSessionHome.class);

  14.        bean = testBean.create();

  15.        System.out.println("From JSP");

  16.     } catch (Exception NamingException) {

  17.            NamingException.printStackTrace();

  18.     }

  19.     }

  20.   

  21.     public String Welcome() {

  22.     String msg = "";

  23.     try {

  24.             msg = bean.Welcome();

  25.     } catch (Exception NamingException) { 

  26.            NamingException.printStackTrace();

  27.          }

  28.            return msg;

  29.     }

  30.     

  31.     public String getName(String id) {

  32.     String name = "";

  33.     try {

  34.             name = bean.getName(id);

  35.     } catch (Exception NamingException) { NamingException.printStackTrace();}

  36.         return name;

  37.     } 

  38.     

  39.     public String getCountry(String id) {

  40.     String country = "";

  41.     try {

  42.              country = bean.getCountry(id);

  43.     } catch (Exception NamingException) { NamingException.printStackTrace();}

  44.         return country;

  45.     }        

  46. }

/*
**
**FirstSession.java 
**
*/



  1. package Dev.First;


  2. import java.lang.*;

  3. import java.rmi.RemoteException;

  4. import javax.ejb.CreateException;

  5. import javax.ejb.EJBException;

  6. import javax.ejb.SessionBean;

  7. import javax.ejb.SessionContext;



  8. public interface FirstSession extends javax.ejb.EJBObject{


  9.          public String Welcome() throws java.rmi.RemoteException;

  10.          

  11.          public String getName(String id) throws java.rmi.RemoteException;

  12.          

  13.          public String getCountry(String id) throws java.rmi.RemoteException;


  14. }


/*
**
**FirstSessionHome.java 
**
*/



  1. package Dev.First;


  2. import java.lang.*;

  3. import java.rmi.RemoteException;

  4. import javax.ejb.CreateException;

  5. import javax.ejb.EJBException;

  6. import javax.ejb.SessionBean;

  7. import javax.ejb.SessionContext;



  8. public interface FirstSessionHome extends javax.ejb.EJBHome{


  9. public FirstSession create() throws javax.ejb.CreateException, java.rmi.RemoteException;


  10. }


/*
**
**FirstSessionBean.java 
**
*/



  1. package Dev.First;


  2. import java.rmi.RemoteException;

  3. import javax.ejb.CreateException;

  4. import javax.ejb.EJBException;

  5. import javax.ejb.SessionBean;

  6. import javax.ejb.SessionContext;



  7. public class FirstSessionBean implements SessionBean{


  8. public void ejbCreate() throws CreateException {


  9. }


  10. public String Welcome(){

  11.       String msg="Hello! This My Session Bean From Jboss.";

  12.       System.out.println(msg);

  13.       return msg;

  14. }


  15. public String getName(String id){

  16.       String name = "";

  17.       System.out.println("From bean before getName :"+ name);

  18.       try{

  19.       Dev.Dao.MysqlDao dao = new Dev.Dao.MysqlDao();

  20.       name = dao.getName(id);

  21.       System.out.println("From bean after getName :"+ name);

  22.       }catch(Exception e){ System.out.println(e.getMessage());}

  23.       return name;

  24. }


  25. public String getCountry(String id){

  26.       String country = "";

  27.       try{      

  28.       Dev.Dao.MysqlDao dao = new Dev.Dao.MysqlDao();

  29.       country = dao.getCountry(id);

  30.       }catch(Exception e){ }      

  31.       return country;

  32. }


  33. public void setSessionContext( SessionContext aContext ) throws EJBException {


  34. }


  35. public void ejbActivate() throws EJBException {


  36. }


  37. public void ejbPassivate() throws EJBException {


  38. }


  39. public void ejbRemove() throws EJBException {


  40. }


  41. }




/*Don't put the following lines into index.jsp
**
**index.jsp 
**
*/Don't put the above lines into index.jsp




  1. <%@page language="java" %>


  2. <%


  3.     String msg = "";

  4.     String msg1 = "";

  5.     Dev.Delegate.NewDelegate nn = new Dev.Delegate.NewDelegate();

  6.     if (request.getParameter("id") != null && 

  7.            request.getParameter("id") != ""&& 

  8.            !request.getParameter("id").equals("")){

  9.         String id = request.getParameter("id");

  10.         String name = "";

  11.         Dev.Dao.MysqlDao dao = new Dev.Dao.MysqlDao();

  12.         name = nn.getName(id);      //access database through session bean

  13.         //name = dao.getName(id);   //access database directly

  14.         if(name!= null && !name.equals("")){

  15.             msg1 ="Welcome  " + name +" !     You are from  "+ dao.getCountry(id)+ " .";

  16.         }else{

  17.             msg1 ="Please Check Your ID. : " + id;

  18.         }


  19.     }

  20.     msg = nn.Welcome() ;

  21. %>

  22. <html>


  23. <head>

  24. <title>Welcome</title>

  25. </head>


  26. <body bgcolor="#FFFFCC">

  27. <br> <%= msg %> <br>


  28. <FORM ACTION="index.jsp" method="post">


  29. <P>Your ID:

  30. <INPUT TYPE="TEXT" NAME="id" size = "10"></P>



  31. <P><INPUT TYPE="SUBMIT" NAME="SUBMIT"></P>

  32. </FORM>

  33. <br>

  34. <br>


  35. <%=(msg1 == "")? "":msg1 + "<br> <br> <br>Connect to Database OK." %>


  36. </body>

  37. </html>



<!--不要将此以下5行存入文件
**
**ejb-jar.xml
**
-->不要将此以上5行存入文件, 下同.



  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <!DOCTYPE ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN" 

  3. "http://java.sun.com/dtd/ejb-jar_2_0.dtd">


  4. <ejb-jar>


  5.  <description>First</description>

  6.  <display-name>First</display-name>


  7. <enterprise-beans>


  8. <!-- Session Beans -->

  9. <session id="MyFirstSession">

  10.      <display-name>My First Session Bean</display-name>

  11.      <ejb-name>FirstSession</ejb-name>

  12.      <home>Dev.First.FirstSessionHome</home>

  13.      <remote>Dev.First.FirstSession</remote>

  14.      <ejb-class>Dev.First.FirstSessionBean</ejb-class>

  15.      <session-type>Stateless</session-type>

  16.      <transaction-type>Container</transaction-type>

  17. </session>


  18. </enterprise-beans>


  19. <assembly-descriptor>


  20. </assembly-descriptor>


  21. </ejb-jar>




<!-- 
**
**jboss.xml
**
-->



  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <!DOCTYPE jboss PUBLIC "-//JBoss//DTD JBOSS//EN" "http://www.jboss.org/j2ee/dtd/jboss.dtd">


  3. <jboss>


  4. <enterprise-beans>


  5. <session>

  6. <ejb-name>FirstSession</ejb-name>

  7. <jndi-name>ejbFirstSession</jndi-name>

  8. </session>


  9. </enterprise-beans>


  10. <resource-managers>

  11. </resource-managers>


  12. </jboss>



<!-- 
**
**jboss-web.xml
**
-->



  1. <?xml version="1.0" encoding="UTF-8"?>

  2. <!DOCTYPE jboss-web PUBLIC "-//JBoss//DTD Web Application 2.2//EN" 

  3. "http://www.jboss.org/j2ee/dtd/jboss-web.dtd">


  4. <jboss-web>



  5.     <resource-ref>

  6.         <res-ref-name>jdbcPostgresDS</res-ref-name>

  7.         <res-type>javax.sql.DataSource</res-type>

  8.         <jndi-name>java:/PostgresDS</jndi-name>

  9.     </resource-ref>


  10. </jboss-web>



<!-- 
**
**web.xml
**
-->



  1. <?xml version="1.0" encoding="ISO-8859-1"?>


  2. <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"

  3. "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">


  4. <web-app>


  5. <resource-ref>

  6.   <description>Postgresql driver</description>

  7.   <res-ref-name>jdbcPostgresDS</res-ref-name>

  8.   <res-type>javax.sql.DataSource</res-type>

  9.   <res-auth>Container</res-auth>

  10. </resource-ref>


  11. </web-app>




<!-- 
**
**application.xml
**
-->



  1. <?xml version="1.0" encoding="ISO-8859-1"?>


  2. <application>

  3. <display-name>First</display-name>

  4. <module>

  5. <web>

  6. <web-uri>First.war</web-uri>

  7. <context-root>/First</context-root>

  8. </web>

  9. </module>


  10. <module>

  11. <ejb>First.jar</ejb>

  12. </module>

  13. </application>



编译JAVA源程序,生成class文件.
进入JAVA源程序目录, 运行: 
javac -classpath  %classpath%;%jboss%\server\default\deploy\First.ear\First.jar *.java
或者
javac -classpath  %jboss%\server\default\deploy\First.ear\First.jar;%jboss%\client\jboss-j2ee.jar *.java

Copy 目录First.ear to jboss\server\default\deploy.
打开浏览器输入地址 http://localhost:8080/First

到此, 在浏览器看到:  Hello! This My Session Bean From Jboss. 
说明这个EJB工作了.

如果按按钮, 没反应或出错. 原因没安装配置数据库, 下面安装配置Postgres数据库


For Windows2000
下载 PgSQL731wina1.exe (http://www.postgresql.org),
Finally you will see the next line, you need enter the password for Administrator
最后你将看下一个行,你必须为用户Administrator输入password. 
********************
Enter password of user `.\Administrator':123456
********************

记下此password, 我的口令是123456.

从开始菜单 > Programm > PostgresSQL > Adjust PostgresSQL Configuration file
它将在Wordpad中打开PostgresSQL Configuration文件, 找到下列行,


#
#    Connection Parameters
#
#tcpip_socket = false
#ssl = false

#max_connections = 32
#superuser_reserved_connections = 2

#port = 5432 

修改编辑:
#
#    Connection Parameters
#
tcpip_socket = true
#ssl = false

#max_connections = 32
#superuser_reserved_connections = 2

port = 5432 

接着,保存文件.

起动PostgresSQL服务器:
开始菜单>Programm>PostgresSQL>Utilies>Start PostgresSQL server
起动命令行:
开始菜单>Programm>PostgresSQL>Utilies>Command Shell


执行下列命令,准备数据,
Administrator@SAN /
$ dir

$ cd bin

$ createdb test

$ psql test

test=# create table users
test-# (name varchar(20),
test(# id varchar(20),
test(# country varchar(20));
test=# insert into users values ('Sam', '123', 'China');
test=# insert into users values ('Tom', '321', 'USA');
test=# insert into users values ('Sean', '231', 'France');

test=# select * from users;
 name | id  | country
------+-----+---------
 Sam  | 123 | China
 Tom  | 321 | USA
 Sean | 231 | France
(3 rows)

test=#

到此, 数据准备就绪.



For RedHat:
以root登陆, 执行下列命令,准备数据,
 
mkdir /usr/local/pgsql/data
chown postgres /usr/local/pgsql/data
su - postgres
/usr/local/pgsql/bin/initdb -D /usr/local/pgsql/data

Open and edit /usr/local/pgsql/data/pg_hba.conf

local      all                                          trust
host       all         127.0.0.1     255.255.255.255    trust

just delete #, and save.


[root@localhost root]# su - postgres
-bash-2.05b$ /usr/bin/postmaster -i -D /usr/local/pgsql/data >logfile 2>&1 &
-bash-2.05b$ /usr/bin/createdb test
-bash-2.05b$ /usr/local/pgsql/bin/psql test
test=#    .......the following same as Windows2000

到此, 数据准备就绪.


执行shutdown.bat or shutdown.sh, 停止Jboss Server.

找到JDBC drive.
为了在Jboss中使用连接池,需要拷贝jdbc drive 到Jboss/server/default/deploy ,  在linux 我们能找到/usr/share/pgsql/pgjdbc2.jar,在wondows2000,我们能找到PostgreSQL\usr\share\ postgresql\java\postgresql.jar
把其中之一复制到Jboss/server/default/deploy


配置Jboss

(1) 复制 $Jboss/examples/jca/postgres-service.xml 到 $Jboss/server/default/deploy/

(2) 打开编辑Jboss/server/default/deploy/postgres-service.xml

        <attribute name="JndiName">PostgresDS</attribute>
        <attribute name="ManagedConnectionFactoryProperties">
          <properties>
            <config-property name="ConnectionURL" type="java.lang.String">jdbc:postgresql://localhost/test</config-property>
            <config-property name="DriverClass" type="java.lang.String">org.postgresql.Driver</config-property>
            <!--set these only if you want only default logins, not through JAAS -->
            <config-property name="UserName" type="java.lang.String">Administrator</config-property>
            <config-property name="Password" type="java.lang.String">123456</config-property>
          </properties>

In my example, set Username  Administrator, password  123456 for windows 2000
        set Username  Postgres, no password  for Linux.
在我的例子中,
windows2000,   用户:Administrator,password:123456
Linux(RH8.0),  用户:Postgres, 没有password
因为PostgresSQL和windows2000使用不同的default用户名,所以在linux和window2000中这文件不同.当然,你可以加相同的PostgresSQL用户名和password在linux和window2000中, 这样这文件就相同了.

保存文件.

(3) 打开编辑 $Jboss/server/default/conf/standardjbosscmp-jdbc.xml
找到:
      <datasource>java:/DefaultDS</datasource>
      <datasource-mapping>Hypersonic SQL</datasource-mapping>
加入:
      <datasource>java:/PostgresDS</datasource>
      <datasource-mapping>Postgres</datasource-mapping> 
保存文件.

(4) open and edit $Jboss/server/default/conf/standardjaws.xml
找到:
   <datasource>java:/DefaultDS</datasource>
   <type-mapping>Hypersonic SQL</type-mapping>
   <debug>false</debug>
加入:
   <datasource>java:/PostgresDS</datasource>
   <type-mapping>Postgres</type-mapping>
   <debug>false</debug> 
保存文件.

现在重起JBoss.
打开浏览器输入地址 http://localhost:8080/First
输入ID,按按钮. 
关闭本页
 
首页 | 投资与合作 | 服务条款 | 隐私政策 | 收藏本站 | 设为首页 | 新用户注册 | 免责声明 | 使用帮助
Copyright ©2005-2008 chinaitpower.com All rights reserved. www.chinaitpower.com 版权所有