6 Best Practices for Java EE architecture

Source: Internet
Author: User
Tags html form http post i18n java web
--Leverage advanced Java best practices to improve the architecture and design of existing and future Java EE applications

Author: Tarak Modi


Although many articles have discussed the best practice of Java EE. So, why do I have to write another article. What is the difference between this article and the previous article, or better than other articles?
First, the target audience for this article is the architect who is working on the technology. To avoid wasting everyone's talents, I avoid telling banal best practices, such as "Daily builds", "Test Everything", and "often integrated" (integrate often). Any project with a competent architect has a well-defined and well-defined team structure. They also have documented processes for coding checks, building code (daily or when needed), testing (unit, integration, and system), deployment and Configuration/Release management.
Second, I'll skip the best practices that are usually touted, such as "interface based design," "Using a well-known design model," and "using a service-oriented architecture". Instead, I will focus on the In-the-trench courses I have studied and used for several years in 6 (not many) areas. Finally, the purpose of this article is to let you think about your own architecture, provide a working code example, or a solution that is beyond the scope of this article. Let me introduce the following 6 lessons:

Lesson 1th: Do not bypass server-side validation
As a software consultant, I had the opportunity not only to design and implement a Web application, but also to evaluate/audit many Web applications. In complex, and JavaScript-client-encapsulated applications, I often encounter Web pages that perform extensive checks on user input information. This is true even if the HTML element has data validation properties, such as MaxLength. You can submit an HTML form only after you have successfully validated all the input information. As a result, once the server side receives a notification form (request), it executes the business logic appropriately.
Here, you find the problem. Developers have made a number of important assumptions. For example, they assume that all Web application users are equally honest. Developers also assume that all users will always access Web applications using browsers they have tested. There are a lot of other assumptions. These developers forget to take advantage of the tools available for free and easily simulate browser-like behavior through the command line. In fact, you can send any "posted" form by typing the appropriate URL in the browser window, however, by disabling the Get requests for these pages, it is easy for you to block such "form sending". However, you cannot prevent people from simulating or even creating their own browsers to invade your system.
The fundamental problem is that developers cannot determine the main differences between client and server-side validation. The main difference between the two is not where to verify where, for example, on the client or on the server side. The main difference is that the purpose behind the validation is different.
Client-side validation is simply convenient. Execute it to provide users with quick feedback?? Making the application appear to respond gives the illusion of running a desktop application.
On the other hand, server-side validation is required to build secure Web applications. Regardless of what is entered on the client side, it ensures that all data sent by the client to the server is valid.
As a result, only server-side validation can provide true application-level security. Many developers are trapped in the wrong sense: it is only when all data is validated on the client that security is ensured. The following is a common example of this view:
A typical login page has a text box for entering a username and a text box to enter a password. On the server side, someone may encounter code in the receiving servlet that forms the following SQL query:
"SELECT * from securitytable WHERE username = '" + form.getparameter ("username") + "' and password = '" + form.getparamete R ("password") + "';", and execute the code. If the query returns on a row in the result set, the user logon succeeds, otherwise the login fails.
The first question is how to construct SQL, but now let's ignore it for a while. What happens if the user enters "Alice" in the username. Suppose that a user named "Alice" is already in securitytable, when this user (or, more appropriately, a hacker) logs in successfully. I'll try to find out why this is happening as a problem for you.
Many creative client-side validations can prevent normal users from logging in from the browser. But what can we do for clients that have JavaScript disabled, or for advanced users (or hackers) who are able to use other browser-like programs to send commands directly (HTTP post and get commands)? Server-side validation is necessary to prevent this type of vulnerability. At this point, SSL, firewalls and so on are not useful.

Lesson 2nd: Safety is not an add-on
As the 1th lesson describes, I have had the privilege of studying many Web applications. I found that all of the JavaServer Page (JSP) had a common theme, which was a layout similar to the following pseudocode:

<%
User User =
Session.getattribute ("User");
if (user = null)
{
Redirect to
The logon page ...
}
if (!user.role.equals ("manager"))
{
Redirect to the
"Unauthorized" page ...
}
%>

<!-
HTML, JavaScript, and JSP
Code to display data and
Allow user interaction-->

If the project uses an MVC framework such as struts, all the action beans will have similar code. Although the last code might work very well, if you find a bug, or you must add a new role (for example, "Guest" or "admin"), this represents a maintenance nightmare.
In addition, all developers, no matter how young you are, need to be familiar with this coding pattern. Of course, you can use some JSP tags to organize your JSP code, and you can create a basic action bean that clears the derived action bean. However, because security-related code is distributed across multiple locations, the maintenance nightmare still exists. Because Web application security is enforced at the level of application code (by multiple developers) rather than at the architectural level, Web applications are likely to have weaknesses.
It is likely that the fundamental problem is to deal with security issues when the project is nearing completion. Recently, as an architect, I have experienced one or 6 versions of a project in more than a year, and we didn't mention security until the fourth edition. Even if the project exposes highly sensitive personal data to the Web, we are not aware of security. In order to change the release plan, we were involved in a battle with the project sponsors and their managers to include all security-related features in the first release and to put some "business" features in subsequent releases. In the end, we won the victory. And because of the high security of the application and the ability to protect the customer's private data, we are proud and our customers are very happy.
Unfortunately, in most applications, security does not seem to add any real business value, so it is not resolved until the end. When this happens, people rush to develop security-related code without considering the long-term maintainability or robustness of the solution. Another symptom of ignoring this security is the lack of full server-side validation, as I mentioned in Lesson 1th, which is an important part of a secure Web application.
Remember that the security of the Java EE Web application is not just the use of appropriate declarations in Web.xml and ejb-jar.xml files, nor is it the use of Java-EE technologies such as java-based authentication and authorization services Authorization Service,jaas). It's a thoughtful design and implements a framework that supports it.

Lesson 3rd: Internationalization (i18n) is no longer an armchair
The fact of the world today is that many non-native speakers of English will be accessing your public Web application. This is particularly true with the introduction of E-government, which allows people (a country's residents) to interact online with government agencies. Examples include the renewal of a driver's license or a vehicle registration certificate. Many of the first languages that are not English people are likely to access such applications. Internationalization (that is, "i18n" because there are 18 letters between the letter I and the letter N in the word "internationalization") enables your application to support multiple languages.
Obviously, if you have hard-coded text in your JSP page, or if your Java code returns a hard-coded error message, you spend a lot of time developing the Spanish version of the Web application. However, in Web applications, in order to support multiple languages, text is not the only part that must be "materialized." Because many images are embedded with text, graphics and images should also be configurable. In extreme cases, images (or colors) may have completely different meanings in different cultural contexts. Similarly, any Java code that formats numbers and dates must also be localized. The problem is that your page layout may also need to be changed.
For example, if you use an HTML table to format and display menu options, application headers, or footnotes, you may have to change the minimum width of each column and other possible aspects of the table for each supported language. To accommodate different fonts and colors, you may have to use a separate style sheet for each language.
Obviously, creating an internationalized Web application now faces architectural challenges rather than application challenges. A well-formed Web application means that your JSP page and all business-related (application-specific) Java code have unwittingly chosen to localize. The lesson to keep in mind is that you don't want internationalization to be supported by Java, EE. You must remember to design an internationalized solution from the first day.

Lesson 4th: Avoid common mistakes in the MVC representation
Java EE development is mature enough that in the presentation layer, most projects use some form of the MVC architecture, such as struts. In such projects, the phenomenon I often see is the misuse of the MVC pattern. Here are a few examples.
The common misuse is to implement all the business logic at the model layer (for example, in the action bean of struts). Don't forget that the model layer of the presentation layer is still part of the presentation layer. The correct way to use this model layer is to invoke the appropriate business layer service (or object) and send the results to the view layer. In design pattern terminology, the model of the MVC presentation layer should be implemented as the appearance of the business layer (Fa?ade). A better approach would be to use the business delegate pattern discussed in the core Java EE Model (Patterns). This excerpt from the book highlights the highlights and benefits of implementing your model as a business delegate:
Business delegate plays a role in abstracting client business. It abstracts and hides the implementation of business services. With business Delegate, the business services of the presentation tier client and the system can be reduced. The degree of coupling between. Depending on the implementation strategy, Business delegate can protect clients from potentially volatile effects in the implementation of the Business Services API. This can potentially reduce the number of times that the presentation layer client code must be modified when the Business service API or its underlying implementation changes.
Another common mistake is to place many of the presentation types logic in the model layer. For example, if a JSP page needs a date formatted in a specified way or data that is sorted in a specified manner, some people might place that logic at the model layer, which is the wrong place for that logic. In fact, it should be in a set of helper classes used by JSP pages. When the business layer returns data, the Action bean should forward the data to the view layer. This enables flexible support for multiple view tiers (JSP, Velocity, XML, etc.) without creating redundant coupling between the model and the view. It also enables the view to determine the best way to display data to the user.
Finally, most of the MVC applications I've seen have controllers that are not fully applied. For example, most struts applications will create a basic action class and complete all security-related functions. All other action beans are derived classes of this base class. This feature should be part of the controller, because if security conditions are not met, the first call should not reach the action Bean (that is, the model). Remember, one of the most powerful features of a well-designed MVC architecture is the presence of a robust, extensible controller. You should take advantage of this ability to enhance your own strengths.

Lesson 5th: Don't let the jopo tie your hands
I have seen many projects using Enterprise JavaBean in order to use Enterprise JavaBean. Because EJBs seem to give the project a superior and arrogant performance, sometimes it is a cool element (coolness factor). Other times, it causes Java EE and EJB to be confused. Remember, Java EE and EJB are not consent words. EJB is just a part of Java EE, a series of technologies that include JSP, servlet, Java Messaging Service (JMS), Java Database Connectivity (JDBC), JAAS, Java Management Extensions (JMX), and EJBs. It is also a set of guiding principles and patterns for how to use these technologies to build solutions together.
If you use EJBS without having to use EJBS, they can affect the performance of your program. EJB generally has more requirements for the application server than the old Web server. All value-added services provided by EJBS typically require more memory and more CPU time. Many applications do not require these services, so the application server competes with the application for resources.
In some cases, unnecessarily using EJBS can crash the application. For example, I recently encountered an application that was developed on an open source application server. The business logic is encapsulated in a series of stateful session beans (EJBS). Developers have a great effort to disable the "passivation" of these beans completely in the application server. The client requires that the application be deployed on a commercial application server that is part of the client technology stack. The application server does not allow the "passivation" feature to be turned off. In fact, the client does not want to change the setting of the application server with which it cooperates. As a result, developers have encountered a lot of trouble. The interesting thing is that developers themselves cannot give a good reason why code is implemented in EJB (and stateful session beans). Not only are developers experiencing performance problems, their programs are not working with customers.
In Web applications, unformatted common Java Objects (POJO) are powerful competitors of EJBS. Pojo is lightweight and does not burden an extra burden like an EJB. In my opinion, the advantages of many ejbs, such as object pooling, are overestimated. Pojo is your friend, don't be tied to it.

Lesson 6th: Data Access does not host the O/R mapping
All of the Web applications I've worked with have provided users with data that is accessible from other places, and therefore require a data access layer. This is not to say that all projects need to identify and build such a layer, which simply means that the existence of such a layer is not implicit or explicit. In the case of an implied data layer, the data tier is part of the business object (that is, the business services) layer. This applies to small applications, but is often inconsistent with architectural guidelines accepted by larger projects.
In summary, the data access layer must meet or exceed the following four criteria:
With transparency
Business objects can use a data source without knowing the specifics of the data source implementation. Because implementation details are hidden inside the data access layer, the access is transparent.
Easy migration
The data access layer makes it easy for applications to migrate to other database implementations. Business objects do not understand the underlying data implementations, so migration involves only modifying the data access layer. Further, if you are deploying some kind of factory policy, you can provide specific factory implementations for each underlying storage implementation. In that case, migrating to a different storage implementation means providing a new factory implementation for the application.
Minimizing code complexity in business objects
Because the data access layer manages all the data access complexity, it simplifies the business object and the code that uses other data clients of the data access layer. The data access layer, rather than the business object, contains many implementation-related code, such as SQL statements. This gives developers a range of benefits such as greater efficiency, better maintainability, and improved readability of the code.
Centralize all data access on a separate layer
Since all data access operations are now delegated to the data access layer, you can view this individual data access layer as a layer that can isolate other parts of the application from the data access. This centralization makes the application easy to maintain and manage.
Note: These standards do not explicitly demand the O/r (object to relationship) mapping layer. The O/R mapping layer is typically created with the O/R mapping tool, which provides objects to view and perceive relational data structures (Look-and-feel). In my opinion, using the O/R mapping in a project is similar to using an EJB. In most cases, it is not required. For relational databases that contain medium-scale unions and many-to-many relationships, the O/R mapping becomes quite complex. By increasing the inherent complexity of the O/R mapping solution itself, such as deferred loading (lazy loading), high-speed buffering, and so on, you will bring greater complexity (and risk) to your project.
To further support my point of view, I will point out many failed attempts to implement the entity Bean (O/R mapping), as popularized by Sun Microsystem, which has plagued people since version 1.0. In Sun's defense, some of the early problems were implemented by developers of EJB specifications. This in turn proves the complexity of the entity bean specification itself. As a result, most Java EE architects generally consider it a good idea to detach from the entity bean.
Most applications can only do a limited number of queries when processing their data. An effective way to access data in such an application is to implement a data access layer that implements a range of services (or objects, or APIs) that perform these queries. As mentioned, in this case, the O/R mapping is not required. When you ask for query flexibility, the O/R mapping is appropriate, but keep in mind that this additional flexibility is not without cost.
As I promised, in this article, I try to avoid stale best practices. Instead, I focused on my point of view on the most important decisions that every architect must make in the Java EE project. Finally, you should keep in mind that Java EE is not a specific technique or a number of acronyms that are forced into the solution. Instead, you should use the right technology at the right time, in the right place, and follow the principles of Java EE and the practices that are more important in Java EE than the technology itself.

About the author
Tarak Modi is a senior expert at North Highland (a management and technical consulting firm). He has extensive expertise in COM, MTS, COM +,. NET, Java EE, and CORBA. 2002 worked with people to write professional Java Web Services (Wrox Press). The author's personal website is: http://www.tekNirvana.com.

Original source
http://www.fawcette.com/special/J2EE/modi1/
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.