http://blog.9cbs.net/sinaPaper/archive/2004/06/28/28659.aspx
http://blog.9cbs.net/sinaPaper/archive/2004/06/29/29634.aspx
Http://blog.9cbs.net/sinaPaper/archive/2004/06/30/30538.aspx
http://blog.9cbs.net/sinaPaper/archive/2004/07/01/31231.aspx
Http://blog.9cbs.net/sinaPaper/archive/2004/07/05/34109.aspx
http://blog.9cbs.net/sinaPaper/archive/2004/07/05/34202.aspx
Http://blog.9cbs.net/sinaPaper/archive/2004/07/14/41058.aspx
http://blog.9cbs.net/sinaPaper/archive/2004/07/15/42234.aspx
In order to seek new progress, I think I started learning EJB programming from today.
I hope that all kind-of-minded friends can participate in it.
I am using the reference book is the Wrox EJB Programming Guide. This book has more than 1,000 pages, and strive to complete him all!
Ok, I don't have to say it. Now start to enter the first chapter.
Chapter 1 Enterprise JavaBeans System.
A large stack of nonsense will begin, and the multi-layer architecture is told from the single-layer architecture, and the N-layer architecture is said. This leads out the subject (J2EE). But this sentence is good: Others need special attention () server resources including threads, database connections, security, transactions, and more. Customization of the infrastructure of these resources is quite hard. This work is impossible in the Internet environment. If your development cycle is only three months, is it possible to establish a connection pool, an object buffer or a "wonderful" object layer for database access?
gosh! Said a big pile, finally got a great J2EE. But if you don't know the N-layer structure, you should look!
Container: It is said that the container is the operating environment of the Java program. I don't know if my understanding is correct. Now, you can only understand this.
The book says that the J2EE specification defines four container types:
1. Applets.
2. Application customer container. (I think it is swing)
3. Web container (Servlet and JSP)
4. EJB container.
It seems that 123 have been mastered, and now it is 4, so the EJB container is still learning! ~
The book writes a more in-depth explanation on EJB: EJB is a distributed component model that develops secure, scalable, transactional multi-user components. Simply put, EJB is a reusable software unit that contains business logic. As JSP can separate the application with business logic, EJB can separate application logic and system layer services, enabling developers to consider business issues without having to consider system programming.
J2EE API:
RMI / IIOP: Remote Method Invocation Some things like network connections.
JAVA Naming and Directory Interface.
JDBC: Don't you say this?
JavaMail / Jaf: Java's Mail service, JAF is an accessory for mail.
JMS: Java Message Server. Java message service.
Why use EJB in the design: I said a lot, I am still uncertain. Go again! However, this time I am more determined, the original EJB container is equivalent to a "function" server, and some business functions can be written. Then use 123 to call! (I don't know if it is a bit funny).
Haha, my understanding is correct, I said the 8th page of the book, the container can be seen as an executive environment!
EJB container service: (The container service here is not encoded, but the container management you are implemented. Good)
Component pool and life cycle management:
Haha, come to the vernacular, this is my personal understanding, the component pool has generated a lot of bean instances when the container starts, if it is 10, this time the customer 1 is coming, he took Bei1 At this time, others can't use bean1, and then come back to the second customer. He can't take Bean1, you can only take bean2. . . . . . . At this time, the customer 11 came, the container found no bean used him, so I found a bean who now used to use it, but I found that all are occupied, there is no way, I have to regenerate it into him. . Haha, it is so simple, but someone will ask, is this not more to build? It doesn't matter, the container finds that the generated bean is not used, it will be automatically deleted, release the space, release the system resources!
Customer session management:
Understand the passivation and activation.
Passivation is to save the customer's BEAN state in the pool.
Activation is to give the customer's bean status to the customer.
Database connection pool:
This seems to be not to talk! Data resource sharing! This named COOL B is.
Transaction management:
The transaction is very expensive!
Verification and access control:
This is very simple!
How to provide services in containers: This part is not written first, then write again, because I don't understand. Haha
EJB Type: ***** This is a key place. *****
Divided into three types:
Session bean: (life is as long as the conversation of our customers)
1. No state session bean.
2. Status Session Bean.
These two beans are very important, but they are told in Chapter 3. Haha, take this!
Entity Bean:
I understand that it is a database bean, just read the contents of the database in Bean, and I don't know how it is read. Don't be very wasting system resources! ? ? ?
The entity bean can be divided into:
CMP (persistence of container management): The container is responsible for the BEAN and the foundation database synchronization.
BMP (persistence of bean management): Here you must program a person responsibility and basic database synchronization! The container calls the programmer to write a good SQL statement when appropriate!
I really don't understand why CMP has I have to have a BMP, and the book is explained:
Sometimes adding design flexibility or support persistence in non-relational storage? ? Is this a human language?
There is also a bit: EJB specification V1.1 allows only one-to-one mapping between instance variables and table columns. Thus, when using this version, if you want to indicate a cumulative object in a plurality of tables in the entity bean, CMP cannot be used, and BMP is used. EJB2.0 specification fixes complex query language! Still very well! ~~~~ But it should be useful! ! I will find it in the future! Ha ha! ~~ Message Drive Bean. Chapter 6: just wait! Brothers ~~~~
Haha! After reading the first chapter. Look at Chapter 2 tomorrow!
Let's talk about it, Bromon said it is a little horrible. I don't know the authenticity of the source. If I think people don't want to go to the EJB3. Oh, but I still have to thank Bromon and my iron. My needle, my first article finally saw it, I hope more and more people will join! J
Chapter 1 EJB Development
EJB's role: (specified 6 development and deployment roles) L Enterprise Bean Provider's work tasks as follows: 1. Write the main interface of the bean. 2. Write the BEAN's component interface to declare the various business methods required by the application. 3. Write the implementation class that implements various business methods defined in the remote interface. 4. Write a deployment description item. 5. Package.
In fact, writing EJB programmers. As for what is the primary interface, what is the component interface, what is the implementation of the class! Let's die first!
l Application Assembler: It is actually a person who is working with a BEAN provider. Nothing is very useful, also known as industry experts! (just kidding)
l Deployer
l System administrator
l EJB service provider, container provider (two in the book, but I think they should be the same, at least temporarily the same thing)
In fact, it is coming back, some people are not very important, people we have to do are enterprise bean providers.
Develop the first EJB
Happy, I finally have a HelloWorld!
Everyone must remember the few elements of the bean provider! It is very important to expand between the few elements.
The topic of HelloWord is: based on annual salary, provident fund and income tax calculation monthly net income. (Stateless session bean).
EJB customer view:
Local Customers: Use local interfaces and local primary interfaces. Press the reference transmission value.
Remote customers: Using remote interfaces and remote primary interfaces. Press the variable transmission value. There will be java.rmi.RemoteException errors.
Standard design mode is that all access to the business logic layer use session beans, which require a remote interface to enable the client layer to access these session beans. The remaining entities and stateless session beans can see "implementation details" and only publish local interfaces.
This is the original words in the book, do you understand? Anyway, I can only understand 80%. Haha ~~~ followed.
Developer interface: fell! I told a lot of main interfaces before, I remembered it now, I don't know how old this book is written. The primary interface is responsible for controlling the life cycle operation of Bean: generated, delete, and looking. The primary interface is the first contact point of the customer in the bean. The customer gets references through JNDI. In fact, determine JNDI when deploying, not anxious. When the client references the primary interface, the bean can be performed by this interface: l Generate a new instance or look for existing Bean instances. (Local or remote) l Access the EJBMetadata interface (remote). l Sequence references (remote) getting a bean instance. l Delete the bean instance. l Execute the primary business method. In this example, only the primary interface generates a new instance of beans.
The local interface and remote interface are defined in EJB. (Ejbhome and ejblocalhome). The source of these two interfaces is available.
Method in the EJBHOME interface: getJBMetadata (): Returns the reference to the EJBMetAdata interface to obtain Bean information. (Still don't know what EJBMetadata is something. That dictionary is the meant of metadata). GethomeHandle (): Returns the handle of the main object. Remove (): Very simple, deleted. Haha, joke, actually different BEAN results, the session bean is putting the bean back into the pool, and the entity bean is deleted from the database. This time is it!
The lower side is the program, I will try the programs to take a moment to talk about it!
Through the analysis of the sample program, the sample program in the self-sensation book is really unprincuring, mainly to deploy tools, in this year, how can J2EE bring a deployment tool with J2EE, A large pile of configuration is really irritating! Ha ha.
Said a lot, starting to enter the key topic, you listen to you.
I chose Eclipse, this free thing is not bad, I found a lot of advantages in me, but I am unfortunate, I haven't used JBuilder, I don't know if they are not the same.
Eclipse has a Lomboz plugin that contains all the configurations of all servers. You can configure Web Model, and EJB Model, I choose the JBoss server, because I heard that he is not worthless.
As for the jboss under Eclipse, it is very simple. As long as Google is searching 'Eclipse deployment', there are many, and Mr. Jiang Yan, Lenovo, wrote a configuration, but everyone don't look at his EJB deployment, it is really garbage. According to him, it is difficult for beginners to learn the first EJB!
Do you still come to see my helloworld!
Excerpt from http://www.objectlearn.com/support/docs/firstejb.jsp
In fact, I just help you translate it, huh, huh. Look at the original text can be on the upper website.
Ok, don't say nonsense. Start now. Yes, be sure to ensure that your Lomboz and Eclipse have been configured.
1. Create a new Lomboz J2EE Project called "MyfirstejbProject". Don't change any other places, Next.
2. Then you can enter this interface:
I saw it, plus a new modules in this EJB Modules called MyBeans. Then select the Target Server option. That's it.
Choose our already configured JBoss.
3. Ok, now if you don't report an error. Just point finish!
4. The first EJB module has been completed, it can generate EJB and EJB HOME, but the implementation class developed needs yourself! How do you write an implementation class below?
5.
This pair can understand, but someone wants to ask, where is this thing come? Main interface, perfernece under the Window menu, point him! Haha, there is a full choice of Lomboz inside.
6.ok pull, follow the picture below to lose the name:
This time Finish will generate a TestSessionBean.java. This is the generated implementation class.
7. Then fill in this implementation class. How to fill it? Don't change source code, don't do it, do this:
then,
This will be added to the method, don't manually add the code, this will let your component interface can't find what you write!
Then change this method of this implementation:
Public string helloworld () {
Return "Hello from Lomboz!";
} // This knows what it means?
Up to now, even if we have made an EJB program, just miss the main interface, some things, but don't be afraid, Eclipse will give you automatic generation. Will it? Next, we need to do such steps:
a) Add this EJBBEAN just written to EJB.
b) Generate a primary interface, component interface.
c) Deploy him to the server.
d) Write a client program to experiment with him.
Easy! Really Easy!
8. This is a) that step, add him into the EJB. It is the EJB established in EJB Modules.
9. Everyone, now everyone finds this interface with the fastest speed.
Then do this:
This action is the task of completing task B).
10. OK, now do C), is to deploy the EJB just written to the server, and follow the two pictures below.
Looking for a console to see if your deployment is unsuccessful, if it is successful. You can do d). If you are not successful, come again! If it is still unsuccessful. Looking for me.
11. Now we have to write a customer program to experiment him, it is excited!
Re-establish a Java project, so that the EJB function can be displayed.
The newly established project called this name MyejbClientProject, in fact, what is called.
Point next to next page When you want to put the myejbclientproject we just made in Project! Otherwise it is done.
Then find this item under the New menu, Create An EJB Test Client. Point.
12. This is configured. This is actually not used.
You can see this class after finish: TestClient.java.
Modify this method
Public void testbean () {
Try {
com.testing.session.testsssion
MyBean = gethome (). CREATE ();
// --------------------------------------
// this is the place you make your calls.system.out.println (myBean.Helloworld ());
} catch (remoteException E) {
E.PrintStackTrace ();
} catch (createException e) {
E.PrintStackTrace ();
} catch (namingexception e) {
E.PrintStackTrace ();
}
}
OK, Save and then run! ! ! ! success! ! !
OK, a simplest EJB is done. I can finally enter the third chapter!
The front program is easy to use, I feel that the troubles written more than the book is much more, so I still have tools.
Finally, there is a point of AJB achievements, hot iron, now you will look at the third chapter.
Chapter 1 Development Session Bean
Everyone knows that the session bean is divided into state session beans and stateless sessions beans.
The book summed up their common point:
1. Both can realize the Javax.ejb.SessionBean interface, so there is the same container callback. Container callback? Now China's translation!
2. Both represent dedicated resources for generating BEAN customers.
3. Both can construct a process or a task model
4. Both can update the shared data, but the shared data is displayed as in the entity bean.
NND, I said so many common points, tell the truth, I don't know what he meant at all. Why is it so professional? ? ()
But different points but very clear:
Status Session Bean can save data between customer access, without status!
Take him, from the example, find the entry point.
A simple example of the stateless session bean is calculating the number, the number can be arbitrarily complex, but only stores in the client program. Oh! This is the case, it is actually quite free, but it seems that I can't say this, just so understand.
So, this time I decided to adopt the example of the book, the example of the book is equivalent to a Bank system! Exaggerate, it is actually adding minimalism.
In this way, we are still deploying him with the method inside (three):
Remember is an example of a stateless session bean.
Create a new implementation class, I wrote this:
Package com.testing.fund;
Import javax.ejb.sessionbean;
/ **
* @ ejb.bean name = "fundmanger"
* JNDI-NAME = "Fundmangerbean"
* Type = "stateless"
*
* -
* This is needed for jonas.
* If you are not usning Jonas You can Safely Remove The Tags Below.
* @ Jonas.bean EJB-Name = "Fundmanger"
* JNDI-NAME = "Fundmangerbean"
*
* -
** /
Public Abstract Class FundmangerBean Implements SessionBean {
/ **
* @ ejb.interface-method
* View-type = "remote" ** /
Public Double Add (Double B, Double A) {
B = B a;
Return B;
}
/ **
* @ ejb.interface-method
* View-type = "remote"
** /
Public Double Withdraw (Double B, Double A) {
B = B-A;
Return B;
}
}
I have to remember the ADD and WITHDRAW methods in this, it is not manual plus, it is Wizard. If you won't, look at me (3)! ! ! !
Then deploy it on the JBoss on the side of the (3)!
If everything is successful, or write one implementation in accordance with (3)! I wrote this, and the book is a bit different, but the implementation method is exactly the same!
Package com.testing.client;
Import java.rmi.remoteexception;
Import java.util.hashtable;
Import javax.ejb.createException;
Import javax.naming.initialcontext;
Import javax.naming.namingexception;
Import javax.swing. *;
Import java.awt. *;
Import java.awt.event. *;
Import java.text. *;
Import com.testing.fund.fundman;
Public Class Fundtest Extends Jframe Implements ActionListener {
Public Fundtest () {
Super ("Fund Manger");
}
Private com.testing.fund.fundmangerhome gethome () throws namingexception {
return (com.testing.fund.fundmanGerhome) getContext (). Lookup
com.testing.fund.fundmangerHome.jndi_name);
}
Private InitialContext getContext () throws namingexception {
Hashtable props = new hashtable ();
Props.put
InitialContext.Initial_Context_Factory,
"Org.jnp.interfaces.namingContextFactory");
Props.PUT (InitialContext.Provider_URL, "JNP: //127.0.0.1: 1099");
// this Establishes the security for authorization / authentication
// Props.Put (InitialContext.security_principal, "username");
// Props.Put (InitialContext.security_credentials, "password");
InitialContext InitialContext = New InitialContext (PROPS);
Return INIALCONTEXT;
}
Public void testbean () {buildgui ();
AddWindowListener (New windowadapter () {public void windowclosing (windowevent evt) {system.exit (0);}});
CreateFund ();
AddFund.addActionListener (this);
WITHDRAW.ADDACTIONLISTENER (this);
Currencyfomat = Numberformat.getCurrencyInstance ();
String currency = currencyfomat.format (0);
Status.setText (MSG Currency);
Pack ();
SHOW ();
}
Public Void ActionPerformed (ActionEvent E) {
String str = Amout.getText ();
Try {
IF (E.GetSource () == addfund) {
Balance = (Double) MyBean.add (Balance, Double.Parsedouble);
Currencyfomat = Numberformat.getCurrencyInstance ();
Strbar = currencyfomat.format (balance);
Status.Settext (MSG strbar);
}
IF (E.getsource () == withdraw) {
Balance = (double) MyBean.withdraw (Balance, Double.Parsedouble (STR));
Currencyfomat = Numberformat.getCurrencyInstance ();
Strbar = currencyfomat.format (balance);
Status.Settext (MSG strbar);
}
} catch (exception ex) {}
}
Public void createfund () {
Try {
MyBean = gethome (). CREATE ();
// --------------------------------------
// this is the place you make your caver
//System.out.println (MyBean.callyourthod ());
} catch (remoteException E) {
E.PrintStackTrace ();
} catch (createException e) {
E.PrintStackTrace ();
} catch (namingexception e) {
E.PrintStackTrace ();
}
}
Public static void main (String [] args) {
Fundtest Test = New FundTest ();
Test.TestBean ();
}
Public void buildinggui () {
GridbagLayout GL = New gridbaglayout ();
Gridbagconstraints gc = new gridbagconstraints ();
Container Container = getContentPane ();
Container.setLayout (GL);
gc.fill = gridbagconstraints.both;
Jlabel label = new Jlabel ("Enter Amout");
Gl.SetConstraints (Label, GC);
Container.Add (label); gc.gridwidth = gridbagconstraints.remainder;
Gl.SetConstraints (Amout, GC);
Container.Add (Amout);
Gl.addlayoutComponent (Addfund, GC);
Container.Add (addfund);
Gl.addlayoutComponent (Withdraw, GC);
Container.Add (withdraw);
Status = New Jlabel (MSG);
Gl.addlayoutComponent (Status, GC);
Container.Add (Status);
}
Double balance = 100;
Jtextfield Amout = New JtextField (10);
JButton AddFund = New JButton ("Add Funds");
JButton withdraw = New JButton ("withdraw funds");
String msg = "Current Funds IS:";
String strbar = "0";
Jlabel Status;
Fundmanger mybean;
Numberformat currencyfomat;
}
Run as Java app! Success! The interface is as follows:
Now I think about why there is a stateless session bean. In fact, this EJB is equivalent to a simple application background data processor! All your data record information is all in front desk, that is, on the side of this interface.
OK, the next class is the status session bean.
Haha, after a relaxed weekend, I have to start writing something.
I was also written on the weekend, but I still feel interesting, aunt, a few days.
The last talk is the stateless session bean.
It seems that it is still a bit. I don't understand why I have two kinds of beans that are united and state session beans, but don't matter, I can understand the program of the state session bean. Yes, there is something to say. I made a day of Eclipse3 on Friday. I heard that he made a new version, so he quickly downloaded the test test. He added a function of the function in it called EJB Editor. This thing is good, there are many new things. But the only thing I have understood is why it always reports when using his Create Client test programm! So or more irritated! I don't know if Eclipse's problem is still the problem of my machine, I will try again and tell me!
My status session bean is still pulling with Eclipse2.1.
I will write the program to everyone, then analyze it, I seem to be the kind of person who likes to look at the program first and then look at the theory. I don't know if someone is like me.
This is the client's implementation program:
Package com.test.session;
Import javax.ejb. *;
/ **
* @ Ejb.bean name = "stateful"
* JNDI-Name = "Statefulbean"
* Type = "stateful"
*
* -
* This is needed for jonas.
* If you are not usning Jonas You can Safely Remove The Tags Below.
* @ Jonas.bean EJB-Name = "Stateful"
* JNDI-Name = "Statefulbean" *
* -
** /
Public Abstract Class StatefulBean Implements SessionBean {
/ **
* @ ejb.create-method
* View-type = "remote"
** /
Public void ejbcreate (double amout) throws createException {
THIS.AMOUT = Amout;
}
/ **
* @ ejb.interface-method
* View-type = "remote"
** /
Public void addfunds (double amout) {
THIS.AMOUT = Amout;
}
/ **
* @ ejb.interface-method
* View-type = "remote"
** /
Public void withdrawfunds (double amout) {
THIS.AMOUT- = Amout;
}
/ **
* @ ejb.interface-method
* View-type = "remote"
** /
Public Double getBalance () {
Return this.amout;
}
Double amout;
}
Yes, the EJBCREATE method is to call the EJBCREATE (Double Amout) method during the Bean generation process.
It is like a method of initialization.
And you must make sure there is a CREATE (Double Amout) method in the primary interface and Ejbcreate (double amout)! This is a must, if you don't understand, find information. You should choose Create when you are new.
Give you the test program of the client:
Package com.testing.client;
Import java.rmi.remoteexception;
Import java.util.hashtable;
Import javax.ejb.createException;
Import javax.naming.initialcontext;
Import javax.naming.namingexception;
Import javax.swing.jframe;
Import javax.swing. *;
Import java.awt. *;
Import java.awt.event. *;
Import java.text. *;
Import com.test.session. *;
/ **
* @Author Sy
*
* Change the template for the generated type annotation
* Window> Preferences> Java> Code Generation> Code and Notes
* /
Public Class TestStateful Extends Jframe IMPLEments ActionListener {
Public testStateful () {
Super ("Fund Manger");
}
Private com.test.session.StateFulhome gethome () throws namingexception {
return (com.test.session.statefulhome) getContext (). Lookup (
com.test.session.StateFulHome.jndi_name);
}
Private InitialContext getContext () throws namingexception {
Hashtable props = new hashtable ();
Props.put
InitialContext.Initial_Context_Factory,
"Org.jnp.interfaces.namingContextFactory");
Props.PUT (InitialContext.Provider_URL, "JNP: //127.0.0.1: 1099");
// this Establishes the security for authorization / authentication
// Props.Put (InitialContext.security_principal, "username");
// Props.Put (InitialContext.security_credentials, "password");
InitialContext InitialContext = New InitialContext (PROPS);
Return INIALCONTEXT;
}
Public void createfund () {
Try {
MyBean = gethome (). CREATE (1000);
// --------------------------------------
// this is the place you make your caver
//System.out.println (MyBean.callyourthod ());
} catch (remoteException E) {
E.PrintStackTrace ();
} catch (createException e) {
E.PrintStackTrace ();
} catch (namingexception e) {
E.PrintStackTrace ();
}
}
Public void testbean () {
BUILDGUI ();
AddWindowListener (New windowadapter () {public void windowclosing (windowevent evt) {system.exit (0);}});
CreateFund ();
AddFund.addActionListener (this);
WITHDRAW.ADDACTIONLISTENER (this);
Currencyfomat = Numberformat.getCurrencyInstance ();
Try {
String currency = currencyfomat.format (myBean.getBalance ());
Status.setText (MSG Currency);
} catch (exception e) {}
Pack ();
SHOW ();
}
Public Void ActionPerformed (ActionEvent E) {
String str = Amout.getText ();
Try {
IF (E.GetSource () == addfund) {
MyBean.addfunds (Double.Parsedouble (STR));
Currencyfomat = Numberformat.getCurrencyInstance ();
strbar = currencyfomat.format (MyBean.getBalance ());
Status.Settext (MSG strbar);
}
IF (E.getsource () == withdraw) {
MyBean.withdrawfunds (Double.Parsedouble (STR)); currencyfomat = Numberformat.getCurrencyinstance ();
strbar = currencyfomat.format (MyBean.getBalance ());
Status.Settext (MSG strbar);
}
} catch (exception ex) {}
}
Public void buildinggui () {
GridbagLayout GL = New gridbaglayout ();
Gridbagconstraints gc = new gridbagconstraints ();
Container Container = getContentPane ();
Container.setLayout (GL);
gc.fill = gridbagconstraints.both;
Jlabel label = new Jlabel ("Enter Amout");
Gl.SetConstraints (Label, GC);
Container.Add (label);
gc.gridwidth = gridbagconstraints.remaInder;
Gl.SetConstraints (Amout, GC);
Container.Add (Amout);
Gl.addlayoutComponent (Addfund, GC);
Container.Add (addfund);
Gl.addlayoutComponent (Withdraw, GC);
Container.Add (withdraw);
Status = New Jlabel (MSG);
Gl.addlayoutComponent (Status, GC);
Container.Add (Status);
}
Double balance = 100;
Jtextfield Amout = New JtextField (10);
JButton AddFund = New JButton ("Add Funds");
JButton withdraw = New JButton ("withdraw funds");
String msg = "Current Funds IS:";
String strbar = "0";
Jlabel Status;
STATEFUL MYBEAN;
Numberformat currencyfomat;
Public static void main (String [] args) {
TestStateful test = new testStateful ();
Test.TestBean ();
}
}
Did you see the door? I finally know why this is called: Status session bean. Because of because. . . . . Haha, he has an Amout variable, this is completely internal variables, saved in the EJB container! And where the stateless session bean is not the same, the stateless session bean is saved in the client. Very big difference! This is the key to the problem! I don't know if you understand! Anyway, I think it is really obvious.
Below this is a pair of pictures I found in the IBM article library, I feel good, I fully explain what the state bean is going to pull:
These are some explanations, and the book is almost the same, save me typing.
State Session Bean Lifecycle:
BEAN is reclaimed in the following cases:
Timeout (whether activated or passivated)
Call remove ()
Passivation is based on the Least-Recently-useed algorithm Activation is generated by the method of bacan.
Afterbegin () beforecompletion () instercompletion () method is only valid for Beans that implements the sessionsynchronization interface.
In a transaction environment, the method of calling must have the same transaction type.
OK, status session bean is such a thing. It should be very simple, it can be understood.
Oh, everyone saw the QUGHOST that overself returned to my post? He's my good friend.
He has a lot of funny stories, I discuss with him, ready to send his funny experience in a new piece, but I don't know if he agrees.
OK, the words are passed down. I will always end the third chapter soon, in fact, the third chapter of the session bean to 5 is already finished, but there is a very critical thing inside, that is, serialization.
Serialization
The Java serialization mechanism can output the status of the entire object to a stream
Objects can then rebuild from its original state
In fact, it is very simple, it is to output all things of an object to a file. It can also be something else. many.
Then when you want to use him, you will then find some of this object's status and so on.
What really happened?
The instance of the bean is not serialized. If the Bean instance itself is serialized, a new instance needs to be created when it is re-built. This is lost.
Bean's state is serialized each attribute needs to be considered separately
What will be serialized?
A sequential (serializable) object
NULL
Direct reference to a specific inquirable object:
A reference to a bean home or Remote interface
Reference to sessionContext
Serialization of direct references to insequential partial parts
Containers must save their REMOTE and HOME interfaces when they are passivated.
Perhaps relying on Java's java.io.objectOutputStream and object replacement techniques in java.io.objectInputStream
Partial sequence
Each properties of the constituent state must be sequentially
The content of all attributes must contain sequentially
Helper class
Otherwise, the container can choose to recover the bean instance when passivated
These all I copied from IBM. I hope to understand the serialization of everyone.
Give me my program, I use it or the EJB of the state session bean.
/ *
* Create a date 2004-7-5
*
* Change the generated file template for
* Window> Preferences> Java> Code Generation> Code and Notes
* /
Package com.testing.client;
Import java.rmi.remoteexception;
Import java.util.hashtable;
Import javax.ejb.createException;
Import javax.naming.initialcontext;
Import javax.naming.namingexception;
Import com.test.session. *;
Import java.io. *;
Import javax.ejb.handle;
/ **
* @Author Sy
*
* Change the template for the generated type annotation
* Window> Preferences> Java> Code Generation> Code and Notes
* /
Public class handletest {
Private com.test.session.StateFulhome gethome () throws namingexception {
Return (com.test.session.statefulhome) getContext (). Lookup (com.test.session.statefulhome.jndi_name);
}
Private InitialContext getContext () throws namingexception {
Hashtable props = new hashtable ();
Props.put
InitialContext.Initial_Context_Factory,
"Org.jnp.interfaces.namingContextFactory");
Props.PUT (InitialContext.Provider_URL, "JNP: //127.0.0.1: 1099");
// this Establishes the security for authorization / authentication
// Props.Put (InitialContext.security_principal, "username");
// Props.Put (InitialContext.security_credentials, "password");
InitialContext InitialContext = New InitialContext (PROPS);
Return INIALCONTEXT;
}
Public void testbean () {
Try {
Com.test.Session.Stateful MyBean = gethome (). Create (1000);
//System.out.println ("adding 1000 ");
MyBean.Addfunds (1000);
System.out.println ("Adding 1000");
System.out.println ("Now Account IS:" MyBean.getBalance ());
MyBean.withdrawfunds (100);
System.out.Println ("withdrawing 100");
System.out.println ("Now Account IS:" MyBean.getBalance ());
System.out.println ("Saving Handle");
SaveHandle (MyBean);
System.out.Println ("Saving Success");
MyBean = NULL;
System.out.Println ("Loading Handle");
MyBean = loadingHandle ();
System.out.Println ("Loading Success");
System.out.println ("Now Account IS:" MyBean.getBalance () ", WITHDRAWING 100");
MyBean.withdrawfunds (100);
System.out.println ("Now Account IS:" MyBean.getBalance ());
// --------------------------------------
// this is the place you make your caver
//System.out.println (MyBean.callyourthod ());
} catch (remoteException E) {
E.PrintStackTrace ();} catch (createException e) {
E.PrintStackTrace ();
} catch (namingexception e) {
E.PrintStackTrace ();
}
}
Public static void main (String [] args) {
Handletest Test = new handletest ();
Test.TestBean ();
}
Private static void savehandle (stateful mybean) {
Try {
FileOutputStream Fos = New FileOutputStream ("Symic");
ObjectOutputStream out = New ObjectOutputStream (FOS);
Out.writeObject (myBean.getHandle ());
Out.close ();
} catch (exception e) {}
}
Private static stateful loadhandle () {
Try {
FileInputStream Fis = New FileInputStream ("Symic");
ObjectInputStream in = New ObjectInputStream (FIS);
Handle Handle = (Handle) in.readObject ();
Stateful mybean = (stateful) Handle.GeteJBObject ();
In.Close ();
Return mybean;
} catch (exception x) {}
Return NULL;
}
}
In fact, it is very simple, look at my procedure, then find the Symic file, see what you wrote inside. Haha ~~~~
Say something else, I have recently found it is really a good country. But it seems that there is no chance to go all over China!
ITaly
SHOPPER's DESTINATION!
It is very suitable in his buying! I heard that Prada, Amani is there a lot of TAX Rebate, only half of the price, and things are all the most Top Class.
I really want to go ~~~~~~~~~~
ITaly
My Dream-Pradise!
Ha ha! ~~~
Finally, you can come out again. I haven't been busy on the last week, and the company took us out of Happy. But now it is cool, can't go to the water. I was frozen in an instant in two minutes. Special cold.
Well, the words retired. I have been watching CMP, entity bean, but I have to make EntityBean first to do what I know how to configure the server, I found a guide to configure the JBoss server, I feel good, I will give you Share.
Http://www.uml.org.cn/j2ee/j2ee121505.htm
JBoss3.07 configuration
There are two places where JBoss is configured, one is a log information option for JBoss, so that we can get detailed information about deployment in the deployment of EJB; the other is the data source in JBoss, so that we can use EntityBeans managed by container persistence to operate data in the database.
(1) First we describe the changes to the log information option, enter the server / default / conf directory in the directory where JBoss is located, find the file log4j.xml, open it with the text editor, modify the property as follows:
Modify one:
category>
change into:
category>
Modify 2:
Modify to:
After modifying these properties, when we deploy CMP EntityBean, you will see the SQL plug-in statement that is automatically generated for the deployed CMP EntityBean and the EJB-QL statement included in the CMP EntityBean; check sentence.
(2) Next, we tell the configuration of the data source. Step 1: We entered the DOCS / EXAMPLES / JCA directory under the JBoss folder, open mysql-service.xml with the text editor, and modify the part of them:
(Database URL)
config-protety>
(Database driver)
config-protety>
Name = "Username" type = "java.lang.string"> Database (database user) config-protety> SAILING (Database User Password) config-property> Properties> attribute> After saving the modified content, copy the mysql-service.xml file to the JBoss folder, the server / default / deploy directory, at which time the file in the deploy directory is shown below: In the second step, we will copy the JAR file containing the MySQL JDBC 2.0.14 driver to the Server / Default / Lib directory of the JBoss installation directory. At this time, the files in the lib directory are shown below: Now we have completed the previous configuration, and we will tell the development of CMP EntityBean. Let's first configure the JBoss, then prepare, we want to start CMP, it is a database! ! ! This week has happened a lot. So there is no time to write. But many people ask me why I don't write it? I am going to write, and I will start writing now. (5) There is a brother asked my IBM website, my favorites were Del, I didn't find it for a long time on Google, waiting for me to find, then send it! However, I will put all all the reference URLs in the future. Ok, now I will enter my 4th chapter. Developing EJB1.1 entity beans, as if the EJB entity bean is also divided into version, but now I don't know why the subprint. Due to the deployment of the database bean, I didn't figure it out, so I found a sample program on the Lomboz, let's first do this experiment, then do it photo, ok? Excerpted from: http://www.object/cmp.jsport/docs/cmp.jsp 1-9 steps and I wrote before, how to build J2EE projects, this is written in my article in my previous article. Write from step 10: Now select CMP. Then hit your own name and bag name, do next. Then you will go to the CMP this interface: In fact, this interface will know what is going on: Write a table name, plus a field, and everything is simple OK. Remember, here Datasource must be the same as the fields inside the table. There is also a corresponding data type. You can add a lot of fields, but this example gives two fields, we also use him two fields. Right, and it is to set a primary key. Get it. Finish. At this time, Eclipse will open your AddressBean you just created. Then you change the code with this example. In fact, don't tell why you can understand that you can understand: Package com.testing.cmp; Import javax.ejb.entitybean; / *** @ ejb.bean name = "address" * jndi-name = "addressbean" * type = "cmp" * primkey-field = "name" * schema = "addressschema" * cmp-version = "2.x "* * @ ejb.persistence * Table-name =" address "* * @ Ejb.finder * query =" SELECT OBJECT (a) from addressschema as a "* signature =" java.util.collection Findall () "* * * / public Abstract Class AddressBean Implements EntityBean { ... Modify The Ejbcreate and Ejbpostcreate Methods to Accepts Two Parameters: / *** The ejbCreate method * * @ ejb.create-method * / public java.lang.String ejbCreate (String name, String phone) throws javax.ejb.CreateException {setName (name);. SetPhone (phone); return NULL; / *** The Container Invokes this method immediately after it calls ejbcreate. * * / Public void ejbpostcreate (String name, string phone) throws javax.ejb.createException {} The contents of the POST and CREATE methods must be changed. Waiting, tell you why do you have to do this, right, he will help you in him. SetName (); SETPHONE (); method. It's just fine. Then Save, add the bean you just wrote to the EJB, just use J2EE-> add ejb to modules, then select EJB you just created. The next side is the most annoying thing, just writing an ejbdoclet, the example is to change EJBGENERATE.XML, NND, I don't have this file at all, then I checked a lot of information, I know that the original version is old version, depressed ~~~~~~ The old version is still sticking. We 3.x to change this file, this file guarantees that you can see it after you find it, there are many XMLs of the database of the server, I use JBoss, so I will change this. . Version = "3.0" UnauthenticatedPrincipal = "noBody" XmlenCoding = "UTF-8" Destdir = "$ {ejb.dd.dir}" Validatexml = "false" DataSource = "java: / mysqlds" DataSourceMapping = "mysql" PreferredRelationMapping = "please_modify_this" /> Right, say this, I found the article is also good, it is written by a small j. Give you address: http://nemuneko.com/jboss/lomboz_cmp.html Because I have learned Japanese recently, I can understand the point, I don't understand, I will look at the picture. ~~~~~ Note, here is the most critical place, I think it may be because I compare stupid. Ha ha. The mysqlds here is the defualt datasouce that I am written inside (7), right, I'm going to put the mysql-service.xml this configuration file in 7. I can't check it for a long time. I found it. It turned out to be your EJB deployment to which folder, this mysql-service.xml file is to put it under that folder, on the machine: d: /jboss-3.0.8/server/default / deploy This folder. Finally, put your DB Driver in the LIB corresponding to this folder. I am this machine: D: /jboss-3.0.8/server/default/lib I use MySQL Driver, no problem. This should be no problem. Yes, the statement of the table also gives you: Create Table Address (Name Varchar (40), Phone Varchar (40)); Then Save your xdoclet.xml. Do Generate EJB Files, and Deploy. If you succeed, you can see such an output: 22: 50: 11,031 INFO [MainDeployer] Starting deployment of package: mybeans.jar22: 50: 11,302 INFO [EjbModule] Creating22: 50: 11,342 INFO [EjbModule] Deploying Address22: 50: 11,392 INFO [EjbModule] Created22: 50: 11,392 INFO [EjBModule] Starting22: 50: 11,822 info [address] table 'address' Already Exists22: 50: 11,842 info [ejbmodule] Started22: 50: 11,842 infoed package: mybeans.jar Be sure to look out! Very critical place. This completes our EJB CMP Bean. Write a client to test him OK. Give you my client program. Public void testbean () { Try {address address = gethome (). Create ("John Smith", " 2122222222222222223); Collection all = gethome (). FindAll (); items = all.iterator (); while (it.hasnext )) {Address element = (address) it.next (); system.out.println ("name:" element.getname () "Phone:" Element.getphone ());}} catch (Exception E ) { E.PrintStackTrace (); } } IMPORT remember to add it ~ haha. Run, success! ! ! ! ! ! Next, write some theoretical things, tell the truth, I hate the theory of things, because it is really big! ~~ http://nemuneko.com/jboss/lomboz_cmp.html The following text is COPY under CN-Java. (http://www.cn-java.com/target/news.php?news_id=2174)