Use JBoss and PostgreSQL ----- Rapid Development EJB and J2EE Web Application

xiaoxiao2021-03-06  74

Author: Han QW, reproduced, please indicate the source if inappropriate, please point out

Install JSDK first, then install JBoss.

Install JSDK, you must get a JDK that corresponds to the user's operating system.

My installation file directory is

Windows2000: d: /s1studio_jdk/j2sdk1.4.1

Linux: /root/s1studio_jdk/j2sdk1.4.1

In order to use EJB, you need a J2EE-1.3.jar or J2EE-1.2.jar,

If Sun One Studio or J2EE (www.sun.com) is installed.

Place this file on the ClassPath path.

Or use jboss-j2ee.jar, after installing JBoss, you can find in $ JBOSS / CLIENT.

It is recommended to install Sun One Studio, compile the Java source program with Sun One Studio,

Do not set ClassPath, save a lot of processes.

Install JBoss:

Unlock the JBoss's compressed package, put it on either directory,

My installation file directory is

/DOSE/Jboss-3.0.4_tomcat-4.1.12 (redhat8.0)

E: /JBOSS-3.0.4_Tomcat-4.1.12 (Windows2000)

Windows2000, Linux share the same set of JBoss.

Configure jboss:

Start JBoss needs to perform a script file:

Linux: run.sh

Windows corresponds: run.bat

(1)

Insert a line in jboss / bin / run.bat (for windows)

SET JAVA_HOME = D: /s1studio_jdk/j2sdk1.4.1

Insert a line in jboss / bin / run.sh (for linux)

Java_home = "/ root / s1studio_jdk / j2sdk1.4.1"

or

(2) Set the system environment variable java_home, point to JDK

Run jboss, run.sh or run.bat

When you see the information that starts JBOSS, the description is started.

Server simple test:

JBoss default web port is 8080, we can open a browser input address

Http: // localhost: 8080 / jmx-console

When you see the JBoss information in the browser, the installation configuration JBoss is successful.

Establish the following directory and files (accounting case).

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

**

* /

package Dev.Dao; import java.sql.Connection; import java.sql.SQLException; import java.sql.Statement; import java.sql.ResultSet; import javax.naming.InitialContext; import javax.sql.DataSource; public class MysqlDao {public Connection getConnection () throws Exception {InitialContext ctx = new InitialContext (); DataSource ds = (DataSource) ctx.lookup ( "java: / PostgresDS"); Connection conn = null; Statement stmt = null; try {conn = ds .getConnection ();} catch (SQLException sqlEx) {System.out.println ( "Error connect to pool.");} return conn;} public String getName (String id) throws Exception {Connection conn = null; Statement stmt = NULL; ResultSet RS = NULL; String Name = ""; try {conn = getConnection (); if (conn! = null) System.out.println ("Get CONECTTION." Conn.toString ()); STMT = conn .CREATESTATEMENT (); IF (stmt! = null) System.out.Println ("get stating." stmt.toString ()); string sql = "select * from users where id = '" ID ""; system.out.println ("SQL from getId ():" SQL); rs = stmt.executeQuery (SQL); if (RS! = Null) System.out.println ("Get Result)); if (rs.next ()) {Name = rs.getstring ("name");}}}} catch ("Error from getname ()."); System.out.Println ("Error from Dao.getname () "

SQLEX.GetMessage ());} finally {if (conn! = Null) {Try {conn.close ();} catCH (Exception SQLEX) {}}}}}} Return Name;} PUBLIC STRING GETCOUNTRY (STRING ID) THROWS Exception {Connection conn = null; STATEMT = NULL; STRING NAME = ""; try {conn = getConnection (); stmt = conn.createstatement (); string sql = "select * from users where id = '" id "' "; System.out.println (" SQL from getCountry (): " SQL); java.sql.resultset = stmt.executeQuery (SQL); if (rs.next ()) {name = rs.getstring (" ");}}} Catch (SQLEXCEPTION SQLEX) {system.out.println (" Error from getCountry (). ");} Finally {if (conn! = Null) {TRY {Conn.close ();} catch EXCEPTION SQLEX) {}}} return name; } / *

**

** NewdeLegate.java

**

* /

package Dev.Delegate; import java.lang *;. import Dev.First *;. public class NewDelegate {Dev.First.FirstSession bean = null; public NewDelegate () {try {javax.naming.InitialContext ctx = new javax.naming .InitialContext (); Object objref = ctx.lookup ( "ejb / FirstSession"); Dev.First.FirstSessionHome testBean = (Dev.First.FirstSessionHome) javax.rmi.PortableRemoteObject.narrow (objref, Dev.First.FirstSessionHome.class ); Bean = testbean.create (); system.out.println ("from jsp");} catch (exception namingexception) {namingexception.printStackTrace ();}} public string welcome () {string msg = ""; try {msg = bean.Welcome ();} catch (Exception NamingException) {NamingException.printStackTrace ();} return msg;} public String getName (String id) {String name = ""; try {name = bean.getName (id } tch (Exception NamingException) {NamingException.printStackTrace ();} return name;} public String getCountry (String id) {String country = ""; try {country = bean.getCountry (id);} catch (Exception NamingException) {NamingException .printstacktrace ();} return country;}} / *

**

** FirstSession.java

**

* /

package Dev.First; import java.lang *;. import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; public interface FirstSession extends javax.ejb.EJBObject {public String Welcome () throws java.rmi.RemoteException; public String getName (String id) throws java.rmi.RemoteException; public String getCountry (String id) throws java.rmi.RemoteException;} / *

**

** FirstSessionHome.java

**

* /

package Dev.First; import java.lang *;. import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; public interface FirstSessionHome Extends javax.ejb.ejbhome {public firstsession create () throws javax.ejb.createException, java.rmi.RemoteException;}

/ *

**

** FirstSessionBean.java

**

* /

package Dev.First; import java.rmi.RemoteException; import javax.ejb.CreateException; import javax.ejb.EJBException; import javax.ejb.SessionBean; import javax.ejb.SessionContext; public class FirstSessionBean implements SessionBean {public void ejbCreate ( ) throws CreateException {} public String Welcome () {String msg = "Hello This My Session Bean From Jboss!."; System.out.println (msg); return msg;} public String getName (String id) {String name = ""; System.out.println ("from bean before getname:" Name); try {dev.dao.mysqldao Dao = new dev.dao.mysqldao (); name = DAO.GETNAME (ID); system.out .println ("from bean after getname:" Name);} catch (exception e) {system.out.println (E.GetMessage ());} return name;} public string getCountry (String id) {string country = ""; Try {dev.dao.mysqldao DAO = new dev.dao.mysqldao (); country = DAO.GETCOUNTRY (ID);} catCH (Exception E) {} Return C ountry;} public void setSessionContext (SessionContext aContext) throws EJBException {} public void ejbActivate () throws EJBException {} public void ejbPassivate () throws EJBException {} public void ejbRemove () throws EJBException {}} / * Do not put the following Lines INTO INDEX.JSP

**

** index.jsp

**

* / Don't put the Above lines INTO INDEX.JSP

<% @ page language = "java"%> <% string msg = ""; string msg1 = "; dev.delegate.newdelegate nn = new dev.dlegate.newdeLegate (); if (Request.GetParameter) )! = Null && request.getParameter ("ID")! = "" &&! Request.getParameter ("ID"). Equals (")) {string id = request.getParameter (" id "); string name = ""; Dev.dao.mysqldao Dao = new dev.dao.mysqldao (); name = nn.getname (ID); // access database through session bean // name = DAO.GETNAME (ID); // access data Directly if (name! = null&&! name.equals (")) {msg1 =" Welcome " Name "! You are from " DAO.GETCOUNTRY (ID) ";} else {msg1 = " Please check your ID.: " ID;}} msg = nn.welcome ();%> welcome </ title> </ head> <body bgcolor =" # fffcc "> < BR> <% = msg%> <br> <form action = "index.jsp" method = "post"> <p> Your ID: <input type = "text" name = "id" size = "10"> </ P> <p> <input type = "SUBMIT" NAME = "SUBMIT"> </ P> </ FORM> <br> <br> <% = (msg1 == "")? "": Msg1 "<br> <br> <br> Connect To Database OK. "%> </ body> </ html> <! - Do not store this 5 row of files</p> <p>**</p> <p>** ejb-jar.xml</p> <p>**</p> <p>-> Do not store this 5 lines into files, the same.</p> <p><? XML Version = "1.0" Encoding = "UTF-8"?> <! doctype ejb-jar public "- // Sun microsystems, Inc.//dtd Enterprise JavaBeans 2.0 // en" http: // java. Sun.com/dtd/ejb-jar_2_0.dtd "> <ejb-jar> <description> first </ description> <display-name> first </ display-name> <Enterprise-Beans> <! - session beans - -> <session id = "myfirstsession"> <display-name> my first session bean </ display-name> <ejb-name> firstsession </ ejb-name> <home> dev.first.firstsessionHome </ home> < Remote> Dev.first.FirstSession </ recote> <ejb-class> dev.first.firstsessionBean </ ejb-class> <session-type> stateless </ session-type> <transaction-type> container </ transaction-type > </ session> </ enterprise-beans> <askEMBLY-Descriptor> </ askEMBLY-Descriptor> </ ejb-jar> <! -</p> <p>**</p> <p>** jboss.xml</p> <p>**</p> <p>-></p> <p><? XML Version = "1.0" encoding = "UTF-8"?> <! doctype jboss public "- // jboss // dtd jboss // 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></p> <p><! -</p> <p>**</p> <p>** jboss-web.xml</p> <p>**</p> <p>-></p> <p><? XML Version = "1.0" encoding = "UTF-8"?> <! doctype jboss-web public "- // jboss // DTD web application 2.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 </ jidi-name> </ resource-ref> </ jboss-web> <!</p> <p>**</p> <p>** Web.xml</p> <p>**</p> <p>-></p> <p><? XML Version = "1.0" Encoding = "ISO-8859-1"?> <! doctype web-app public "- // sun microsystems, Inc.//dtd Web Application 2.2 // en" "http: // Java.sun.com/j2ee/dtds/web-app_2_2.dtd "> <web-app> <resource-ref> <description> PostgreSQL Driver </ description> <res-ref-name> jdbcpostgresds </ res-ref- Name> <res-type> javax.sql.datasource </ res-type> <res-auth> Container </ res-auth> </ resource-ref> </ web-app></p> <p><! -</p> <p>**</p> <p>** Application.xml</p> <p>**</p> <p>-></p> <p><? XML Version = "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></p> <p>Compile the Java source program to generate a Class file.</p> <p>Enter the Java source program directory, run:</p> <p>Javac-ClassPath% classpath%;% jboss% / server / default / deploy / first.ear / first.jar * .java</p> <p>or</p> <p>Javac-ClassPath% jboss% / server / default / deploy / first.ear / first.jar;% jboss% / client / jboss-j2ee.jar * .java</p> <p>Copy directory first.ear to jboss / server / default / deploy.</p> <p>Open the browser input address http: // localhost: 8080 / first To this, see: Hello! This My session bean from jboss.</p> <p>Description This EJB works.</p> <p>If you press the button, there is no reaction or an error. The reason is not installed, and the configuration postgres database is installed below.</p> <p>For windows2000</p> <p>Download pgsql731wina1.exe (http://www.postgreSQL.org),</p> <p>Finally You Will See The next line, you need enter the password for administrator</p> <p>Finally, you will look at the next line, you must enter Password for the user administrator.</p> <p>*******************</p> <p>ENTER Password of User`/administrator' :123456</p> <p>*******************</p> <p>Keep this Password, my password is 123456.</p> <p>From Start Menu> Programm> Postgressql> Adjust Postgressql Configuration File</p> <p>It will open the PostgressQL Configuration file in WordPad, find the following line,</p> <p>#</p> <p># Connection Parameters</p> <p>#</p> <p>#tcpip_socket = false</p> <p>#ssl = false</p> <p>#max_connections = 32</p> <p>#superuser_reserved_connections = 2</p> <p>#port = 5432</p> <p>Modify editing:</p> <p>#</p> <p># Connection Parameters</p> <p>#</p> <p>TCPIP_SOCKET = TRUE</p> <p>#ssl = false</p> <p>#max_connections = 32</p> <p>#superuser_reserved_connections = 2</p> <p>Port = 5432</p> <p>Then, save the file.</p> <p>Startup PostgressQL Server:</p> <p>Start menu> Programm> Postgressql> Utilies> Start Postgressql Server</p> <p>Start command line:</p> <p>Start menu> Programm> Postgressql> Utilies> Command shell</p> <p>Execute the following command, prepare data,</p> <p>Administrator @ SAN /</p> <p>$ DIR</p> <p>$ Cd bin</p> <p>$ Createdb test</p> <p>$ PSQL Test</p> <p>Test = # CREATE TABLE USERS</p> <p>Test- # (Name Varchar (20),</p> <p>Test (# id varchar (20),</p> <p>Test (# Country varchar (20));</p> <p>Test = # Insert INTO Users Values ​​('Sam', '123', 'China');</p> <p>Test = # Insert INTO Users VALUES ('Tom', '321', 'USA');</p> <p>Test = # insert INTO Users Values ​​('Sean', '231', 'France');</p> <p>Test = # selection * from users;</p> <p>Name | ID | country</p> <p>------ ----- -------</p> <p>SAM | 123 | China</p> <p>Tom | 321 | USA</p> <p>Sean | 231 | FRANCE</p> <p>(3 ROWS)</p> <p>Test = #</p> <p>At this point, the data is ready.</p> <p>For redhat:</p> <p>Log in to ROOT, perform the following commands, prepare data,</p> <p>MKDIR / USR / local / PGSQL / DATA</p> <p>Chown Postgres / USR / local / PGSQL / DATA</p> <p>Su - Postgres</p> <p>/ usr / local / pgsql / bin / initdb -d / usr / local / pgsql / data</p> <p>Open and edit /usr/local/pgsql/data/pg_hba.conf</p> <p>Local All Trust</p> <p>Host All 127.0.0.1 255.255.255.255 Trust</p> <p>Just delete #, and Save.</p> <p>[root @ localhost root] # su - postgres</p> <p>-bash-2.05b $ / usr / bin / postmaster -i -d / usr / local / pgsql / data> logfile 2> & 1 & 1</p> <p>-Bash-2.05b $ / usr / bin / createdb test</p> <p>-Bash-2.05b $ / usr / local / pgsql / bin / psql test</p> <p>Test = # ....... the folowing Same as windows2000</p> <p>At this point, the data is ready.</p> <p>Execute Shutdown.bat or Shutdown.sh to stop JBoss Server.</p> <p>Locate JDBC Drive.</p> <p>In order to use the connection pool in JBoss, you need to copy JDBC Drive to JBoss / Server / Default / Deploy, we can find /usr/share/pgsql/pgjdbc2.jar in Linux, in Wondows2000, we can find PostgreSQL / USR / Share / PostgreSQL /java/postgresql.jar</p> <p>Copy one of them to JBoss / Server / Default / Deploy</p> <p>Configuring jboss</p> <p>(1) Copy $ JBOSS / EXAMPLES / JCA / Postgres-Service.xml to $ JBOSS / Server / Default / Deploy /</p> <p>(2) Open editing JBoss / Server / Default / Depoy / Postgres-Service.xml</p> <p><Attribute Name = "JNDINAME"> PostgreSDS </ attribute></p> <p><Attribute Name = "ManagedConnectionFactoryProperties"></p> <p><Properties></p> <p><config-proteth name = "connectionURL" type = "java.lang.string"> jdbc: postgreSQL: // localhost / test </ config-protety></p> <p><config-proteth name = "driverclass" type = "java.lang.string"> Org.postgreSQL.Driver </ config-property></p> <p><! - set these only if you want only default logins, not through jaas -></p> <p><config-proteth name = "username" type = "java.lang.string"> administrator </ config-property></p> <p><config-property name = "password" type = "java.lang.string"> 123456 </ config-protety> </ profment></p> <p>In My Example, Set Username Administrator, Password 123456 for Windows 2000</p> <p>Set Username Postgres, No Password for Linux.</p> <p>In my example,</p> <p>Windows2000, User: Administrator, Password: 123456</p> <p>Linux (RH8.0), User: Postgres, no password</p> <p>Because PostgressQL and Windows2000 use different default usernames, this file is different in Linux and Window2000. Of course, you can add the same PostgressQL username and password in Linux and Window2000, this file is the same.</p> <p>save document.</p> <p>(3) Open Edit $ JBoss / Server / Default / conf / standardjbosscmp-jdbc.xml</p> <p>turn up:</p> <p><Datasource> Java: / Defaultds </ datasource></p> <p><DataSource-maping> Hypersonic SQL </ DataSource-mapping></p> <p>Join:</p> <p><Datasource> Java: / Postgresds </ DataSource></p> <p><datasource-mapping> postgres </ datasource-maping></p> <p>save document.</p> <p>(4) Open and edit $ jboss / server / default / conf / standardjaws.xml</p> <p>turn up:</p> <p><Datasource> Java: / Defaultds </ datasource></p> <p><type-mapping> Hypersonic SQL </ type-mapping></p> <p><Debug> False </ debug></p> <p>Join:</p> <p><Datasource> Java: / Postgresds </ DataSource></p> <p><type-mapping> postgres </ type-maping></p> <p><Debug> False </ debug></p> <p>save document.</p> <p>Now we will restart JBoss.</p> <p>Open the browser input address http: // localhost: 8080 / first</p> <p>Enter ID, press the button.</p></div><div class="text-center mt-3 text-grey"> 转载请注明原文地址:https://www.9cbs.com/read-76708.html</div><div class="plugin d-flex justify-content-center mt-3"></div><hr><div class="row"><div class="col-lg-12 text-muted mt-2"><i class="icon-tags mr-2"></i><span class="badge border border-secondary mr-2"><h2 class="h6 mb-0 small"><a class="text-secondary" href="tag-2.html">9cbs</a></h2></span></div></div></div></div><div class="card card-postlist border-white shadow"><div class="card-body"><div class="card-title"><div class="d-flex justify-content-between"><div><b>New Post</b>(<span class="posts">0</span>) </div><div></div></div></div><ul class="postlist list-unstyled"> </ul></div></div><div class="d-none threadlist"><input type="checkbox" name="modtid" value="76708" checked /></div></div></div></div></div><footer class="text-muted small bg-dark py-4 mt-3" id="footer"><div class="container"><div class="row"><div class="col">CopyRight © 2020 All Rights Reserved </div><div class="col text-right">Processed: <b>0.052</b>, SQL: <b>9</b></div></div></div></footer><script src="./lang/en-us/lang.js?2.2.0"></script><script src="view/js/jquery.min.js?2.2.0"></script><script src="view/js/popper.min.js?2.2.0"></script><script src="view/js/bootstrap.min.js?2.2.0"></script><script src="view/js/xiuno.js?2.2.0"></script><script src="view/js/bootstrap-plugin.js?2.2.0"></script><script src="view/js/async.min.js?2.2.0"></script><script src="view/js/form.js?2.2.0"></script><script> var debug = DEBUG = 0; var url_rewrite_on = 1; var url_path = './'; var forumarr = {"1":"Tech"}; var fid = 1; var uid = 0; var gid = 0; xn.options.water_image_url = 'view/img/water-small.png'; </script><script src="view/js/wellcms.js?2.2.0"></script><a class="scroll-to-top rounded" href="javascript:void(0);"><i class="icon-angle-up"></i></a><a class="scroll-to-bottom rounded" href="javascript:void(0);" style="display: inline;"><i class="icon-angle-down"></i></a></body></html><script> var forum_url = 'list-1.html'; var safe_token = 'nlizI37neQXpoImEFeXeWWo3qBGXNamonYzJV_2FLM9KuZ8Mz8DT43XIHEkt8btSOsBVvJd0WxYQw6_2BhH8'; var body = $('body'); body.on('submit', '#form', function() { var jthis = $(this); var jsubmit = jthis.find('#submit'); jthis.reset(); jsubmit.button('loading'); var postdata = jthis.serializeObject(); $.xpost(jthis.attr('action'), postdata, function(code, message) { if(code == 0) { location.reload(); } else { $.alert(message); jsubmit.button('reset'); } }); return false; }); function resize_image() { var jmessagelist = $('div.message'); var first_width = jmessagelist.width(); jmessagelist.each(function() { var jdiv = $(this); var maxwidth = jdiv.attr('isfirst') ? first_width : jdiv.width(); var jmessage_width = Math.min(jdiv.width(), maxwidth); jdiv.find('img, embed, iframe, video').each(function() { var jimg = $(this); var img_width = this.org_width; var img_height = this.org_height; if(!img_width) { var img_width = jimg.attr('width'); var img_height = jimg.attr('height'); this.org_width = img_width; this.org_height = img_height; } if(img_width > jmessage_width) { if(this.tagName == 'IMG') { jimg.width(jmessage_width); jimg.css('height', 'auto'); jimg.css('cursor', 'pointer'); jimg.on('click', function() { }); } else { jimg.width(jmessage_width); var height = (img_height / img_width) * jimg.width(); jimg.height(height); } } }); }); } function resize_table() { $('div.message').each(function() { var jdiv = $(this); jdiv.find('table').addClass('table').wrap('<div class="table-responsive"></div>'); }); } $(function() { resize_image(); resize_table(); $(window).on('resize', resize_image); }); var jmessage = $('#message'); jmessage.on('focus', function() {if(jmessage.t) { clearTimeout(jmessage.t); jmessage.t = null; } jmessage.css('height', '6rem'); }); jmessage.on('blur', function() {jmessage.t = setTimeout(function() { jmessage.css('height', '2.5rem');}, 1000); }); $('#nav li[data-active="fid-1"]').addClass('active'); </script>