怎么样使用JBoss和PostgreSQL?

怎么样使用JBoss和PostgreSQL?

作者:HanQW,转载请指明出处如有不当之处,敬请指出

先安装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,
如果安装了SunOneStudio或者J2EE(www.sun.com)这个文件已经有.
把这个文件放在classpath路径上.
或者使用jboss-j2ee.jar,安装JBoss后在$JBoss/client中可找到.
建议安装SunOneStudio,用SunOneStudio编译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(forWindows)开头插入一行
setJAVA_HOME=d:/s1studio_jdk/j2sdk1.4.1
在JBoss/bin/run.sh(forLinux)开头插入一行
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. packageDev.Dao;
  2.  
  3. importjava.sql.Connection;
  4. importjava.sql.SQLException;
  5. importjava.sql.Statement;
  6. importjava.sql.ResultSet;
  7.  
  8. importjavax.naming.InitialContext;
  9. importjavax.sql.DataSource;
  10.  
  11.  
  12. publicclassMysqlDao{
  13.  
  14. publicConnectiongetConnection()throwsException{
  15.  
  16. InitialContextctx=newInitialContext();
  17.  
  18. DataSourceds=(DataSource)ctx.lookup("java:/PostgresDS");
  19.  
  20.  
  21. Connectionconn=null;
  22. Statementstmt=null;
  23.  
  24. try{
  25. conn=ds.getConnection();
  26.  
  27. }catch(SQLExceptionsqlEx){
  28. System.out.println("Errorconnecttopool.");
  29. }
  30.  
  31. returnconn;
  32. }
  33.  
  34. publicStringgetName(Stringid)throwsException{
  35.  
  36. Connectionconn=null;
  37. Statementstmt=null;
  38. ResultSetrs=null;
  39. Stringname="";
  40.  
  41. try{
  42. conn=getConnection();
  43. if(conn!=null)System.out.println("Getconecttion."+conn.toString());
  44. stmt=conn.createStatement();
  45. if(stmt!=null)System.out.println("GetStatement."+stmt.toString());
  46. Stringsql="SELECT*fromuserswhereid='"+id+"'";
  47. System.out.println("SqlfromgetId():"+sql);
  48. rs=stmt.executeQuery(sql);
  49. if(rs!=null)System.out.println("Getresult.");
  50. if(rs.next()){
  51. name=rs.getString("name");
  52. }
  53.  
  54. }catch(ExceptionsqlEx){
  55. System.out.println("ErrorfromgetName().");
  56. System.out.println("ErrorfromDAO.getName():"+sqlEx.getMessage());
  57. }finally{
  58. if(conn!=null){
  59. try{conn.close();}catch(ExceptionsqlEx){}
  60. }
  61. }
  62. returnname;
  63. }
  64.  
  65. publicStringgetCountry(Stringid)throwsException{
  66.  
  67. Connectionconn=null;
  68. Statementstmt=null;
  69. Stringname="";
  70.  
  71. try{
  72. conn=getConnection();
  73. stmt=conn.createStatement();
  74. Stringsql="SELECT*fromuserswhereid='"+id+"'";
  75. System.out.println("SqlfromgetCountry():"+sql);
  76. java.sql.ResultSetrs=stmt.executeQuery(sql);
  77. if(rs.next())
  78. {
  79. name=rs.getString("Country");
  80. }
  81.  
  82. }catch(SQLExceptionsqlEx){
  83. System.out.println("ErrorfromgetCountry().");
  84. }finally{
  85. if(conn!=null){
  86. try{conn.close();}catch(ExceptionsqlEx){}
  87. }
  88. }
  89. returnname;
  90. }
  91.  
  92. }


/*
**
**NewDelegate.java
**
*/
  1. packageDev.Delegate;
  2.  
  3. importjava.lang.*;
  4. importDev.First.*;
  5.  
  6.  
  7. publicclassNewDelegate{
  8.  
  9. Dev.First.FirstSessionbean=null;
  10.  
  11. publicNewDelegate(){
  12. try{
  13. javax.naming.InitialContextctx=newjavax.naming.InitialContext();
  14. Objectobjref=ctx.lookup("ejb/FirstSession");
  15. Dev.First.FirstSessionHometestBean=(Dev.First.FirstSessionHome)
  16. javax.rmi.PortableRemoteObject.narrow
  17. (objref,Dev.First.FirstSessionHome.class);
  18. bean=testBean.create();
  19. System.out.println("FromJSP");
  20. }catch(ExceptionNamingException){
  21. NamingException.printStackTrace();
  22. }
  23. }
  24.  
  25. publicStringWelcome(){
  26. Stringmsg="";
  27. try{
  28. msg=bean.Welcome();
  29. }catch(ExceptionNamingException){
  30. NamingException.printStackTrace();
  31. }
  32. returnmsg;
  33. }
  34.  
  35. publicStringgetName(Stringid){
  36. Stringname="";
  37. try{
  38. name=bean.getName(id);
  39. }catch(ExceptionNamingException){NamingException.printStackTrace();}
  40. returnname;
  41. }
  42.  
  43. publicStringgetCountry(Stringid){
  44. Stringcountry="";
  45. try{
  46. country=bean.getCountry(id);
  47. }catch(ExceptionNamingException){NamingException.printStackTrace();}
  48. returncountry;
  49. }
  50. }

/*
**
**FirstSession.java
**
*/
  1. packageDev.First;
  2.  
  3. importjava.lang.*;
  4. importjava.rmi.RemoteException;
  5. importjavax.ejb.CreateException;
  6. importjavax.ejb.EJBException;
  7. importjavax.ejb.SessionBean;
  8. importjavax.ejb.SessionContext;
  9.  
  10.  
  11. publicinterfaceFirstSessionextendsjavax.ejb.EJBObject{
  12.  
  13. publicStringWelcome()throwsjava.rmi.RemoteException;
  14.  
  15. publicStringgetName(Stringid)throwsjava.rmi.RemoteException;
  16.  
  17. publicStringgetCountry(Stringid)throwsjava.rmi.RemoteException;
  18.  
  19. }


/*
**
**FirstSessionHome.java
**
*/
  1. packageDev.First;
  2.  
  3. importjava.lang.*;
  4. importjava.rmi.RemoteException;
  5. importjavax.ejb.CreateException;
  6. importjavax.ejb.EJBException;
  7. importjavax.ejb.SessionBean;
  8. importjavax.ejb.SessionContext;
  9.  
  10.  
  11. publicinterfaceFirstSessionHomeextendsjavax.ejb.EJBHome{
  12.  
  13. publicFirstSessioncreate()throwsjavax.ejb.CreateException,java.rmi.RemoteException;
  14.  
  15. }


/*
**
**FirstSessionBean.java
**
*/
  1. packageDev.First;
  2.  
  3. importjava.rmi.RemoteException;
  4. importjavax.ejb.CreateException;
  5. importjavax.ejb.EJBException;
  6. importjavax.ejb.SessionBean;
  7. importjavax.ejb.SessionContext;
  8.  
  9.  
  10. publicclassFirstSessionBeanimplementsSessionBean{
  11.  
  12. publicvoidejbCreate()throwsCreateException{
  13.  
  14. }
  15.  
  16. publicStringWelcome(){
  17. Stringmsg="Hello!ThisMySessionBeanFromJboss.";
  18. System.out.println(msg);
  19. returnmsg;
  20. }
  21.  
  22. publicStringgetName(Stringid){
  23. Stringname="";
  24. System.out.println("FrombeanbeforegetName:"+name);
  25. try{
  26. Dev.Dao.MysqlDaodao=newDev.Dao.MysqlDao();
  27. name=dao.getName(id);
  28. System.out.println("FrombeanaftergetName:"+name);
  29. }catch(Exceptione){System.out.println(e.getMessage());}
  30. returnname;
  31. }
  32.  
  33. publicStringgetCountry(Stringid){
  34. Stringcountry="";
  35. try{
  36. Dev.Dao.MysqlDaodao=newDev.Dao.MysqlDao();
  37. country=dao.getCountry(id);
  38. }catch(Exceptione){}
  39. returncountry;
  40. }
  41.  
  42. publicvoidsetSessionContext(SessionContextaContext)throwsEJBException{
  43.  
  44. }
  45.  
  46. publicvoidejbActivate()throwsEJBException{
  47.  
  48. }
  49.  
  50. publicvoidejbPassivate()throwsEJBException{
  51.  
  52. }
  53.  
  54. publicvoidejbRemove()throwsEJBException{
  55.  
  56. }
  57.  
  58. }




/*Don'tputthefollowinglinesintoindex.jsp
**
**index.jsp
**
*/Don'tputtheabovelinesintoindex.jsp

  1. <%@pagelanguage="java"%>
  2.  
  3. <%
  4.  
  5. Stringmsg="";
  6. Stringmsg1="";
  7. Dev.Delegate.NewDelegatenn=newDev.Delegate.NewDelegate();
  8. if(request.getParameter("id")!=null&&
  9. request.getParameter("id")!=""&&
  10. !request.getParameter("id").equals("")){
  11. Stringid=request.getParameter("id");
  12. Stringname="";
  13. Dev.Dao.MysqlDaodao=newDev.Dao.MysqlDao();
  14. name=nn.getName(id);//accessdatabasethroughsessionbean
  15. //name=dao.getName(id);//accessdatabasedirectly
  16. if(name!=null&&!name.equals("")){
  17. msg1="Welcome"+name+"!Youarefrom"+dao.getCountry(id)+".";
  18. }else{
  19. msg1="PleaseCheckYourID.:"+id;
  20. }
  21.  
  22. }
  23. msg=nn.Welcome();
  24. %>
  25. <html>
  26.  
  27. <head>
  28. <title>Welcome</title>
  29. </head>
  30.  
  31. <bodybgcolor="#FFFFCC">
  32. <br><%=msg%><br>
  33.  
  34. <FORMACTION="index.jsp"method="post">
  35.  
  36. <P>YourID:
  37. <INPUTTYPE="TEXT"NAME="id"size="10"></P>
  38.  
  39.  
  40. <P><INPUTTYPE="SUBMIT"NAME="SUBMIT"></P>
  41. </FORM>
  42. <br>
  43. <br>
  44.  
  45. <%=(msg1=="")?"":msg1+"<br><br><br>ConnecttoDatabaseOK."%>
  46.  
  47. </body>
  48. </html>



<!--不要将此以下5行存入文件
**
**ejb-jar.xml
**
-->不要将此以上5行存入文件,下同.
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPEejb-jarPUBLIC"-//SunMicrosystems,Inc.//DTDEnterpriseJavaBeans2.0//EN"
  3. "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
  4.  
  5. <ejb-jar>
  6.  
  7. <description>First</description>
  8. <display-name>First</display-name>
  9.  
  10. <enterprise-beans>
  11.  
  12. <!--SessionBeans-->
  13. <sessionid="MyFirstSession">
  14. <display-name>MyFirstSessionBean</display-name>
  15. <ejb-name>FirstSession</ejb-name>
  16. <home>Dev.First.FirstSessionHome</home>
  17. <remote>Dev.First.FirstSession</remote>
  18. <ejb-class>Dev.First.FirstSessionBean</ejb-class>
  19. <session-type>Stateless</session-type>
  20. <transaction-type>Container</transaction-type>
  21. </session>
  22.  
  23. </enterprise-beans>
  24.  
  25. <assembly-descriptor>
  26.  
  27. </assembly-descriptor>
  28.  
  29. </ejb-jar>




<!--
**
**jboss.xml
**
-->
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPEjbossPUBLIC"-//JBoss//DTDJBOSS//EN""http://www.jboss.org/j2ee/dtd/jboss.dtd">
  3.  
  4. <jboss>
  5.  
  6. <enterprise-beans>
  7.  
  8. <session>
  9. <ejb-name>FirstSession</ejb-name>
  10. <jndi-name>ejbFirstSession</jndi-name>
  11. </session>
  12.  
  13. </enterprise-beans>
  14.  
  15. <resource-managers>
  16. </resource-managers>
  17.  
  18. </jboss>



<!--
**
**jboss-web.xml
**
-->
  1. <?xmlversion="1.0"encoding="UTF-8"?>
  2. <!DOCTYPEjboss-webPUBLIC"-//JBoss//DTDWebApplication2.2//EN"
  3. "http://www.jboss.org/j2ee/dtd/jboss-web.dtd">
  4.  
  5. <jboss-web>
  6.  
  7.  
  8. <resource-ref>
  9. <res-ref-name>jdbcPostgresDS</res-ref-name>
  10. <res-type>javax.sql.DataSource</res-type>
  11. <jndi-name>java:/PostgresDS</jndi-name>
  12. </resource-ref>
  13.  
  14. </jboss-web>



<!--
**
**web.xml
**
-->
  1. <?xmlversion="1.0"encoding="ISO-8859-1"?>
  2.  
  3. <!DOCTYPEweb-appPUBLIC"-//SunMicrosystems,Inc.//DTDWebApplication2.2//EN"
  4. "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
  5.  
  6. <web-app>
  7.  
  8. <resource-ref>
  9. <description>Postgresqldriver</description>
  10. <res-ref-name>jdbcPostgresDS</res-ref-name>
  11. <res-type>javax.sql.DataSource</res-type>
  12. <res-auth>Container</res-auth>
  13. </resource-ref>
  14.  
  15. </web-app>




<!--
**
**application.xml
**
-->
  1. <?xmlversion="1.0"encoding="ISO-8859-1"?>
  2.  
  3. <application>
  4. <display-name>First</display-name>
  5. <module>
  6. <web>
  7. <web-uri>First.war</web-uri>
  8. <context-root>/First</context-root>
  9. </web>
  10. </module>
  11.  
  12. <module>
  13. <ejb>First.jar</ejb>
  14. </module>
  15. </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.eartojboss/server/default/deploy.
打开浏览器输入地址http://localhost:8080/First

到此,在浏览器看到:Hello!ThisMySessionBeanFromJboss.
说明这个EJB工作了.

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


ForWindows2000
下载PgSQL731wina1.exe(http://www.postgresql.org),
Finallyyouwillseethenextline,youneedenterthepasswordforAdministrator
最后你将看下一个行,你必须为用户Administrator输入password.
********************
Enterpasswordofuser`./Administrator':123456
********************

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

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


#
#ConnectionParameters
#
#tcpip_socket=false
#ssl=false

#max_connections=32
#superuser_reserved_connections=2

#port=5432

修改编辑:
#
#ConnectionParameters
#
tcpip_socket=true
#ssl=false

#max_connections=32
#superuser_reserved_connections=2

port=5432

接着,保存文件.

起动PostgresSQL服务器:
开始菜单>Programm>PostgresSQL>Utilies>StartPostgresSQLserver
起动命令行:
开始菜单>Programm>PostgresSQL>Utilies>CommandShell


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

$cdbin

$createdbtest

$psqltest

test=#createtableusers
test-#(namevarchar(20),
test(#idvarchar(20),
test(#countryvarchar(20));
test=#insertintousersvalues('Sam','123','China');
test=#insertintousersvalues('Tom','321','USA');
test=#insertintousersvalues('Sean','231','France');

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

test=#

到此,数据准备就绪.



ForRedHat:
以root登陆,执行下列命令,准备数据,

mkdir/usr/local/pgsql/data
chownpostgres/usr/local/pgsql/data
su-postgres
/usr/local/pgsql/bin/initdb-D/usr/local/pgsql/data

Openandedit/usr/local/pgsql/data/pg_hba.conf

localalltrust
hostall127.0.0.1255.255.255.255trust

justdelete#,andsave.


[root@localhostroot]#su-postgres
-bash-2.05b$/usr/bin/postmaster-i-D/usr/local/pgsql/data>logfile2>&1&
-bash-2.05b$/usr/bin/createdbtest
-bash-2.05b$/usr/local/pgsql/bin/psqltest
test=#.......thefollowingsameasWindows2000

到此,数据准备就绪.


执行shutdown.batorshutdown.sh,停止JbossServer.

找到JDBCdrive.
为了在Jboss中使用连接池,需要拷贝jdbcdrive到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

<attributename="JndiName">PostgresDS</attribute>
<attributename="ManagedConnectionFactoryProperties">
<properties>
<config-propertyname="ConnectionURL"type="java.lang.String">jdbc:postgresql://localhost/test</config-property>
<config-propertyname="DriverClass"type="java.lang.String">org.postgresql.Driver</config-property>
<!--settheseonlyifyouwantonlydefaultlogins,notthroughJAAS-->
<config-propertyname="UserName"type="java.lang.String">Administrator</config-property>
<config-propertyname="Password"type="java.lang.String">123456</config-property>
</properties>

Inmyexample,setUsernameAdministrator,password123456forwindows2000
setUsernamePostgres,nopasswordforLinux.
在我的例子中,
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>HypersonicSQL</datasource-mapping>
加入:
<datasource>java:/PostgresDS</datasource>
<datasource-mapping>Postgres</datasource-mapping>
保存文件.

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

现在重起JBoss.
打开浏览器输入地址http://localhost:8080/First
输入ID,按按钮.