怎么样使用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
**
*/
- packageDev.Dao;
- importjava.sql.Connection;
- importjava.sql.SQLException;
- importjava.sql.Statement;
- importjava.sql.ResultSet;
- importjavax.naming.InitialContext;
- importjavax.sql.DataSource;
- publicclassMysqlDao{
- publicConnectiongetConnection()throwsException{
- InitialContextctx=newInitialContext();
- DataSourceds=(DataSource)ctx.lookup("java:/PostgresDS");
- Connectionconn=null;
- Statementstmt=null;
- try{
- conn=ds.getConnection();
- }catch(SQLExceptionsqlEx){
- System.out.println("Errorconnecttopool.");
- }
- returnconn;
- }
- publicStringgetName(Stringid)throwsException{
- Connectionconn=null;
- Statementstmt=null;
- ResultSetrs=null;
- Stringname="";
- try{
- conn=getConnection();
- if(conn!=null)System.out.println("Getconecttion."+conn.toString());
- stmt=conn.createStatement();
- if(stmt!=null)System.out.println("GetStatement."+stmt.toString());
- Stringsql="SELECT*fromuserswhereid='"+id+"'";
- System.out.println("SqlfromgetId():"+sql);
- rs=stmt.executeQuery(sql);
- if(rs!=null)System.out.println("Getresult.");
- if(rs.next()){
- name=rs.getString("name");
- }
- }catch(ExceptionsqlEx){
- System.out.println("ErrorfromgetName().");
- System.out.println("ErrorfromDAO.getName():"+sqlEx.getMessage());
- }finally{
- if(conn!=null){
- try{conn.close();}catch(ExceptionsqlEx){}
- }
- }
- returnname;
- }
- publicStringgetCountry(Stringid)throwsException{
- Connectionconn=null;
- Statementstmt=null;
- Stringname="";
- try{
- conn=getConnection();
- stmt=conn.createStatement();
- Stringsql="SELECT*fromuserswhereid='"+id+"'";
- System.out.println("SqlfromgetCountry():"+sql);
- java.sql.ResultSetrs=stmt.executeQuery(sql);
- if(rs.next())
- {
- name=rs.getString("Country");
- }
- }catch(SQLExceptionsqlEx){
- System.out.println("ErrorfromgetCountry().");
- }finally{
- if(conn!=null){
- try{conn.close();}catch(ExceptionsqlEx){}
- }
- }
- returnname;
- }
- }
/*
**
**NewDelegate.java
**
*/
- packageDev.Delegate;
- importjava.lang.*;
- importDev.First.*;
- publicclassNewDelegate{
- Dev.First.FirstSessionbean=null;
- publicNewDelegate(){
- try{
- javax.naming.InitialContextctx=newjavax.naming.InitialContext();
- Objectobjref=ctx.lookup("ejb/FirstSession");
- Dev.First.FirstSessionHometestBean=(Dev.First.FirstSessionHome)
- javax.rmi.PortableRemoteObject.narrow
- (objref,Dev.First.FirstSessionHome.class);
- bean=testBean.create();
- System.out.println("FromJSP");
- }catch(ExceptionNamingException){
- NamingException.printStackTrace();
- }
- }
- publicStringWelcome(){
- Stringmsg="";
- try{
- msg=bean.Welcome();
- }catch(ExceptionNamingException){
- NamingException.printStackTrace();
- }
- returnmsg;
- }
- publicStringgetName(Stringid){
- Stringname="";
- try{
- name=bean.getName(id);
- }catch(ExceptionNamingException){NamingException.printStackTrace();}
- returnname;
- }
- publicStringgetCountry(Stringid){
- Stringcountry="";
- try{
- country=bean.getCountry(id);
- }catch(ExceptionNamingException){NamingException.printStackTrace();}
- returncountry;
- }
- }
/*
**
**FirstSession.java
**
*/
- packageDev.First;
- importjava.lang.*;
- importjava.rmi.RemoteException;
- importjavax.ejb.CreateException;
- importjavax.ejb.EJBException;
- importjavax.ejb.SessionBean;
- importjavax.ejb.SessionContext;
- publicinterfaceFirstSessionextendsjavax.ejb.EJBObject{
- publicStringWelcome()throwsjava.rmi.RemoteException;
- publicStringgetName(Stringid)throwsjava.rmi.RemoteException;
- publicStringgetCountry(Stringid)throwsjava.rmi.RemoteException;
- }
/*
**
**FirstSessionHome.java
**
*/
- packageDev.First;
- importjava.lang.*;
- importjava.rmi.RemoteException;
- importjavax.ejb.CreateException;
- importjavax.ejb.EJBException;
- importjavax.ejb.SessionBean;
- importjavax.ejb.SessionContext;
- publicinterfaceFirstSessionHomeextendsjavax.ejb.EJBHome{
- publicFirstSessioncreate()throwsjavax.ejb.CreateException,java.rmi.RemoteException;
- }
/*
**
**FirstSessionBean.java
**
*/
- packageDev.First;
- importjava.rmi.RemoteException;
- importjavax.ejb.CreateException;
- importjavax.ejb.EJBException;
- importjavax.ejb.SessionBean;
- importjavax.ejb.SessionContext;
- publicclassFirstSessionBeanimplementsSessionBean{
- publicvoidejbCreate()throwsCreateException{
- }
- publicStringWelcome(){
- Stringmsg="Hello!ThisMySessionBeanFromJboss.";
- System.out.println(msg);
- returnmsg;
- }
- publicStringgetName(Stringid){
- Stringname="";
- System.out.println("FrombeanbeforegetName:"+name);
- try{
- Dev.Dao.MysqlDaodao=newDev.Dao.MysqlDao();
- name=dao.getName(id);
- System.out.println("FrombeanaftergetName:"+name);
- }catch(Exceptione){System.out.println(e.getMessage());}
- returnname;
- }
- publicStringgetCountry(Stringid){
- Stringcountry="";
- try{
- Dev.Dao.MysqlDaodao=newDev.Dao.MysqlDao();
- country=dao.getCountry(id);
- }catch(Exceptione){}
- returncountry;
- }
- publicvoidsetSessionContext(SessionContextaContext)throwsEJBException{
- }
- publicvoidejbActivate()throwsEJBException{
- }
- publicvoidejbPassivate()throwsEJBException{
- }
- publicvoidejbRemove()throwsEJBException{
- }
- }
/*Don'tputthefollowinglinesintoindex.jsp
**
**index.jsp
**
*/Don'tputtheabovelinesintoindex.jsp
- <%@pagelanguage="java"%>
- <%
- Stringmsg="";
- Stringmsg1="";
- Dev.Delegate.NewDelegatenn=newDev.Delegate.NewDelegate();
- if(request.getParameter("id")!=null&&
- request.getParameter("id")!=""&&
- !request.getParameter("id").equals("")){
- Stringid=request.getParameter("id");
- Stringname="";
- Dev.Dao.MysqlDaodao=newDev.Dao.MysqlDao();
- name=nn.getName(id);//accessdatabasethroughsessionbean
- //name=dao.getName(id);//accessdatabasedirectly
- if(name!=null&&!name.equals("")){
- msg1="Welcome"+name+"!Youarefrom"+dao.getCountry(id)+".";
- }else{
- msg1="PleaseCheckYourID.:"+id;
- }
- }
- msg=nn.Welcome();
- %>
- <html>
- <head>
- <title>Welcome</title>
- </head>
- <bodybgcolor="#FFFFCC">
- <br><%=msg%><br>
- <FORMACTION="index.jsp"method="post">
- <P>YourID:
- <INPUTTYPE="TEXT"NAME="id"size="10"></P>
- <P><INPUTTYPE="SUBMIT"NAME="SUBMIT"></P>
- </FORM>
- <br>
- <br>
- <%=(msg1=="")?"":msg1+"<br><br><br>ConnecttoDatabaseOK."%>
- </body>
- </html>
<!--不要将此以下5行存入文件
**
**ejb-jar.xml
**
-->不要将此以上5行存入文件,下同.
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEejb-jarPUBLIC"-//SunMicrosystems,Inc.//DTDEnterpriseJavaBeans2.0//EN"
- "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
- <ejb-jar>
- <description>First</description>
- <display-name>First</display-name>
- <enterprise-beans>
- <!--SessionBeans-->
- <sessionid="MyFirstSession">
- <display-name>MyFirstSessionBean</display-name>
- <ejb-name>FirstSession</ejb-name>
- <home>Dev.First.FirstSessionHome</home>
- <remote>Dev.First.FirstSession</remote>
- <ejb-class>Dev.First.FirstSessionBean</ejb-class>
- <session-type>Stateless</session-type>
- <transaction-type>Container</transaction-type>
- </session>
- </enterprise-beans>
- <assembly-descriptor>
- </assembly-descriptor>
- </ejb-jar>
<!--
**
**jboss.xml
**
-->
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEjbossPUBLIC"-//JBoss//DTDJBOSS//EN""http://www.jboss.org/j2ee/dtd/jboss.dtd">
- <jboss>
- <enterprise-beans>
- <session>
- <ejb-name>FirstSession</ejb-name>
- <jndi-name>ejbFirstSession</jndi-name>
- </session>
- </enterprise-beans>
- <resource-managers>
- </resource-managers>
- </jboss>
<!--
**
**jboss-web.xml
**
-->
- <?xmlversion="1.0"encoding="UTF-8"?>
- <!DOCTYPEjboss-webPUBLIC"-//JBoss//DTDWebApplication2.2//EN"
- "http://www.jboss.org/j2ee/dtd/jboss-web.dtd">
- <jboss-web>
- <resource-ref>
- <res-ref-name>jdbcPostgresDS</res-ref-name>
- <res-type>javax.sql.DataSource</res-type>
- <jndi-name>java:/PostgresDS</jndi-name>
- </resource-ref>
- </jboss-web>
<!--
**
**web.xml
**
-->
- <?xmlversion="1.0"encoding="ISO-8859-1"?>
- <!DOCTYPEweb-appPUBLIC"-//SunMicrosystems,Inc.//DTDWebApplication2.2//EN"
- "http://java.sun.com/j2ee/dtds/web-app_2_2.dtd">
- <web-app>
- <resource-ref>
- <description>Postgresqldriver</description>
- <res-ref-name>jdbcPostgresDS</res-ref-name>
- <res-type>javax.sql.DataSource</res-type>
- <res-auth>Container</res-auth>
- </resource-ref>
- </web-app>
<!--
**
**application.xml
**
-->
- <?xmlversion="1.0"encoding="ISO-8859-1"?>
- <application>
- <display-name>First</display-name>
- <module>
- <web>
- <web-uri>First.war</web-uri>
- <context-root>/First</context-root>
- </web>
- </module>
- <module>
- <ejb>First.jar</ejb>
- </module>
- </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,按按钮.
本文地址:http://www.45fan.com/dnjc/69640.html