1. Trang chủ
  2. » Công Nghệ Thông Tin

The j2eetm tutorial - phần 8 ppt

35 171 0

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

THÔNG TIN TÀI LIỆU

Thông tin cơ bản

Định dạng
Số trang 35
Dung lượng 1,05 MB

Nội dung

246 TRANSACTIONS The source code for the following example is in the examples/src/ejb/teller directory. To compile the code, go to the examples/src directory and type ant teller . To create the database tables, type ant create-bank-teller. To demarcate a JTA transaction, you invoke the begin, commit, and rollback methods of the UserTransaction interface. The following code, taken from the TellerEJB example program, demonstrates the UserTransaction methods. The begin and commit invocations delimit the updates to the database. If the updates fail, the code invokes the rollback method and throws an EJBException. public void withdrawCash(double amount) { UserTransaction ut = context.getUserTransaction(); try { ut.begin(); updateChecking(amount); machineBalance -= amount; insertMachine(machineBalance); ut.commit(); } catch (Exception ex) { try { ut.rollback(); } catch (SystemException syex) { throw new EJBException (“Rollback failed: “ + syex.getMessage()); } throw new EJBException (“Transaction failed: “ + ex.getMessage()); } } Returning Without Committing In a stateless session bean with bean-managed transactions, a business method must commit or roll back a transaction before returning. However, a stateful ses- sion bean does not have this restriction. In a stateful session bean with a JTA transaction, the association between the bean instance and the transaction is retained across multiple client calls. Even if each business method called by the client opens and closes the database connec- tion, the association is retained until the instance completes the transaction. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com SUMMARY OF TRANSACTION OPTIONS 247 In a stateful session bean with a JDBC transaction, the JDBC connection retains the association between the bean instance and the transaction across multiple calls. If the connection is closed, the association is not retained. Methods Not Allowed in Bean-Managed Transactions Do not invoke the getRollbackOnly and setRollbackOnly methods of the EJBContext interface. These methods should be used only in container-managed transactions. For bean-managed transactions you invoke the getStatus and rollback methods of the UserTransaction interface. Summary of Transaction Options The decision tree in Figure 17 shows the different approaches to transaction management that you may take. Your first choice depends on whether the enter- prise bean is an entity or a session bean. An entity bean must use container-man- aged transactions. With container-managed transactions, you specify the transaction attributes in the deployment descriptor and you roll back a transac- tion with the setRollbackOnly method of the EJBContext interface. A session bean may have either container-managed or bean-managed transactions. There are two types of bean-managed transactions: JDBC and JTA transactions. You delimit JDBC transactions with the commit and rollback methods of the Con- nection interface. To demarcate JTA transactions, you invoke the begin, com- mit , and rollback methods of the UserTransaction interface. In a session bean with bean-managed transactions, it is possible to mix JDBC and JTA transactions. This practice is not recommended, however, because it could make your code difficult to debug and maintain. If you’re unsure about how to set up transactions in an enterprise bean, here’s a tip: In the deployment descriptor specify container-managed transactions. Then, set the Required transaction attribute for the entire bean. This approach will work most of the time. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 248 TRANSACTIONS Figure 17 Options in Specifying Transactions Transaction Timeouts For container-managed transactions, you control the transaction timeout interval by setting the value of the transaction.timeout property in the con- fig/default.properties file. For example, you would set the timeout value to 5 seconds as follows: transaction.timeout=5 With this setting, if the transaction has not completed within 5 seconds, the EJB container manager rolls it back. When J2EE is first installed, the timeout value is set to 0: Enterprise Bean Session Bean Entity Bean Bean-Managed Transaction Container-Managed Transactio n JDBC Transaction JTA Transaction declare tx attributes in deployment descriptor invoke Connection methods in bean invoke UserTransaction methods in bean Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com ISOLATION LEVELS 249 transaction.timeout=0 If the value is 0, the transaction will not time out. Only enterprise beans with container-managed transactions are affected by the transaction.timeout property. For enterprise beans with bean-managed, JTA transactions, you invoke the setTransactionTimeout method of the User- Transaction interface. Isolation Levels Transactions not only ensure the full completion (or rollback) of the statements that they enclose, they also isolate the data modified by the statements. The iso- lation level describes the degree to which the data being updated is visible to other transactions. Suppose that a transaction in one program updates a customer’s phone number, but before the transaction commits another program reads the same phone num- ber. Will the second program read the updated and uncommitted phone number or will it read the old one? The answer depends on the isolation level of the transaction. If the transaction allows other programs to read uncommitted data, performance may improve because the other programs don’t have to wait until the transaction ends. But there’s a tradeoff—if the transaction rolls back, another program might read the wrong data. You cannot modify the isolation level of a entity beans with container-managed persistence. These beans use the default isolation level of the DBMS, which is usually READ_COMMITTED. For entity beans with bean-managed persistence and for all session beans, you can set the isolation level programmatically with the API provided by the under- lying DBMS. A DBMS, for example, might allow you to permit uncommitted reads by invoking the setTransactionIsolation method: Connection con; con.setTransactionIsolation(TRANSACTION_READ_UNCOMMITTED); Do not change the isolation level in the middle of a transaction. Usually, such a change causes the DBMS software to issue an implicit commit. Because the iso- lation levels offered by DBMS vendors may vary, you should check the DBMS documentation for more information. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 250 TRANSACTIONS Updating Multiple Databases The J2EE transaction manager controls all enterprise bean transactions except for bean-managed JDBC transactions. The J2EE transaction manager allows an enterprise bean to update multiple databases within a transaction. The figures that follow show two scenarios for updating multiple databases in a single trans- action. In Figure 18, the client invokes a business method in Bean-A. The business method begins a transaction, updates Database-X, updates Database-Y, and invokes a business method in Bean-B. The second business method updates Database-Z and returns control to the business method in Bean-A, which com- mits the transaction. All three database updates occur in the same transaction. Figure 18 Updating Multiple Databases In Figure 19, the client calls a business method in Bean-A, which begins a trans- action and updates Database-X. Then, Bean-A invokes a method in Bean-B, which resides in a remote J2EE server. The method in Bean-B updates Database- Client J2EE Server Databases Bean-A Bean-B X Y Z Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com UPDATING MULTIPLE DATABASES 251 Y. The transaction managers of the J2EE servers ensure that both databases are updated in the same transaction. Figure 19 Updating Multiple Databases Across J2EE Servers Client Databases J2EE Server Bean-A X J2EE Server Bean-B Y Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 252 TRANSACTIONS Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 253 Security by Eric Jendrock THE J2EE application programming model insulates developers from mecha- nism-specific implementation details of application security. J2EE provides this insulation in a manner that has the complementary affect of enhancing the porta- bility of applications in a way that the applications may be deployed in diverse security environments. The J2EE platform defines declarative contracts between those who develop and assemble application components and those who configure applications in oper- ational environments. In the context of application security, application provid- ers are required to declare the security requirements of their applications in a way that they may be satisfied during application configuration. The security requirements of an application are communicated in a declarative syntax in a document called a deployment descriptor. An application deployer employs con- tainer-specific tools to map application requirements captured in a deployment descriptor to security mechanisms that are implemented by J2EE containers. The J2EE SDK provides this functionality with the deploytool. In many cases, J2EE containers can provide an application's security functional- ity completely outside of the application implementation. In other cases, there must be a programmatic aspect to realizing an applications security functional- ity. The declarative contract that accompanies an application must convey the security requirements of the application, including identifying where it is neces- sary to bind implementation-embedded security functionality to environment- specific mechanisms or values. J2EE security mechanisms combine the concepts of container hosting and the declarative specification of application security requirements with the availabil- ity of application-embedded mechanisms. This provides a powerful model for secure, portable, distributed component computing. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 254 SECURITY Authentication 254 J2EE Users, Realms, and Groups 255 Authentication Mechanisms 257 Controlling Access to J2EE Resources 259 Client Authentication 260 Web Client Authentication 261 Application Client Authentication 261 Setting Component Security Identities 262 Container Authentication 262 Configuring EJB Target Security Requirements 263 Configuring Resource Signon (Connectors) 264 Authorization 264 Declaring Roles 265 Declaring Method Permissions 265 Declaring Role References 266 Mapping Roles to J2EE Users and Groups 266 Linking Role References to Roles 267 Configuring J2SE Security Policy Files 267 Determining the Caller Identity 267 Making Portable Access Decisions Programmatically from Components 267 Protecting Messages 268 Application Scenarios 268 J2EE Application Client 268 Web Browser Client 268 Authentication Authentication is the mechanism by which callers and service providers prove to one another that they are acting on behalf of specific users or systems. When the proof is bidirectional, it is referred to as mutual authentication. Authentication establishes the call identities and proves that the participants are authentic instances of these identities. An entity that participates in a call without estab- lishing or proving an identity (that is, anonymously), is called unauthenticated. When calls are made from a client program being run by a user, the caller iden- tity is likely to be that of the user. When the caller is an application component acting as an intermediary in a call chain that originated with a user, the identity may be associated with that of the user. In this case, the component impersonates the user. Alternatively, one application component may call another with an identity of its own and unrelated to that of its caller. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com AUTHENTICATION 255 Authentication is carried out in two phases: 1. Service-independent authentication that requires knowledge of some secret is performed to establish an authentication context that encapsulates the identity and is able to create proofs of identity, called authenticators. 2. The authentication context is then used to authenticate with other called or calling entities. Controlling access to the authentication context, and thus the ability to authenti- cate as the associated identity, becomes the basis of authentication. The follow- ing policies and mechanisms can be used for controlling access to an authentication context: • Once the user performs an initial authentication, all processes started by the user inherit access to the authentication context. • When a component is authenticated, access to the authentication context may be available to other related or trusted components, such as those that are part of the same application. • When a component is expected to impersonate its caller, the caller may delegate its authentication context to the called component. J2EE Users, Realms, and Groups A J2EE user is similar to an operating system user. Typically, both types of users represent people. However, these two types of users are not the same. The J2EE authentication service has no knowledge of the user and password you provide when you log on to the operating system. The J2EE authentication service is not connected to the security mechanism of the operating system. The two security services manage users that belong to different realms. A realm is a collection of users that are controlled by the same authentication policy. The J2EE authentication service governs users in two realms: certificate and default. Certificates are used with the HTTPS protocol to authenticate web browser cli- ents. To verify the identity of a user in the certificate realm, the authentication service verifies a X509 certificate. For step-by-step instructions, see Setting Up a Server Certificate (page 262). The common name field of the X509 certificate is used as the principal name. In most cases, the J2EE authentication service verifies user identity by checking the default realm. This realm is used for the authentication of all clients except for web browser clients that use the HTTPS protocol and certificates. Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com [...]... -certreq -sigalg MD5withRSA -alias -file 5 Send the contents of the for signing If you are using Verisign CA, go to http://digitalid.verisign.com/ Verisign will send the signed certificate in email Store this certificate in a file 6 Import the signed certificate that you recieved in email into the server: keytool -import -alias -file ... Enter the fully-qualified name of your server This fully-qualified name includes the host name and the domain name c organizational unit - Enter the appropriate value d organization - Enter the appropriate value Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com AUTHENTICATION e city or locality - Enter the appropriate value f state or province - Enter the unabbreviated name g two-letter... the certificate, perform these tasks: a Request the CA certificate from your CA Store the certificate in a file b To install the CA certificate in the Java 2 Platform, Standard Edition, run the keytool utility as follows (You must have the required permissions to modify the $JAVA_HOME/jre/lib/security/cacerts file.) keytool -import -trustcacerts -alis -file 4 Generate a... the certificate, run the keytool utility as follows, substituting with the alias of your certificate: keytool -genkey -keyalg RSA -alias 2 The keytool utility prompts you for the following information: a keystore password - The default value of this password is changeit You can change the password by editing the config/auth.properties file b first and last name -. .. Select the J2EE application from the tree 2 Select the JNDI Names tab 3 In the References table, select the row containing the resource reference For the AccountEJB example, the resource reference is jdbc/AccountDB, the name you entered in the Coded Name field of the Resource Ref’s tab 4 In the row you just selected, enter the JNDI name For the AccountEJB example, you would enter jdbc/Cloudscape in the. .. feature either HTTP basic authentication, form-based authentication, or HTTP digest authentication over SSL are also supported Configuring A Web Component’s Authentication Mechanism To configure the authentication mechanism that a web component will use: 1 Select the web component in the tree view The Web Component inspector will be displayed 2 Select the Security tab 3 Choose one of the following authentication... specify the -remove flag For example, to remove a user named tjones from the default realm, you would type the following command: realmtool -remove default tjones To add a group to the default realm, you specify the -addGroup flag The following command adds the customer group: realmtool -addGroup customer You cannot add a group to the certificate realm To remove a group from the default realm, you specify the. .. doesn’t contain the password Form-based authentication lets developers customize the authentication user interface presented by an HTTP browser Like HTTP basic authentication, form- 257 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 2 58 SECURITY based authentication is not secure, since the content of the user dialog is sent as plain text, and the target server is not authenticated... for Running the HTMLReaderEJB Example 1 Include the HTTPResponseException class in the enterprise bean 277 Simpo PDF Merge and Split Unregistered Version - http://www.simpopdf.com 2 78 RESOURCE CONNECTIONS 2 In the Resource Ref’s tab of the bean, specify the values in the following table Replace the string with the name of the host running the J2EE server Table 31 Resource Ref’s for the HTMLReaderEJB... know the roles of your users, but you probably won’t know exactly who the users will be That’s perfectly all right, because after your bean has been deployed, the administrator of the J2EE server will map the roles to the J2EE users (or groups) of the default realm In the Account bean example, the administrator might assign the user Sally to the Manager role, and the users Bob, Ted, and Clara to the . ensure the full completion (or rollback) of the statements that they enclose, they also isolate the data modified by the statements. The iso- lation level describes the degree to which the data. entities. Controlling access to the authentication context, and thus the ability to authenti- cate as the associated identity, becomes the basis of authentication. The follow- ing policies and mechanisms. follows. (You must have the required permissions to modify the $JAVA_HOME/jre/lib/security/cacerts file.) keytool -import -trustcacerts -alis <ca-cert-alias> -file <ca- cert-filename> 4.

Ngày đăng: 13/08/2014, 08:21