12 The most important J2EE best practices (transfer)
1, always use the MVC framework.
2, at each level are the application of automated unit testing and test management.
3, in accordance with the norms for the development, rather than in accordance with the application server for development.
4, from the outset, plans to use the J2EE security.
5, to create you know.
6, when the use of EJB components, always use the conversation Facades.
7, the use of stateless session bean, rather than have the state of the session bean.
8, the use of container-managed affairs.
9, the JSP as the presentation layer of choice.
10, when using HttpSession as far as possible, only the current state of firms necessary to preserve one of the other content not to be saved in HttpSession Medium.
11, in WebSphere, the start of dynamic cache, and use the WebSphere servlet caching mechanisms.
12, in order to improve the efficiency of programmers will CMP entity bean, as O / R mapping solution of choice.
1. Always use the MVC framework.
MVC framework can be business logic (Java beans and EJB components), the controller logic (Servlets / Struts Action), indicating that the layer (JSP, XML / XSLT) clearly separated. Good stratification can bring many benefits.
MVC framework for the successful use of J2EE are so important that there is no other best practices can be placed on a par with their. Model - View - Controller (MVC) design are the basic J2EE application. MVC will be your program code divided into the following some easy parts:
Responsible for business logic code (ie, the model - often using EJB or a Java object implementation).
Responsible for user interface display code (that is, the view - often through the JSP and tag library to achieve, and sometimes the use of XML and XSLT to achieve).
Flow responsible application code (that is, the controller - typically used as the Java Servlet or Struts controller to achieve such a category).
If you do not follow the basic MVC framework, in the development process there will be a lot of questions. The most common problem is the view of some of the ingredients add up too much, for instance, there may be the use of JSP tags to implement the database access, or JSP applications in flow control, which at small-scale applications are more frequently see, but, with the late development, to do so will cause problems, because JSP gradually become more and more difficult to maintain and debug.
Similarly, we also often see the view layer to build the business logic of the situation. For example, a common problem is to use in building a view of the XML direct application of analytic techniques to the business layer. Business on the business object layer should be - not bound to view the specific data to operate.
2. In the application of each layer are the use of automatic unit testing and test management.
Not to just test your graphical user interface (GUI). Tiered test to make testing and maintenance work has become extremely easy.
In the past few years, in the methods of the field of study has been considerable innovation, such as emerging known as the Agile (such as SCRUM [Schwaber] and Extreme Programming [Beck1]) lightweight method has now been very universal applications. Almost all of these methods a common characteristic is that they are advocating the use of automated testing tools, these tools can help developers with less time for regression testing (regression testing), and can help them avoid the return because of inadequate testing errors, it can be used to improve programmer productivity. In fact, there is also known as Test-First Development [Beck2] The method, which even advocated in the development of the code before the actual preparation of unit test first. However, before you test the code, you'll need to code can be divided into a number of test pieces. A "big mud ball" are difficult to test because it is not only a simple implementation of easily identifiable features. If each of your code snippet the function of various aspects of implementation, such a code would be difficult to guarantee their complete accuracy.
MVC Framework (as well as the J2EE implementation of the MVC) is one of the advantages of the component elements can (in fact, very easy) on your application for unit testing. Therefore, you can easily entity bean, session bean and the JSP an independent preparation of test cases, without having to consider other code. Now there is much for J2EE testing framework and tools, these frameworks and tools make this process easier. For example, JUnit (is a junit.org open source development tools) and Cactus (developed by the Apache open-source tools) for testing J2EE components are very useful. [Hightower] discusses in detail how to use these tools in J2EE.
Despite all of these in detail how to thoroughly test your application, but we still see some people think as long as they tested the GUI (may be Web-based GUI, or is an independent Java application), then they are fully test the entire application. GUI testing is very difficult to achieve a comprehensive testing program, has the following several reasons. First of all, the use of GUI testing is difficult to thoroughly test each system path, GUI is just a way to affect the system, there may be Backgrounds computing, scripts, and various other access points, which also needs to be tested. However, they usually do not have the GUI. Second, GUI-level testing is a very coarse-grained tests. This test is only at the macro level on the test system behavior. This means that when the problem is found, then related to this issue should check the entire subsystem, which allows to identify bug (defect) will be very difficult. Third, GUI testing is usually only at the later stage of the entire development cycle can be a good test, This is because this is the only GUI that time before they get a complete definition. This means that only in the late stage may find potential bug. Fourth, the development of the general staff may not have automatic GUI test tools. Therefore, when a developer changes the code, there is no easy way to re-test the affected subsystem. This in fact is not conducive to good testing. If developers have an automatic code-level unit testing tools, developers can easily run these tools in order to ensure that the changes would not undermine the already existing functions. Finally, if you add an automatic build feature, the automatic build process to add an automated unit testing tools are very easy. Upon the completion of these settings, the entire system can be regularly carried out reconstruction, and regression testing is almost no need for people participation.
In addition, we must emphasize that the use of EJB and Web services for distributed, component-based development allows testing of individual components have become very necessary. If there is no "GUI" need to test, you must carry out low-level (lower-level) testing. The best start in this way test, the province you will be properly distributed components or Web services applications as your part, you have to spend re-thought to be tested.
In short, through the use of automated unit testing, be able to quickly discover system deficiencies, and also easy to find these defects, making the test job has become more systematic, so the overall quality can be improved.
3. In accordance with the norms for the development, rather than in accordance with the application server for development.
To standardize the lies at the heart, if we deviate from the norm, the community must be careful consideration before they can do so. This is because when you deviate from the rules, you do not often you should do.
When you want to deviate from the J2EE can allow you to do things, this makes it easy for your misfortune. We found that some developers have studied a number of things outside the permit J2EE, they think that it can "slightly" to improve the performance of J2EE, and they will eventually be found to do so will cause serious performance problems, or in subsequent transplantation (from one vendor to another vendor, or are more common from one version to another version) in question will appear. In fact, this problem transplantation are so severe that [Beaton] called this the principle of the basic job transplant best practices.
Now there is some good places if we do not provide direct access to J2EE approach would certainly give rise to problems. A common example is the development of staff through the use of JAAS modules to replace J2EE security, rather than using the built-in follow the norms of the application server mechanisms for authentication and authorization. Attention should be paid from the J2EE specification not to provide authentication mechanisms, if out of the norm, this will be the system security vulnerabilities exist, as well as the main reason for manufacturers compatibility problem. Similarly, it is necessary to standardize the use of servlet and EJB authorization mechanism provided, and if you want to deviate from these norms, then the use of norms to ensure that the definition of API (such as getCallerPrincipal ()) as the basis for implementation. In this way, you will be able to make use of vendors to provide a strong security infrastructure, one of, the operational requirements necessary to support complex authorization rules.
Other common questions include the use of non-compliance with J2EE specifications persistent mechanism (which makes management more difficult), in the J2EE process J2SE using inappropriate methods (such as thread or singleton), and the use of your own solutions procedures to the procedures (program-to-program) of communication, rather than using J2EE internal support mechanisms (such as JCA, JMS, or Web services). When you follow the J2EE server of a transplant to other servers, or transplanted to the same server on the new version, the above design options will result in numerous problems. The only departure from the norm is that when a problem in the framework of norms of the time can not be resolved. For example, arrangements for the implementation of business logic from time to time at EJB2.1 is a problem before, in similar circumstances, we propose that when the vendors have provided solutions for the use of vendor provided solutions (such as WebSphere Application Server Enterprise in Scheduler instrument), and in the absence of vendor provided solutions on the use of tools provided by third parties. If you are using vendors to provide solutions, application maintenance and its transplantation to a new version of the specification will be the manufacturers, rather than your problem.
Finally, we should pay attention not to use the new technology too early. Too keen to adopt has not yet integrated into the J2EE specification, or other parts have not yet integrated into the manufacturers of technology products often have disastrous consequences. Support is key - If your vendor does not directly support a specific JSR raised at the technical, but this technology has not yet been accepted by J2EE, then you should not be using this technology. After all, the majority of our people engaged in solving business problems, rather than the development of propulsion technology.
4. From the very beginning, plans to use the J2EE security.
Enable WebSphere security. This allows your EJB and the URL at least be sufficient to allow all authorized users access. Not to ask why - Acted as told .
In cooperation with our customers, the one intended to start on the opening of the WebSphere J2EE security customers are very small, it has let us by surprise. According to our estimates, only around 50% of customers intend to use one start on this feature. For example, we met with several large financial institutions (banks, agent and so on) together, they did not intend to enable security. Fortunately, this problem at the inspection prior to deployment on can be resolved.
Do not use J2EE security is a dangerous thing. Suppose your application requires security (almost all applications are required), you bet your developers can build their own security system, and this system than you bought from J2EE vendors better. That's not a good bet for distributed applications to provide security are extremely difficult. For example, you need to use encrypted network security tokens to control access to EJB. From our experience, the majority of their own to build the security system is unsafe, and have significant deficiencies, which makes product system is extremely weak.
Some do not use J2EE security reasons include: fear of the decline in performance, I believe that other security (such as Netegrity SiteMinder) can replace the J2EE security, or are not aware of WebSphere Application Server security features and functions. Not to fall into these traps, and in particular, even though such as Netegrity SiteMinder product can provide excellent security features, but only its own can not protect the whole J2EE applications. These products must be consistent with J2EE application servers together can fully protect your system.
Other non-use of a common J2EE security reasons are: role-based model did not provide enough granularity of access control to meet the complex business rules. Although this is the truth, but it should not become a non-use of J2EE security reasons. On the contrary, should be J2EE authentication and J2EE role with a specific combination of the expansion rules. If the complex business rules required to make security decisions, it is the preparation of the corresponding code, their safety must be based on the decision-making can be directly used and a reliable J2EE authentication information (user ID and role).
5. To create you know.
Repeated development work will allow you to gradually be able to grasp all of the J2EE module. From small and easy to create the module from the beginning rather than start one as soon as all the modules involved.
We must admit J2EE system are huge. If a development team is just beginning to use J2EE, it will be difficult to be able to master it all at once. In J2EE there are too many concepts and master the required API. Under such circumstances, the key to the success of master J2EE are easy steps to start from the start.
7. The use of stateless session bean, rather than have the state of the session bean.
This allows you to make the system stand up to the termination of the error. Use HttpSession to store and user-related condition.
To our point of view, there is the concept of stateful session bean is already outdated. If you carefully consider its a session bean in fact there is a state with a CORBA object on the system structure are identical, nothing more than an object instance, bound to a server, and relies on the server to manage their life cycle. If the server is shut down, this object does not exist, then the bean's client information does not exist.
J2EE application server for the session bean has state to provide failover (failover) can solve some problems, but there is a state of solution without non-state solution that is easy to expand. For example, in WebSphere Application Server, the stateless session bean on the request are passed to the deployment of non-state members of the conversation clusters to achieve a balanced load. On the contrary, J2EE application servers should not have state of the bean to load balance requests. This means that your cluster server loading process will be uneven. Moreover, the use of stateful session bean will be add some state to your application server up, which is bad practice. This will increase the complexity of the system, and in case of failure to make the problem even more complicated. Create a robust Distributed System A key principle is to minimize the use of non-state actors.
Therefore, we suggest that for most applications the use of stateless session bean method. Any treatment at the time required for use with the user-related parameters of the state of the form should be sent to the EJB methods (and through the use of a mechanism such as HttpSession to store it) or from a persistent back-end storage (such as through the use of entity bean ) as part of EJB Affairs retrieval. Where appropriate, this information can be cached into memory, but should pay attention to the environment in a distributed cache to preserve this potential challenge. Cache is very suitable for read-only data.
In short, you want to ensure that from the beginning one must take into account the extended nature can be. Designed to check all the idea, and take into account when your application on to multiple servers at run-time, can operate normally. This rule will not only fit the above situation, application code, but also to such as MBean management interface and other circumstances.
Avoid the use of not only has the status of the IBM / WebSphere's recommendation This is a basic design principles of J2EE.
8. The use of container-managed affairs.
J2EE Learn about the two-phase commit affairs, and the use of this approach, rather than opening up your own transaction management. Containers at Service optimization is almost always better.
Management of the affairs of the use of container (CMT) has provided two key advantages (if there is no container to support this is almost impossible): The combination of robust job modules and conduct the affairs.
If your application code to explicitly begin and end the use of the Service (javax.jts.UserTransaction or even perhaps the use of local resources are matters), and future requirements necessary combination module (may be will be reconstructed as part of the code), which types of circumstances are often required to change the Transaction Code. For example, if module A start of a database transaction, update the database, and then submitted to the Panel, and module B has made the same deal with, please think about when you try to use module C in the above two modules, what would happen then? Now, the module C is implementing a logical action, and this action will in fact call for two separate affairs. If module B at the failure of implementation, and module A is still to be submitted to the Service. This is what we do not want to see the behavior. If, on the contrary, module A and module B, then use the CMT, module C can also start a CMT (usually done through the configuration descriptors), and in the module A and module B of the Service will be a panel with the implicit part This is no longer required to rewrite code complex work.
If your application at the same operation needs to access a variety of resources, you must use two-phase commit Affairs. For example, if you delete from a JMS message queue and then update the message based on this record, this time, to ensure that these two operations will be implemented or will implement becomes particularly important. If a message has been deleted from the queue, while the system is not updated with this message-related records in the database, then such systems are unstable. Some serious customer and commercial disputes from an inconsistent state.
We often see some client applications that attempt to achieve their own solutions. Perhaps through the application code in the database update failed when the "revocation" of the queue operations. We do not advocate doing so. This initial implementation than you imagine much more complex, and there are many other circumstances (imagine if the application to perform this operation in the course of a sudden collapse of the situation). As an alternative approach should be used to submit a two-stage affairs. If you use the CMT, and CMT in a single visit of two-phase commit resources (such as JMS and most databases), WebSphere will handle all the complex job. It will ensure that the entire Service was executed or not executed, including a system crash, database crash or other situation. In fact, the transaction log is now saved in a state of affairs. When applications access a variety of resources, how do we emphasize the need for the use of CMT affairs can not be overemphasized.
9. The JSP as the presentation layer of choice.
Only express a variety of required output type, and output type by a single controller and back-end support when the use of XML / XSLT.
We have often heard some argue that why you select XML / XSLT instead of JSP technology as a presentation layer. Choose XML / XSLT views of the people are, JSP "allows you to model and view mixed together", and XML / XSLT will not have this problem. Unfortunately, this view is not entirely correct, or at least not as white and black points as well. In fact, XSL and XPath are programming languages. XSL is Turing complete (Turing-complete), although it did not correspond to what most people define the programming language, because it is rule-based, and programmers do not have the customary instrument of control.
The question now is now that given this flexibility, developers will use this flexibility. Although everyone agrees JSP allow developers easily add in the view "similar model" behavior, and in fact, in the XSL also may have made some of the same things. Although XSL access the database in such a thing would be very difficult, but we have seen some very complex XSLT stylesheets to implement complex transformation, which in fact are the model code.
However, it should be select JSP as the preferred technology, express the most basic reason is that, JSP support are now the most extensive and most widely understood view of the J2EE technology. With the Custom Tag Library, JSTL and JSP2.0 the introduction of new features, create a JSP easier and does not require any Java code, as well as model and the view can be clearly separated. In some development environment (such as WebSphere Studio) to add JSP (including debugging support) strong support, and many developers find the use of JSP development than XLS easy to use, some support for JSP graphical design tools and other features of (especially at such a framework JSF) enables developers to WYSIWYG manner JSP development, and for sometimes not easy to do XSL.
Finally one should carefully consider the use of JSP is due to the speed problem. In contrast to IBM's XSL and JSP relative velocity of the performance test showed that: In most cases, JSP in the generated HTML the same time, several times faster than XSL, and even the use of compiled XSL is also true. Although most cases this is not a problem, but at a very high performance requirements, this will become a problem.
However, this also can not say that, you will never not to use XSL. In some cases, XSL can express a set of fixed data, and can be based on a different style sheet in different ways to display these data show that view are the best solution. However, this is only an exceptional case, rather than general rules. If you only generate HTML to express each page, then in most cases, XSL is an unnecessary technology, and that it give your developers the problems brought about by far its best to resolve the many questions.
10. When using HttpSession as far as possible, only the current state of firms necessary to preserve one of the other content not to be saved in HttpSession Medium.
Opening of the session persistence.
HttpSessions for the state to store application information is very useful. Its easy to use and understand API. Unfortunately, developers usually forgotten the purpose of HttpSession ---- temporarily used to maintain user state. It is not arbitrary data cache. We have seen too many systems for each user session Add a lot of data (up to megabytes). Well, if there is simultaneously log 1000 users, each user has a conversation 1MB of data, then the required 1G or more of memory for these conversations. In order that the smaller number of HTTP session data, otherwise, your application performance will decline. Around a more appropriate amount of data each user should be at the session data between the 2K-4K, this is not a hard and fast rules, 8K still no problem, it is clear than when 2K slower. Must pay attention to, not to allow the accumulation of HttpSession data into place.
A common problem is to use the HttpSession caching is easy to create some of the information, if necessary. Because conversations are persistent, unnecessary serialization and writing of data is a very extravagant decision. On the contrary, should be used in-memory hash table to cache data, and in conversation to save a reference to this data keywords. Thus, if the success of Can not log in to other application servers, it can re-create data.
When talking about persistent conversation, do not forget to enable this feature. If you do not enable session persistence, or the server for some reason stopped (server failure or normal maintenance), all the applications the current user's session will be lost. This is a very unhappy thing. Users have to re-sign, and re-do things which they once had done. Conversely, if persistent sessions enabled, WebSphere will automatically users (and their conversation) to get another application server. Users do not even know there is such a happening. We have seen some products exist on the local system because the code is insufferable bug (instead of IBM's code!) And a sudden collapse, and this such a case, these functions can still work well.
11. In WebSphere, the use of dynamic cache, and use the WebSphere servlet caching mechanisms.
Through the use of these features, system performance can be greatly improved, while the overhead is very small. And does not affect the programming model.
Cache to improve performance through the benefits are well-known things. Unfortunately, the current J2EE specification does not include one for servlet / JSP caching mechanism. However, WebSphere provides a page fragment caching as well as support, through its Dynamic Cache feature to implementation, and applications do not need to make any changes. Its cache are a statement of strategy, and its configuration are configured through XML descriptors to the implementation. Therefore, your application will not be affected, and to maintain compatibility with the J2EE specification and portability, but also from WebSphere's servlet and JSP caching mechanism has been optimized performance.
Servet and JSP from the dynamic cache mechanisms improve the performance are obvious, depending on the application characteristics. Cox and Martin [Cox] pointed out that an existing RDF (Resource Description Format) Site Summary (RSS) servlet, when using dynamic cache, its performance can be increased by 10%. Please note that this experiment only involved a simple servlet, this performance increase may not reflect a complex application.
More in order to improve performance, the WebSphere servlet / JSP Result Cache with the WebSphere plug-in ESI Fragment processor, IBM HTTP Server Fast Response Cache Accelerator (FRCA) and Edge Server caching features together. Read on for the heavy work load, through the use of these features can be lot of extra benefits.
12. In order to improve the efficiency of programmers will CMP entity bean as an O / R mapping solution of choice.
Through WebSphere framework (readahead, cache, isolation level, etc.) to optimize performance. If possible, select the application has a number of models to improve performance to achieve the purpose, such as Fast-Lane Reader [Marinescu].
Object / relational (O / R) mapping is to use Java to create enterprise-class application foundation. Almost every J2EE applications need some kind of O / R mapping. J2EE vendors to provide an O / R mapping mechanisms between the different manufacturers are portable, efficient, and can be a number of standards and tools to support well. This is the EJB specification of CMP (container managed persistence) of the question.
Early implementation of the CMP to the poor performance and does not support SQL lot of known structure. However, with the EJB 2.0 and 2.1 specification, as well as those adopted by some manufacturers, and with as IBM WebSphere Studio Application Developer The emergence of these issues is no longer a problem.
CMP EJB component has now been widely used in many high-performance applications. WebSphere, including some optimization to improve the performance of EJB components, and optimize the features include: life cycle of the read-ahead cache and capacity. Optimize these two functions are configuration options, and does not require modifications to applications or the impact of portability.
Cache in a state of the life cycle of CMP cache state data and to provide time-based invalidity. From the cache in a state of the life cycle can improve the performance to be reached Options A cache performance, and still be able to for your application to provide extensibility. Read-ahead capacity and container managed relations used in combination. This feature by the same query casually retrieve relevant data as the father of data and databases to reduce the interaction. If the relevant data through the use of concurrent queries to access, then the performance of this method can be improved. [Gunther] provided a detailed description as well as through the performance of these characteristics enhance the details.
In addition, in order to fully optimize your EJB components, when specified isolation level to be special attention. As far as possible, use the lowest isolation level, and still maintain your data integrity. Lower isolation level can provide the best possible performance, and can reduce the risk of emergence of a database deadlock.
This is the most controversial current best practices. Already have many article praised the CMP EJB, the same voice is also heard denigrating. However, the most basic questions here are database development are difficult. When you begin to use any lasting solution, you need to know how to query and database lock these basic job knowledge. If you choose to use CMP EJB, you want to make sure that you have been through a number of books (such as [Brown] and [Barcia]) know how to use them. At Lock and contention has some subtle aspects of interaction difficult to understand, but you must spend time and effort will be at its disposal.
In this brief summary, we have to introduce you to the core J2EE patterns and best practices, which makes J2EE development into a manageable process. Although we did not give all in practice the use of these models the necessary details, but we hope can give you enough hints and guidance to help you decide what to do next.
About the author
Kyle Brown is the IBM Software Services for WebSphere's advanced technical members. Kyle to the Fortune 500 client to provide information on subject and object-oriented J2EE technology advisory services, training and guidance. Him with others co-authored Enterprise Java Programming with IBM WebSphere, WebSphere AEs 4.0 Workbook for Enterprise Java Beans (version 3) and The Design Patterns Smalltalk Companion. He also frequently published on workshop about Enterprise Java, OO design and design patterns Speech.
Keys Botzum are IBM Software Services for WebSphere's senior adviser. Him at the design of large-scale Distributed System has ten years of experience, and specializes in security issues. Keys used a variety of distributed technologies, including Sun RPC, DCE, CORBA, AFS, and DFS. Most recently, he focused on J2EE and related technologies. He holds a master's degree in computer science at Stanford University and Carnegie Mellon University in Applied Mathematics / Computer Science degree.
Ruth Willenborg is a WebSphere Application Server Performance Group Manager. She co-authored Human Performance Analysis for Java Web Sites (Addison-Wesley, 2002 years) one book.
Related Posts of 12 The most important J2EE best practices (transfer)
Same, JDO, also started compatible JPA. At the field of ORM, it seems that JPA is a benevolent government, is the normative specification. At the support of major manufacturers, JPA use became widespread. 2 Spring Spring + Hibernate often referred to as t
public transient int counter; / / transient property private String firstname; / / persistent property @ Transient String getLengthInMeter () (...) / / transient property String getName () (...) / / persistent property @ Basic int getLength () (...) / / p
1. You need to master the object-oriented analysis and design (OOA / OOD), involving patterns (GOF, J2EEDP) as well as the integrated model. You should understand the UML, especially class, object, interaction and statediagrams. 2. You need to learn basic
According to Sun's definition, JavaBean is a reusable software components. In fact JavaBean is a Java class, through the package into a property and methods of treatment of a function or a business object, referred to as bean. Because JavaBean is ...
The origin of ideas are pretty long history of reasons: [Use iBATIS history] The use of iBATIS has been a long time, the system is to use the CRUD template tool to generate the code, although there are tools to generate, but looked at a lot of CRUD the Sq
1. You need to master the object-oriented analysis and design (OOA / OOD), involving patterns (GOF, J2EEDP) as well as the integrated model. You should understand the UML, especially class, object, interaction and statediagrams. 2. You need to learn basic
2. Abstract class and interface difference (1) interface can be multiple implements, can only be a single abstract class extends (2) only the definition of interfaces, abstract class can have the definition and implementation (3) the definition of the def