站内搜索: 请输入搜索关键词

当前页面: 开发资料首页J2EE 专题使用JBoss和PostgreSQL-----快速开发EJB和J2EE Web Application

使用JBoss和PostgreSQL-----快速开发EJB和J2EE Web Application

摘要: 使用JBoss和PostgreSQL-----快速开发EJB和J2EE Web Application
  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. public NewDelegate( ){
  7. try {
  8. javax.naming.InitialContext ctx = new javax.naming.InitialContext();
  9. Object objref = ctx.lookup("ejb/FirstSession");
  10. Dev.First.FirstSessionHome testBean = (Dev.First.FirstSessionHome)
  11. javax.rmi.PortableRemoteObject.narrow
  12. (objref,Dev.First.FirstSessionHome.class);
  13. bean = testBean.create();
  14. System.out.println("From JSP");
  15. } catch (Exception NamingException) {
  16. NamingException.printStackTrace();
  17. }
  18. }
  19. public String Welcome() {
  20. String msg = "";
  21. try {
  22. msg = bean.Welcome();
  23. } catch (Exception NamingException) {
  24. NamingException.printStackTrace();
  25. }
  26. return msg;
  27. }
  28. public String getName(String id) {
  29. String name = "";
  30. try {
  31. name = bean.getName(id);
  32. } catch (Exception NamingException) { NamingException.printStackTrace();}
  33. return name;
  34. }
  35. public String getCountry(String id) {
  36. String country = "";
  37. try {
  38. country = bean.getCountry(id);
  39. } catch (Exception NamingException) { NamingException.printStackTrace();}
  40. return country;
  41. }
  42. }

/*
**
**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. public String getName(String id) throws java.rmi.RemoteException;
  11. public String getCountry(String id) throws java.rmi.RemoteException;
  12. }


/*
**
**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. <head>
  23. Welcome
  24. </head>
  25. <body bgcolor="#FFFFCC">

  26. <%= msg %>
  27. <form ACTION="index.jsp" method="post">
  28. Your ID:

  29. <input TYPE="TEXT" NAME="id" size = "10">

  30. <input TYPE="SUBMIT" NAME="SUBMIT">

  31. </form>


  32. <%=(msg1 == "")? "":msg1 + "


    Connect to Database OK." %>
  33. </body>



  1. <?xml version="1.0" encoding="UTF-8"?>
  2. ejb-jar PUBLIC "-//Sun Microsystems, Inc.//DTD Enterprise JavaBeans 2.0//EN"
  3. "http://java.sun.com/dtd/ejb-jar_2_0.dtd">
  4. First
  5. First
  6. My First Session Bean
  7. FirstSession
  8. Dev.First.FirstSessionHome
  9. Dev.First.FirstSession
  10. class>Dev.First.FirstSessionBeanclass>
  11. Stateless
  12. <transaction-type>Container</transaction-type>




  1. <?xml version="1.0" encoding="UTF-8"?>
  2. jboss PUBLIC "-//JBoss//DTD JBOSS//EN" "http://www.jboss.org/j2ee/dtd/jboss.dtd">
  3. FirstSession
  4. ejbFirstSession



  1. <?xml version="1.0" encoding="UTF-8"?>
  2. jboss-web PUBLIC "-//JBoss//DTD Web Application 2.2//EN"
  3. "http://www.jboss.org/j2ee/dtd/jboss-web.dtd">
  4. jdbcPostgresDS
  5. javax.sql.DataSource
  6. java:/PostgresDS



  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. 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. Postgresql driver
  5. jdbcPostgresDS
  6. javax.sql.DataSource
  7. Container




  1. <?xml version="1.0" encoding="ISO-8859-1"?>
  2. First
  3. First.war
  4. /First
  5. First.jar



编译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

PostgresDS


jdbc:postgresql://localhost/test
org.postgresql.Driver