Best practices
1. Always use the MVC framework.
2. apply automatic unit testing and test management at each layer.
3. develop according to the specifications, rather than the application server.
4. Plan to use J2EE Security from the very beginning.
5. create what you know.
6. Always use session facades when using the EJB component.
7. Use stateless Session Bean instead of stateful Session Bean.
8. Use transactions managed by containers.
9. Use JSP as the first choice for presentation layer.
10. When using httpsession, try to only save the status required by the current firm, and do not store other content in httpsession.
11. Enable Dynamic Caching in WebSphere and use the WebSphere servlet caching mechanism.
12. To improve the efficiency of programmers, the CMP Entity Bean is the preferred solution for o/R ing.
1. Always use the MVC framework.
The MVC framework can clearly separate business logic (Java Beans and EJB components), controller logic (servlets/struts action), and presentation layer (JSP, XML/XSLT. Good layering can bring many benefits.
The MVC framework is so important for the successful use of J2EE that no other best practices can be compared with it. Model-View-controller (MVC) is the basis for designing J2EE applications. MVC divides your program code into the following parts:
· Code responsible for business logic (that is, model-usually implemented using EJB or common Java objects ).
· Responsible for the code displayed on the user interface (that is, view-usually implemented through JSP and tag library, and sometimes implemented using XML and XSLT ).
· Code responsible For the application process (that is, the Controller-usually implemented using Java Servlet or a class like struts Controller ).
If you do not follow the basic MVC framework, many problems may occur during the development process. The most common problem is that too many components are added to the view. For example, JSP tags may be used to perform database access or process control of applications in JSP, this is common in small-scale applications. However, with the development in the future, this will cause problems because JSP is becoming increasingly difficult to maintain and debug.
Similarly, we often see that the view layer is built into the business logic. For example, a common problem is to directly apply the XML parsing technology used when building a View to the business layer. The business layer should operate on the business object, rather than the specific data representation bound to the view.
However, having the right components does not necessarily mean that your applications can be well layered. We often see that some applications include servlet, JSP, and EJB components. However, the main business logic is implemented at the servlet layer, or the application navigation is processed in JSP. You must perform a strict code check and refactor your code to ensure that the business logic of the application is only processed at the model layer, the application navigation only uses the Controller layer for processing, and your views only represent the passed Model Objects in HTML and JavaScript format.
2. Use automated unit testing and test management at each layer of the application.
Do not just test your GUI ). Stratified testing makes testing and maintenance extremely simple.
Over the past few years, there have been considerable innovations in the methodology field, such as the emergence of agile (for example, scrum [schwaber] and extreme programming [beck1]). the lightweight method is now widely used. One common feature of almost all of these methods is that they advocate the use of automated testing tools that can help developers perform regression testing (regression testing) in less time ), it can also help them avoid errors caused by inadequate regression testing, so it can be used to improve the efficiency of programmers. In fact, there is also a method called test-first development [beck2], which even advocates writing unit tests before developing actual code. However, before you test the code, you need to split the code into some testable parts. A "big mud ball" is hard to test because it is not just a simple and easy-to-recognize function. If each piece of your code implements multiple functions, it is difficult to ensure full correctness of such code.
One advantage of the MVC framework (as well as the MVC implementation in J2EE) Is that componentized elements can (in fact, quite simple) Perform unit tests on your applications. Therefore, you can easily write test cases for entity beans, session beans, and JSP without having to consider other code. There are many frameworks and tools for J2EE testing, which make the process easier. For example, JUnit (an open source code tool developed by junit.org) and cactus (an open source code tool developed by Apache) are useful for testing J2EE components. [Hightower] discusses in detail how to use these tools in J2EE.
Although all this details how to thoroughly test your application, we still see some people think that as long as they test the GUI (possibly web-based GUI, or independent Java applications), then they fully test the entire application. Gui testing is difficult to achieve comprehensive testing for the following reasons. First of all, it is difficult to thoroughly test every path of the system using GUI testing. GUI is only a method that affects the system. There may be background operations, scripts, and various other access points, this also requires testing. However, they generally do not have a GUI. Second, Gui-level testing is a very coarse-grained test. This test is only performed to test the system at the macro level. This means that once a problem is found, the entire subsystem associated with the problem should be checked, which makes it very difficult to identify the bug (defect. Third, Gui testing can be well tested only after the entire development cycle. This is because the GUI is fully defined at that time. This means that potential bugs can only be found later. Fourth, General developers may not have automated GUI testing tools. Therefore, when a developer changes the Code, there is no simple way to re-test the affected subsystem. This is not conducive to good testing. If developers have automated code-level unit testing tools, they can easily run these tools to ensure that changes do not disrupt existing features. Finally, if the Automatic Build function is added, it is very easy to add an automatic unit test tool during the Automatic Build Process. After completing these settings, the entire system can be reconstructed regularly, and regression testing almost requires no human involvement.
In addition, we must emphasize that using EJB and Web Services for distributed and component-based development makes it necessary to test a single component. If there is no "Gui" to be tested, you must perform a low-level test. It is best to start testing in this way, saving you the trouble to re-test distributed components or web services as part of your applications.
In short, automatic unit testing can quickly detect system defects and make it easy to detect these defects, making the testing work more systematic and thus improving the overall quality.
3. develop according to the specifications, rather than the application server.
It is necessary to keep the norms in mind. If you want to deviate from them, you must carefully consider them before doing so. This is because when you deviate from the rules, what you do is often not what you should do.
When you want to deviate from what J2EE allows you to do, this can easily cause your misfortune. We found that some developers studied some things that J2EE allowed, and they thought this could "slightly" improve J2EE performance, in the end, they will only find that this will cause serious performance problems, or be transplanted in the future (from one vendor to another, or more commonly from one version to another). In fact, this porting problem is so serious that [Beaton] calls this principle a basic best practice for porting.
There are several issues if you do not directly use the methods provided by J2EE. A common example is that developers use the JAAS module to replace J2EE Security, instead of using the built-in compliant application server mechanism for verification and authorization. Be sure not to leave the verification mechanism provided by the J2EE specification. If you leave this specification, this will be the main cause of system security vulnerabilities and vendor compatibility problems. Similarly, you need to use the authorization mechanism provided by the servlet and EJB specifications, and if you want to deviate from these specifications, make sure that you use the APIS defined by the specifications (such as getcallerprincipal ()) as the basis for implementation. In this way, you will be able to take advantage of the strong security infrastructure provided by the vendor, where business requirements need to support complex authorization rules.
Other common problems include the use of persistence mechanisms that do not comply with J2EE specifications (which makes transaction management difficult) and the use of inappropriate j2se methods (such as threads or Singleton) in J2EE programs ), and use your own methods to resolve the program-to-program communication, rather than using the mechanisms supported internally by J2EE (such as JCA, JMS, or web services ). When you port a J2EE-compliant server to another server or a new version of the same server, the above design will cause numerous problems. The only deviation from a specification is that a problem cannot be solved within the scope of the Specification. For example, the business logic scheduled for execution is a problem before ejb2.1 occurs. In such a case, we recommend that you use the solution provided by the vendor (such as the scheduler tool in WebSphere Application Server Enterprise) when there is a solution provided by the vendor ), third-party tools are used when no solutions are provided by the vendor. If you use the solution provided by the vendor, application maintenance and porting it to a new standard version will be a vendor issue, not your issue.
Finally, be sure not to use the new technology too early. Too keen on adopting technologies that have not yet been integrated into the J2EE specification or that have not yet been integrated into the vendor's products will often have disastrous consequences. Support is critical-if your vendor does not directly support a specific technology proposed in JSR, but this technology is not accepted by J2EE, you should not use this technology. After all, most of us are engaged in solving business problems, rather than promoting technological development.
4. Plan to use J2EE Security from the very beginning.
Enable WebSphere security. This allows your EJB and URL to at least allow access by all authorized users. Don't ask why-Just follow the instructions.
There were very few customers who planned to enable WebSphere J2EE Security from the very beginning, and we were surprised by the 1.1 straight forward. It is estimated that only about 50% of customers plan to use this feature from the very beginning. For example, we have worked with some large financial institutions (banks, agents, and so on) and they do not intend to enable security. Fortunately, this problem can be solved during pre-deployment checks.
It is dangerous not to use J2EE Security. Assuming that your applications require security (almost all applications need it), you can bet that your developers can build their own security system, this system is better than the one you bought from the J2EE manufacturer. This is not a good bet. It is extremely difficult to provide security for distributed applications. For example, you need to use a network security encryption token to control access to ejbs. In our experience, most self-built security systems are insecure and have major defects, which makes the product system extremely vulnerable.
Some reasons for not using J2EE Security include: worry about performance degradation, believe that other security (such as netegrity SiteMinder) can replace J2EE Security, or do not know the security features and functions of Websphere Application Server. Do not fall into these traps. Especially, although products such as netegrity SiteMinder provide excellent security features, they alone cannot protect the entire J2EE application. These products must be combined with J2EE application servers to fully protect your system.
Another common reason for not using J2EE Security is that the role-based model does not provide adequate granularity access control to meet complex business rules. Despite the fact, this should not be the reason for not using J2EE Security. On the contrary, J2EE authentication and J2EE roles should be combined with specific extension rules. If a complex business rule requires a security decision, write the corresponding code. The security decision should be based on the usable and reliable J2EE authentication information (user ID and role ).
5. create what you know.
Repeated development work will allow you to gradually master all the J2EE modules. All modules should be involved from the very beginning rather than from the very beginning.
We must acknowledge that J2EE is a huge system. If a development team only begins to use J2EE, it will be difficult to grasp it at once. There are too many concepts and APIs to be mastered in J2EE. In this case, the key to successfully master J2EE is to start with a simple step.
This method can be best implemented by creating small and simple modules in your application. If a development team creates a simple domain model and a backend persistence mechanism (probably using JDBC) and performs a complete test on it, this will enhance their self-confidence, so they will use this domain model to master front-end development using Servlet and JSP. If an development team finds it necessary to use EJB, they will similarly start to use simple session facades on the persistent EJB component of container management, you can also use JDBC-based data access objects and Dao instead of skipping them to use more complex structures (such as message-driven bean and JMS ).
This method is not a new method, but few developers use it to develop their skills. On the contrary, most development teams try to build all the modules right away, involving both the view layer, model layer, and controller layer in MVC, the result is that they are often under pressure of progress. They should consider some agile development methods, such as extreme programming (XP), which adopt an incremental learning and development method. In XP, there is a process called modelfirst, which involves first building a domain model as a mechanism to organize and implement user scenarios. Basically, you need to build a domain model as the first part of the user scenario you want to implement, and then build a user interface (UI) on top of the domain model as the result of user scenario implementation. This method is very suitable for an developer to learn only one technology at a time, rather than asking them to face many situations at the same time (or asking them to read a lot of books), which will cause them to crash.
Also, repeated development at each application layer may contain some appropriate patterns and best practices. If you start to apply some modes such as data access objects and session facades from the underlying layer of the application, you should not use the domain logic in your JSP and other view objects.
Finally, when you develop some simple modules, you can test the performance of your applications at the beginning. If you do not perform performance tests until the end of application development, this will often have disastrous consequences.
6. Always use session facades when using the EJB component.
Never expose the entity bean directly to any user type. The object bean can only use the local EJB interface (local EJB interfaces ).
When using the EJB component, using a session facades is undoubtedly the best practice. In fact, this general practice is widely applied to any distributed technology, including CORBA, EJB, and DCOM. Basically, the more underlying your application's "cross-region" is, the less time it takes to relay small pieces of data over multiple network connections. To achieve this goal, you can create a large-granularity facades object, which contains the logic subsystem. Therefore, you can call a method to complete some useful business functions. This method not only reduces network overhead, but also greatly reduces the number of accesses to the database by creating a transaction environment for the entire business function in EJB.
The local EJB interface (used since the EJB 2.0 specification) provides a Performance Optimization Method for coexistence ejbs. The Local interface must be explicitly accessed by your application. This requires code changes and prevents application changes when configuring EJB in the future. Since the session facades and the entire EJB contained in the session should be local to each other, we recommend that you use a local interface for the Entity Bean after the session facades. However, the implementation of session facades itself (for example, stateless session bean) should be designed as a remote interface.
To optimize the performance, you can add a local interface to the session facades. In most cases (at least in Web applications), your EJB client and EJB will coexist in the same Java Virtual Machine (JVM. In another case, if the session facades is called locally, you can use the J2EE application server configuration optimization (configuration optimizations), such as "no local copies" in WebSphere ". However, you must note that these alternative schemes change the pass-by-value method from pass-by-value to pass-by-reference ). This may cause subtle errors in your code. When you want to use these solutions, you should consider their feasibility from the very beginning.
If you use a remote interface (instead of a local Interface) in your session facades, you can also configure the same session facades in J2EE 1.4 as a Web service in a compatible manner. This is because JSR 109 (Web Service deployment in J2EE 1.4) requires that the remote interface of the stateless Session Bean be used as the interface implemented by the EJB web service and EJB. This is worthwhile because it can increase the number of client types for your business logic.
7. Use stateless Session Bean instead of stateful Session Bean.
In this way, your system can withstand the wrong termination. Use httpsession to store user-related statuses.
In our opinion, the concept of stateful Session Bean is outdated. If you think about it carefully, a stateful Session Bean is actually exactly the same as a CORBA object in architecture. It is nothing more than an object instance bound to a server, it depends on the server to manage its lifecycle. If the server is disabled, the object does not exist, and the client information of the bean does not exist.
The fault transfer (Failover) provided by the J2EE application server for stateful session bean can solve some problems, but the stateful solution is not stateless and easy to expand. For example, in WebSphere Application Server, requests for stateless session beans are achieved through balanced loading of member clusters where stateless sessions are deployed. On the contrary, the J2EE application server cannot load stateful bean requests in a balanced manner. This means that the loading process of servers in your cluster will be unbalanced. In addition, using stateful Session Bean will add some status to your application server, which is also a bad practice. This increases the complexity of the system and complicate the problem in the case of a fault. A key principle for creating a robust distributed system is to try to use stateless behavior.
Therefore, we recommend that you use the stateless Session Bean Method for most applications. Any user-related status that needs to be used during processing should be transmitted to the EJB method in the form of parameters (and stored by using a mechanism such as httpsession) you can also retrieve data from persistent backend storage (for example, by using an entity bean) as part of an EJB transaction. This information can be cached in the memory when appropriate, but it is potentially challenging to store this cache in a distributed environment. The cache is very suitable for read-only data.
In short, make sure that the scalability is taken into account from the very beginning. Check all ideas in the design and consider whether your application can run properly when it is running on multiple servers. This rule is applicable not only to the application code in the preceding situations, but also to mbean and other management interfaces.
Avoiding stateful usage is not just a recommendation for IBM/websphere, it is a basic J2EE design principle.
8. Use transactions managed by containers.
Learn about the two-phase commit transactions in J2EE and use this method instead of opening up your own transaction management. Containers are almost always better at transaction optimization.
Transactions managed by containers (CMT) provide two key advantages (which is almost impossible without container support): composable work orders and robust transaction behavior.
If your application code explicitly uses start and end transactions (maybe javax. JTs. usertransaction or even a local resource transaction), and future requirements require a combination of modules (which may be part of code refactoring). In this case, you often need to change the transaction code. For example, if module A starts a database transaction, updates the database, then commits the transaction, and Module B performs the same processing, consider what happens when you try to use the above two modules in Module C? Now, Module C is executing a logical action, which actually calls two independent transactions. If Module B fails to be executed, the transaction of module A can still be committed. This is what we do not expect. If, on the contrary, both module A and Module B use CMT, Module C can also start a CMT (usually through the configuration descriptor ), in addition, the transactions in module A and Module B will be the hidden part of the same transaction, so that complicated code rewriting is no longer required.
If your application needs to access multiple resources in the same operation, you need to use two phases to commit transactions. For example, if you delete a message from the JMS queue and then update the Record Based on the message, it is especially important to ensure that both operations are executed or not executed. If a message has been deleted from the queue and the system does not update the records in the database related to the message, the system is unstable. Some serious customer and business disputes originate from inconsistency.
We often see some customer applications trying to implement their own solutions. The application code may be used to "undo" the queue operation when the database update fails. We do not advocate this. This implementation is much more complex than you initially thought, and there are many other situations (imagine a situation where an application suddenly crashes during the execution of this operation ). As an alternative, you should use two-phase commit transactions. If you use a CMT and access resources submitted in two phases in a single CMT (for example, JMS and most databases), WebSphere will handle all the complex work. It ensures that the entire transaction is executed or not executed, including system crashes, database crashes, or other situations. In fact, the transaction log stores the transaction status. When applications access multiple resources, we cannot emphasize the necessity of using CMT transactions.
9. Use JSP as the first choice for presentation layer.
XML/XSLT is used only when multiple types of output are required, and the output type is supported by a single controller and backend.
We often hear some arguments about why you choose XML/XSLT instead of JSP as the presentation layer technology. In the opinion of the person who chooses XML/XSLT, jsp "allows you to mix models and views" does not have this problem. Unfortunately, this is not entirely true, or at least not as clear as the white and black points. In fact, XSL and XPath are programming languages. XSL is turing-complete, although it does not comply with the programming language defined by most people, because it is rule-based and does not have control tools that programmers are used.
The problem now is that since this flexibility is given, developers will take advantage of this flexibility. Although everyone agrees that JSP makes it easy for developers to add "similar models" to the view, in fact, the same thing may be done in XSL. Although it is very difficult to access the database from XSL, we have seen some extremely complex XSLT style sheets that execute complex conversions, which are actually model code.
However, the most basic reason for choosing JSP as the preferred Representation Technology is that JSP is currently the most widely supported and widely understood J2EE view technology. With the introduction of new features of the custom tag library, jstl, and jsp2.0, it is easier to create JSP without any Java code, and the model and view can be clearly separated. Added strong support for JSP (including debugging support) in some development environments (such as WebSphere Studio), and many developers found that using JSP for development is easier than using XLS, some graphical design tools that support JSP and other features (especially in a framework like JSF) enable developers to develop JSP in WYSIWYG mode, XSL is sometimes not easy to do.
The last reason for using JSP is speed. Performance tests on the relative speed of XSL and JSP compared by IBM show that in most cases, JSP is several times faster than XSL when generating the same HTML, this is even true for compiled XSL. Although this is not a problem in most cases, it will become a problem in the case of high performance requirements.
However, it cannot be said that you should never use XSL. In some cases, XSL can represent a set of fixed data, and the ability to display data in different ways based on different style sheets is the best solution for displaying views. However, this is only an exception, not a general rule. If you only generate HTML to express every page, in most cases, XSL is an unnecessary technology, and, it brings far more problems to your developers than it can solve.
10. When using httpsession, try to only save the status required by the current firm, and do not store other content in httpsession.
Enable session persistence.
Httpsessions is useful for storing application status information. Its APIs are easy to use and understand. Unfortunately, developers often forget the purpose of httpsession-to maintain the temporary user status. It is not an arbitrary data cache. We have seen too many systems put a large amount of data (in MB) into each user's session ). Well, if there are 1000 users logging on to the system at the same time, each user has 1 MB of session data, then 1 GB or more memory is required for these sessions. To make the http session data smaller, otherwise, your application performance will decrease. A suitable data volume should be between 2 k-4 K for each user's session data. This is not a hard rule and 8 K is still correct, but it is obviously slower than 2 K. Be sure not to make httpsession a place where data is accumulated.
A common problem is to use httpsession to cache information that is easy to recreate, if necessary. Since sessions are persistent, it is a luxury to serialize unnecessary data and write data. On the contrary, you should use a hash table in the memory to cache data and save a keyword to reference the data in the session. In this way, if you cannot successfully log on to another application server, you can recreate the data.
When talking about session persistence, do not forget to enable this feature. If you do not enable session persistence or the server is stopped for some reason (Server failure or normal maintenance), the sessions of all current users of this application service will be lost. This is a very unpleasant thing. Users have to log on again and do something they have already done. Conversely, if session persistence is enabled, WebSphere automatically moves users (and their sessions) to another application server. The user does not even know that such a thing will happen. We have seen some unacceptable bugs in Local Code (not IBM code!) in product systems !) In this case, the above functions can still run well.
11. Use Dynamic Caching in WebSphere and the WebSphere servlet caching mechanism.
By using these functions, the system performance can be greatly improved, and the overhead is very small. The programming model is not affected.
The benefits of improving performance through caching are well known. Unfortunately, the current J2EE specification does not include a mechanism for servlet/jsp caching. However, WebSphere provides support for page and fragment caching, which is implemented through its Dynamic Caching function and does not need to be changed to the application. The cache policy is declarative, and its configuration is implemented through the xml configuration descriptor. Therefore, your application will not be affected and maintain compatibility and portability with J2EE specifications. At the same time, you will also get performance optimizations from the cache mechanism of Websphere Servlet and JSP.
The performance improvement from the Dynamic Caching mechanism of Servet and JSP is obvious, depending on the characteristics of the application. Cox and Martin [Cox] point out that when Dynamic Caching is used for an existing RDF (Resource description format) site abstract (RSS) servlet, its performance can be improved by 10%. Note that this experiment only involves a simple servlet. The increasing performance may not reflect a complex application.
To improve performance more, the WebSphere Servlet/jsp result cache is integrated with the WebSphere plug-in ESI Fragment Processor, ibm http server fast response cache accelerator (frca), and Edge Server cache functions. The use of these features provides many additional benefits for heavy read-based workloads.
12. To improve the efficiency of programmers, the CMP Entity Bean is the preferred solution for o/R ing.
Optimize performance through the WebSphere framework (readahead, cache, isolation level, etc. If possible, there are some application modes to improve performance, such as fast-lane reader [Marinescu].
Object/relationship (O/R) ing is the basis for creating enterprise-level applications using Java. Almost every J2EE application requires some type of O/R ing. J2EE vendors provide an O/R ing mechanism, which is portable and efficient among different vendors and can be well supported by some standards and tools. This is the CMP (persistence of Container Management) section in the EJB specification.
Early CMP implementations were known for their poor performance and lack of support for many SQL structures. However, with the emergence of EJB 2.0 and 2.1 specifications and adoption by some vendors, and the emergence of IBM WebSphere Studio Application Developer, these problems are no longer problems.
Cmp ejb components are now widely used in many high-performance applications. WebSphere provides some optimization functions to improve the performance of EJB components. The optimization functions include lifecycle cache and read-ahead capabilities. Both of the optimization functions are configuration options and do not need to modify the application or affect portability.
The CMP State data is cached in the cache life cycle and time-based invalidity is provided. The performance improvement from the cache lifecycle can achieve the cache performance of option A and still provide scalability for your applications. The read-ahead capability is used in conjunction with container management. This feature allows you to randomly retrieve relevant data as the parent data in the same query to reduce interaction with the database. This method can improve performance if the related data needs to be accessed through concurrent queries. [Gunther] provides detailed descriptions and detailed performance improvements through these features.
In addition, to fully optimize your EJB components, pay special attention when specifying the isolation level. Try to use the lowest isolation level and maintain the integrity of your data. A lower isolation level can provide optimal performance and reduce the risk of database deadlocks.
This is currently the most controversial best practice. There have been a lot of articles praising cmp ejb, and the same criticism is endless. However, the most basic problem here is that database development is difficult. Before you start using any persistent solutions, you need to learn the basics of queries and how database locking works. If you choose to use cmp ejb, make sure that you know how to use them through books such as [Brown] and [BARCIA. There are some subtle interactions that are hard to understand in terms of locking and competition, but it will be mastered after you spend some time and effort.
This article from: Liu zhimeng blog Source: http://www.liuzm.com/article/java/090527.htm