[转] 6 best practices for J2EE architecture

xiaoxiao2021-03-06  21

Although many articles have discussed J2EE best practices. So why do I have to write an article again? What is this in this article different from the previous article? Where is it better than other articles?

First, the target reader in this article is a architect that is engaged in technical work. In order to avoid wasting everyone, I will avoid the best practices of some Chen rot, such as "Build Daily", "Test Everything" and "Integrate Offenden. Any competent architect. The projects have a clear and defined team structure. They also use code inspections, build code (time daily or when needed), test (unit, integration, and system), deployment, and configuration / release management. Have a recorded process.

Secondly, I will skip the best practices that are usually touched, such as "interface-based design", "using famous design models", and "using service-oriented architectures". Instead, I will focus on I have learned and used a number of IN-Trench courses in a number of 6 (not a lot). Finally, the purpose of this article is to let you think about your architecture, provide work code examples or solutions beyond the scope of this article. Let me introduce this 6 lesson:

Lesson 1: Do not bypass server-side verification

As a software consultant, I have had the opportunity not only designed and implemented a web application, but also evaluated / reviewing many web applications. In complex, and in applications encapsulated in a JavaScript client, I often encounter a web page that performs a large number of checking for user input information. This is true, even if the HTML element has the properties of data validity, such as MaxLength. The HTML form can only be submitted after successful verifying all input messages. As a result, once the server side receives the notification form (request), the business logic is properly executed.

Here, do you find a problem? Developers have done a lot of important assumptions. For example, they assume that all web application users are equally honest. Developers also assume that all users will always use the browser they tested to access the web application. There are still many other assumptions. These developers have forgotten the tools that can be given free of charge, easily simulate behavior of similar browsers through the command line. In fact, by typing the appropriate URL in the browser window, you can send any "posted" form, despite this, you can easily block such "form transmission" by disabling the GET requests for these pages. However, you can't prevent people from simulating even their own browsers to invade your system.

The fundamental problem is that developers cannot determine the main difference between client authentication and server-side verification. The main difference between the two is not that the verification occurs where, for example, on the client or on the server. The main difference is that the purpose behind the verification.

Client verification is only convenient. Execute it provides users with quick feedback ?? Make the application seem to respond, gives people an illusion that runs desktop applications.

On the other hand, server-side verification is required to build a secure web application. Regardless of what is entered on the client side, it can ensure that all data sent to the server is valid.

Thus, only server-side verification can provide a safe application level. Many developers have fallen into a buzzer: only verification of all data in the client can ensure safety. Here is a common example of this view:

A typical login page has a text box for entering a user name and a text box for entering a password. At the server side, someone may encounter some code in the receiving servlet, which forms the SQL query in the following form:

"Select * from securityTable where username = '" Form.GetParameter ("UserName" "' and password = '" form.getParameter ("password") "", and executes these code. If the query returns a certain line of the result set, the user logs in success, otherwise the user logs in failed. The first question is to construct SQL's way, but now let us ignore it temporarily. What if the user enters "Alice '-" in the user name? Assuming users named "Alice" have been in SecurityTable, then this user (more appropriate manner is hacker) successfully logged in. I will use the reason why this happens to be left as a problem for you.

Many creative client validations prevent a general user from logging in from the browser. But what do we do with a client that has disabled JavaScript, or those who can use other similar browser programs directly send commands (HTTP POST and GET commands), what do we do? Server-side verification is necessary to prevent this type of vulnerability. At this time, SSL, firewall, etc. are not used.

Lesson 2: Safety is not an additive

As mentioned in Lesson 1, I have been fortunate to have a lot of web applications. I found that all JavaServer Page (JSP) has a common topic, which is a layout similar to the following pseudo code:

<%

User user =

Session.getaTribute ("User");

IF (user == NULL)

{

// redirect to

// the logon page ...

}

IF (! User.Role.equals ("manager"))

{

// redirect to the the

// "unauthorized" Page ...

}

%>

HTML, JavaScript, And JSP

Code to Display Data And

Allow User Intertion ->

If the project uses a MVC framework such as Struts, all Action Beans have similar code. Although the last code may run very well, if you find a bug, or you have to add a new role (for example, "guest" or "admin"), this will represent a nightmare.

In addition, all developers need to be familiar with this coding mode whether you are young. Of course, you can use some JSP tags to organize the JSP code, you can create a basic action bean that clears the derived action bean. Despite this, since the safety-related code will be distributed into multiple places, the nightmares when maintaining are still exist. Since the security of the web application is forced to establish the level of application code (by multiple developers), the web application is still likely to have weaknesses.

It is very likely that the fundamental problem is to handle security issues when the project is close to completion. Recently, as a architect, I have experienced some of the six versions to implement the project in more than a year, but until the fourth edition we mentioned safety ?? Even if the project will be highly sensitive Personal data is exposed to the web, we have not noticed security. In order to change the release plan, we have been involved in the battle with project funders and their managers to include all security-related features in the first edition and put some "business" function in subsequent versions. In the end, we have won the victory. And because the security of the application is quite high, protecting the private data of the customer, this is proud of this, our customers are very happy. Unfortunately, in most applications, security does not increase any actual business value, so until finally solve. When this happens, people rushed to develop and safely related code, and did not consider the long-term maintenance or robustness of the solution. Another sign that ignores the security is a lack of comprehensive server-side verification, as I am in Lesson 1, this is an important part of the security web application.

Remember: J2EE Web Applications is not just use of appropriate declarations in web.xml and ejb-jar.xml files, nor using J2EE technology, such as Java authentication and authorization service, JaaS ). It is concurrently designed and implements a architecture that supports it.

Lesson 3: Internationalization (I18N) is no longer talking on paper

Today's fact is that many English non-nomologs will visit your public web application. With the implementation of e-government, this is especially true because it allows people to interact with government agencies online online. Such examples include rehabilitation driver's licenses or vehicle registration certificates. Many first languages ​​are not English people likely to visit such an app. Internationalization (ie: "I18N", because in the "Internationalization" word, there are 18 letters between the letter i and the letter n, which allows your application to support multiple languages.

Obviously, if you have hard-coded text in your JSP page, or your Java code returns a hard coded error message, then you have to spend a lot of time to develop this web application Spanish version. However, in a web application, in order to support multiple languages, the text is not the only part of the "avatar". Because there is a text in many images, the graphics and images should also be configurable. In extreme cases, images (or color) may have a completely different in different cultural contexts. Similarly, any Java code that format numbers and dates must also be localized. But the problem is: Your page layout may also need to change.

For example, if you use an HTML form to format and display menu options, application heads, or footholds, you might have to change the minimum width of each column and other possible aspects of each column for each support. In order to adapt to different fonts and colors, you may have to use a separate style sheet for each language.

Obviously, now create an international web app is facing architectural challenges rather than the application challenges. A good web application means that your JSP page and all business-related (applications unique) Java code does not know localization unconsciously. The lesson to remember is: Don't support internationalization because Java, J2EE supports internationalization. You must remember to design an international solution from the first day.

Lesson 4: Avoid common mistakes in MVC

J2EE development is enough to mature, in the representation, most items use some of the MVC architectures, such as Struts. In such a project, the phenomenon I often see is misuse of MVC mode. Here are a few examples. Common misuse is all of the business logic in the model layer (eg, in the Struts Action bean). Don't forget, the model layer of the layer is still part of the layer. The correct way to use the model layer is to call the appropriate service layer service (or object) and send the result to the view layer. In terms of design patterns, the MVC represents the model of the layer should be implemented as an appearance of the business layer (FA? ADE). A better way is to use the business delegate mode in the Core J2EE Patterns. This section excerpts from the book excels the main points and advantages of making your model as business delegate:

Business delegate works to client business abstraction. It abstracts, and then hides the implementation of business services. Using Business Delegate, you can reduce business services that represent layer clients and systems. The degree of coupling. Depending on the implementation strategy, Business delegate can protect the client unusabogenic effects in the implementation of the business service API. Thus, when the business service API or its underlying, it is possible to potentially reduce the number of times the representation layer client code must be modified.

Another common error is to place a number of logic indicated in the model layer. For example, if the JSP page needs to be formatted in a specified manner or sorted data in a specified manner, some people may place the logic in the model layer, which is wrong place for the logic. In fact, it should be in a group of Helper classes used in the JSP page. When the business layer returns data, the Action Bean should forward the data to the view layer. Thus, there is no need to create excessive coupling between the model and the view, you can flexibly support multiple view layers (JSP, Velocity, XML, etc.). Also allow the view to determine the best way to display data to the user.

Finally, most of the MVC applications I have ever seen have a controller that is not fully applicable. For example, most Struts applications will create a basic Action class and complete all security-related features. All other Action beans are derived classes for this base class. This feature should be part of the controller, because if there is no security condition, first call the action bean (ie: model). Remember, one of the most powerful features of a well-designed MVC architecture is a robust, scalable controller. You should use this capability to strengthen your own advantages.

Lesson 5: Don't be bound by JOPO

I have witnessed many projects to use Enterprise Javabean in order to use Enterprise JavaBean. Because EJB seems to bring superiority and self-respecting performance, sometimes it is a coolness factor (COOLNESS FACTOR). And other times, it will cause J2EE and EJB to be confused. Remember, J2EE and EJB are not consent. EJB is just part of J2EE, J2EE is a series of technologies including JSP, Servlet, Java Message Service (JMS), Java Database Connection (JDBC), JaaS, Java Management Extensions (JMX), and EJB, and also related to how to use These technologies have established a set of guidelines and patterns of solutions.

If EJB does not need to use EJB, they may affect the performance of the program. Compared to old web servers, EJB generally has more requirements for application servers. All value-added services provided by EJB generally need to consume greater memory and more CPU times. Many applications do not need these services, so the application server is to compete with the application. In some cases, unnecessarily use EJB may cause the application to crash. For example, I have recently encountered an application developed on an open source application server. Business logic is packaged in a series of stateful session beans. Developers have a lot of "passivation" for these Beans in the application server. The client requires an application to deploy on a commercial application server, and the server is part of the client technology stack. The application server does not allow the "Passivation" function to be closed. In fact, the client does not want to change any set of application servers with its cooperation. As a result, the developer has encountered a lot of trouble. (It seems) interesting things is that developers don't give this reason why the code is implemented with EJBs (and still state session beans). Not only the developers will encounter performance issues, but their procedures are not working there.

In web applications, there is no formatted normal Java object (POJO) is an EJB powerful competitor. Pojo is a lightweight, unloaring an additional burden as EJB. In my opinion, the advantages of many EJBs, such as objects into the pool, estimated too high. Pojo is your friend, don't be bound by it.

Lesson 6: Data Access does not host O / R mapping

All WEB applications I have participated in providing users with data accessed from other places, and therefore require a data access layer. This is not to say that all items need to be identified and established such a layer, which means that the existence of such layers is not implicit. If it is an implicit data layer, the data layer is part of the business object (ie: business service) layer. This applies to small applications, but usually in contact with architectural guidelines accepted by large projects.

In summary, the data access layer must meet or exceed the following four standards:

Transparency

Business objects can use data sources in the event of a specific detail that does not know the data source. Since the implementation is hidden inside the data access layer, the access is transparent.

Easy to migrate

Data Access Layers make the application easy to migrate to other database implementations. The business object does not understand the underlying data implementation, so the migration only involves modifying the data access layer. Further, if you are deploying a factory strategy, you can provide specific factory implementations for the storage of each underlying storage. If so, migration to a different storage implementation means providing a new factory implementation for the application.

Try to minimize the complexity of the code in business objects

Because the data access layer manages all data access complexity, it simplifies the business object and the code of other data clients using the data access layer. Data Access Layer, not a business object, containing many code related to implementation (eg, SQL statements). This brings higher efficiency, better maintainability, and improves code readability.

Convey all data access in a separate layer

Since all data access operations are now delegated to the data access layer, you can see this separate data access layer as a layer that can separate other parts of the application with data access. This centralization can make the application easy to maintain and manage.

Note: These criteria do not explicitly call the demand for the O / R (object to the relationship) mapping layer. The O / R mapping layer is typically created with an O / R mapping tool, which provides an object to view and perceive the relational data structure (Look-and-Feel). In my opinion, using O / R mapping in the project is similar to using EJB. In most cases, it does not require it. For relational databases containing medium-size, multi-relational relational databases, O / R mappings become quite complicated. Due to increasing the intrinsic complexity of the O / R mapping solution itself, such as lazy loading, high-speed buffering, you will bring greater complexity (and risk) for your project. In order to further support my point of view, I will point out that many failed attempts of entity Bean (an implementation of O / R mapping) in Sun Microsystem, this is a problem that has been tortone from the 1.0 edition. In SUN's defense measures, some early issues are implemented on developers of EJB specifications. This proves the complexity of entity Bean to specify its own complexity. As a result, most J2EE architects generally believe that it is a good idea from entity beans.

Most applications can only perform a limited number of queries when processing their data. In such applications, an effective way to access data is to implement a data access layer that implements a series of services (or objects, or APIs) of these queries. As described above, in this case, an O / R mapping is not required. When you require query flexibility, O / R mapping is right, but remember: This additional flexibility is not available.

As I promised, in this article, I try to avoid the best practices of Chen. On the contrary, I have concentrated on my point of view about every architect must make every architect in the J2EE project. Finally, you should remember: J2EE is not a specific technology, nor is it forced to join some of the first letters in the solution. Instead, you should use the appropriate timing, appropriate place, use the appropriate technology, and follow the J2EE guidelines and more important practices in the J2EE itself.

转载请注明原文地址:https://www.9cbs.com/read-42986.html

New Post(0)