J2EE Design Pattern
Abstract: J2EE Design Pattern
</ Td> </ tr> <tr> <td height="35" valign="top" class="ArticleTeitle"> on J2EE design patterns script, PPT format.
J2EE multi-system mainly by the architecture design, the framework, as well as a number of design components.
A design model is a summary of practice, is the most direct the performance of OOP.
Master design pattern is a measure of the level programmers design the main basis.
</ Td> </ tr> <tr>
↑ Back
J2ee Column
Abstract: j2ee Column
* JSP: containers in the operation of the server process:
Vessels received a customer jsp file a request, it jsp file parser generation java servlet source files, then compile and then proceed to customer response.
* JSP syntax:
Directive # JSP
<% @ And%> settings and used only in the pages related to the properties of three commonly used commands
Page, include, taglib
1.page
<@ Page attribute = "value" attribute 2 = "2 value"%>
Page attributes:
Designated language scripting language, if repeated use, then use whichever is the first time
Example: <% @ page language = "java"%>
Java method specified procedures fragment of the names of properties and methods, including RMS attributes of the service, doGet, doPost
Example: <% @ page method = "doPost"%>
Designated import into the java package name and class name, the list "," separate, the use of this directive into many different packages
Example: <% @ page import = "java.io. *, java.util .*"%>
Content_type response to the outcome of the designated MIME types. The default type is "text / html"
Encoding format for the "ISO-8859-1" and the language attribute to the same language in common use as many instructions while
Whichever is first.
<% @ Page content_type = "text / html, GBK charset ="%>
Session = "ture | false" designated JSP pages use of any session, the default is true
<% @ Page session = "true"%>
ErrorPage = "error_url" designated abnormal Jump Pages
Example: <% @ page errorPage = "errorpage.jsp"%>
IsErrorPage = "ture | false"
JSP page that this is to deal with the abnormal website
<% @ Page isErrorPage = "true"%>
↑ Back
J2EE BluePrints in NetBeans IDE
Abstract: Teaching by example. This is the main theme behind the Java?? BluePrints Solutions Catalog, a new project from the Java BluePrints program. It consists of a set of guidelines and best practices and small applications to illustrate these guidelines on the J2EE 1.4 platform.
Originally, you had to download the catalog from java.net and deploy it to your local Sun Java System?? Application Server, or view a slimmed-down version online. Starting with NetBeans 4.1, however, the Solutions Catalog is integrated right into the IDE.
To open the Solutions Catalog, choose Help> Java BluePrints Solutions Catalog. The catalog viewer opens in the Source Editor.

Select any chapter in the combo box at the top of the viewer to open it. You can then click the Example tab to install an example on your computer and open it as a NetBeans project. You can install as many instances of the examples as you want. This is good if you want to use the examples as templates that you then tweak for your own uses. Of course, each example project is all set up and ready for deployment to the application server.
Not all of the examples available in the full Solutions Catalog have been converted into NetBeans projects yet. Presently, the following chapters are available:
- Web Applications
- Handling Command Submissions
- Creating Tabbed Views
- Server-Side Java Server Faces Validators
- Implementing Client-side Validation
- Web Services
- Accessing Web Services from J2EE Components
- Accessing Web Services from a Stand-Alone Java Client
- Designing Document Oriented Services
- Using a Schema-Defined Type to Represent an XML Document in a Service Interface
- Using String to Represent an XML Document in a Service Interface
- Updating Service Locator to Support Web Services
A new version of the Solutions Catalog will be release on the NetBeans Update Center around JavaOne.
↑ Back
Spring framework with improved J2EE Programming
Abstract: This paper presents an overview roughly IoC and details of the Spring. Spring framework has many functions, many of which function only in the differing views in this paper. From basic to complex dependency injection AOP operation, which formed the power of Spring, which is one of its main advantages.
Abstract
J2EE programming is becoming more and more complex. J2EE API has been developed into a complex programming and configuration of the complex network. In order to deal with this complexity, the new framework and methodologies are emerging. These frameworks are highly dependent on a called IoC (Inversion of Control, reverse Control) concept. This paper will explore some of the features of this method and the advantage that this approach and J2EE programming related, but also to become J2EE programming easier.
Introduction
Mark Twain is often quoted remark: "I…… on the reported deaths was an exaggeration." Now there have been a lot of. Net rumors, and that the complexity of the J2EE API can not be overcome as a group and EJB a framework to be very popular passenger perished (geek) Culture. From the academic or just imagination standpoint, it's not a big deal, but the fact is that J2EE/EJB API has been experiencing a Darwinian evolution. DCOM or CORBA projects have experienced readers will understand what I mean. The past, people were glad to hear EJB component model of our future. The reality is, people associated with the various aspects of J2EE has invested enormous. Discard previously announced that all the work and re-organization, this idea may seem justified, but it has not built on good business insight. EJB continue to develop, and terminology, practice, and also will be emerging framework (spring up), they make up for the shortcomings of the J2EE API. I said that was not "in Spring (up)", right?
I was a consultant, responsibilities is to help build large-scale distributed applications, and is usually J2EE applications. Therefore, I had the opportunity to experience many of the projects throughout the entire life cycle. In addition, I can also I have just completed a project in just learn things directly into a new project. In a sense my "natural selection" process accelerated. I can say that the recent Spring (more specifically IoC, reverse Control) has become increasingly integrated into my project has. In this paper, I will support or enhance J2EE project to explore the perspective of Spring. More precise to say that Spring framework to standardize many J2EE best practices, but also of similar (homogenize) Many everywhere in the J2EE model. We have to go to Spring huge system of a small part, the focus on (in my humble opinion) to help improve the functions of J2EE applications.
IoC Profile
Generally speaking, IoC is a correlation between the management of technology. Yes, It's that simple! No one is isolated, the same is true for the various targets. Application procedures in the target are interdependent. Programming approach to performance through such dependence is usually lengthy and error-prone. IoC framework will be good for the statement (through an XML configuration file) rather than programming to (the reliability of this approach worse) - connections between applications from the interdependence.
Free to use IoC development of the interface is a major principle. Programming Interface greatly enhance the flexibility of the applications, thus increasing the relevance of the statement. Interface through IoC configuration at runtime statement, and that can not be affected or less affect the actual application code of the "reconstruction (rewire)" association. This in a variety of IoC is repeatedly mentioned in the framework of a theme, in general, is good practice to be followed.
A small example
I like faster through examples to understand the concept. Below is the use of a group of IoC example you will see, these examples is the complexity of each progressive. Most people use at the outset IoC containers are using its dependency injection (inject dependency) functionality - namely, the statement of objects and linking. IoC help create more use of clean code and, if necessary, rebuild the relationship between objects, in general for these codes will be more flexible, more easily. IoC far more than the merits of dependency injection, and its expansion is dependent on the injection procedure as a starting point.
We will build a simple example of dependency injection began. The first example has been used to clarify that the two concepts. IoC concept is the first time in the construction and operation of the capacity of related object, the second is the integration and interface code and the flexibility. First presumed architect submitted the UML shown in Figure 1.
Figure 1. Interface can be inserted and
This indicated that a small example of temperature measurement system. Sensors are several different types of object, but to realize ProtocolAdapterIfc interface, so they will be inserted TemperatureSensor targets, which are interchangeable. TemperatureSensor necessary, a system of entities must be aware of the need to generate and the sensor and associated ProtocolAdapterIfc targeted to the specific type. In this example, the sensor could be based on command-line parameters, a row in the database or configuration file attributes. This case is not enough to pose a challenge or display a complex framework, it is sufficient to set out the basis of IoC.
However, Imagine: in a very complex applications in such a situation, there have been frequent, and you also want to dynamically - at least in the external - to change object association. DummyProtocolAdapter a hypothetical, and it is always returned to the 42 of this value, use it to be tested. Why not provide a single unified framework? — Let developers can rely on the framework for a consistent and external configuration of the way to establish the link between the factory and did not cause single element type (factory singleton classe) unusual increase. This sounds may be no big deal, but it will depend on the simplicity of IoC.
We use a TemperatureSensor category, it is the realization of a class ProtocolAdapterIfc interface connected. TemperatureSensor will use the category to be commissioned by the temperature. UML as shown below, in the realization ProtocolAdapterIfc and subsequently can be used for related applications in a number of categories. We will use IoC framework (in this case it was Spring) statement to be used ProtocolAdaperIfc realized. Spring will be in operation, establishing association. Let us first look at XML code, it will TemperatureSensor example of an object and its association with ProtocolAdapterIfc achieve together. The code shown below: <bean Id="tempSensor" class="yourco.project.sensor.TemperatureSensor"> <property name="sensorDelegate"> <ref bean="sensor"/> </ property> </ bean> <! - Sensor to associate with tempSensor -> <bean id="sensor" class="yourco.project.comm.RS232Adapter"/>
Read these codes, for the purpose should be very clear. We configuration Spring TemperatureSensor instantiated object and its associated RS232Adapter, to achieve a ProtocolAdapterIfc interface category. To TemperatureSensor associated with the change has been the realization of the need to change is the only sensor bean marker in the class value. If realized ProtocolAdapterIfc interface, TemperatureSensor no longer concerned about what the association.
Application procedures for this is quite simple. We must first access Spring framework, it will be pointing in the correct configuration file, and then by name to obtain tempSensor Spring object example. Below are the corresponding code:
ClassPathXmlApplicationContext appContext = new ClassPathXmlApplicationContext (new String [] ( "simpleSensor.xml")); BeanFactory bf = (BeanFactory) appContext; TemperatureSensor ts = (TemperatureSensor) bf.getBean ( "tempSensor"); System.out.println ( "The temp is: "+ ts.getTemperature ());
Can be seen, the code is not very difficult. The first is to start Spring and designated use of configuration files. Followed by name (tempSensor) quoted Bean. Spring use of such a mechanism: Based on the description of simpleSensor.xml documents created with the object and other objects related. It is used for injection of dependence - in this case, it will be passed as a parameter passed to sensorDelegate () method and examples of the object and its RS232Adapter TemperatureSensor object association.
In comparison, the use of Java programming accomplish this task is not difficult. As follows:
TemperatureSensor ts2 = new TemperatureSensor (); ts2.setSensorDelegate (new RS232Adapter ());
Purist who might think that this is actually a better way. Only a few lines of code, and may be more readable. True, but this method is much less flexibility.
- Free-for-all and can be different for different layers of different targets to achieve. For example, if a Web layer components need to target new business from the additional functionality, you need the business objects and Web-related objects, as in the example above TemperatureSensor practices. It will be "injected" to the Web object to the use of time.
- To reconfigure the structure of the entire application process, means that the data source can easily change. For example, or for the deployment of different scenes to create a different configuration file, or test scenarios for the creation of more useful, different configuration files. In the test scenario may be injected to achieve analog interface object, and not the real target injection. Later on, we will introduce one such example.
The above-mentioned examples may dependency injection is the most simple form. Use the same strategy, we are not only related to the different categories, can also attribute in the type of installation. Such as a string, integer or floating point numbers, such as properties, as long as the pattern of access to a JavaBean, can Spring configuration files through them into categories. We can also, through the constructor function to create objects and installation attribute or bean used. Its syntax than through only attribute set slightly complicated.
All of this use of a flexible configuration of the statement completed. No need to change code, dependent on the establishment of the association are all Spring difficult task to complete.
Spring - the standardization of positioning mode
I have been positioning services will be regarded as a good model for J2EE major component of the standard. Not familiar with the term for people who can understand it: We are generally considered typical J2EE applications by a number of layers. Usually have Web layer, service layer (EJB, JMS, WS, WLS controls), as well as database. Generally, the completion of a request for the "Find" service are included in a number of ways. Service Locator (locator service) model, these methods will be packaged in a generation or find hidden given the complexity of the factory class is a good idea. This reduces JNDI or Web-operation will only lead to confusion of the other services to increase product code. Previously appeared in the Spring, which is usually proven by the test (tried-and-true) Singleton class to achieve. Singleton / Locator / Factory patterns can be described as:
Figure 2. Positioning mode of sequence diagram
This is spread throughout the Web controller code in the increase in the JNDI find a tremendous improvement of the code. It was cleverly hidden in the factory internal collaboration category. We can use to improve the Spring term. In addition, the solution will be applied to EJB, Web services, asynchronous JMS calls, and even on WLS control services. From Spring to achieve this positioning mode considered a variant of the business services between the abstract and homogeneity. In other words, the Web Controller developers can really do not consider their use of the type of services, a similar "WLS control" but more generic concept.
IoC framework greatly improved the effectiveness of this model, and effectively abolished the singleton complex and special code to achieve it. Through borrowing, the introduction of the concept, we actually no additional code will be able to build a very powerful and ubiquitous in the Service Locator pattern. To this end, at the outset there is a simple request that the operation of Web developers should be devoted to achieving those things interface. This is basically EJB programming has been passed, it does not mean that the operation of the development of Web services must be dealt with through the EJB to achieve. They may just ordinary Java objects or Web services. The point is through the interface (this can be realized for all-out) to the preparation of service procedures, and run-time configuration can be handled by Spring.
Spring is very suitable for Service Locator pattern, because it is more or less able to deal with the reunification of different types of objects. Through a little planning and large-scale use of IoC, we can in a number of ways to handle the most common targets, and they do not have the characteristics of the (EJB, POJO, and so on) how, and does not cause the increase of Singleton factories. This makes Web-programming easier and more flexible.
Let us first look at a model can be applied on such EJB examples. We all know that the use of EJB may be the most complicated, because the application of an activity to introduce EJB remains to be done. If you are using Spring, the proposed EJB interface with non-specific expansion in the business EJB interface. This serves two purposes: to maintain the two automatic synchronization interface, as well as help ensure that business services to non-realization of EJB is interchangeable for testing or removal (stubbing). We can use Spring inherent practical tools to locate and create EJB example, at the same time we are dealing with all the difficult work. Corresponding code shown below:
<bean Id="myBizServiceRef" class="org.springframework.ejb.access. LocalStatelessSessionProxyFactoryBean"> <property name="jndiName"> <value> myBizComponent </ value> </ property> <property name="businessInterface"> < value> yourco.project.biz.MyBizInterface </ value> </ property> </ bean>
Bean can be searched and then start using it, as follows:
MyBizInterface myService = bf.getBean ( "myBizServiceRef");
This will be returned to the Spring dynamic creation and packaging the underlying objective (in this case is a local example of EJB) an object. This method is very good, because it is entirely hidden we deal with the fact that EJB. We will be operating a simple interactive interface proxy object. Spring has been based on the "real" business objects dynamically generated thoughtful consideration of the object. The packaging of course, is the object of Spring location and retrieval to be quoted by the local EJB. In addition, you will note that this form of the code in front for the retrieval tempSensor identical object code.
So if we change our minds and to use ordinary Java objects to achieve operational components, or may be in the test, we want to use a return to the "constant (canned)," the response has been removed (stubbed) heavyweight EJB object to the replacement of the how ? Use IoC and Spring, Spring context documents through changes can be easily achieve these goals. We just need to use a little more conventional things (such as we have in the first Spring seen in the example) to replace EJB agents can be connected:
<Bean id = "myBizServiceRef"
Class = "yourco.project.biz.MyStubbedBizService">
</ Bean>
Please note that I only changed the framework of the Spring Back to the details of the contents, no changes bean id. The end result is targeted business solutions remain unchanged and it looks exactly the same as before:
MyBizInterface myService =
Bf.getBean ( "myBizServiceRef");
Biggest difference is obviously the business interface to achieve the target is now an ordinary Java Objects (POJO) support, and the only one interface has removed (stubbed) version. This unit testing, or to change the characteristics of business services brought great convenience, and the client code little impact.
Spring to standardize the use of anomaly
Spring is a major contribution to the "template" of the code block. This is pure JDBC Programming performance in the most obvious. We have written code with the following features:
- Create a database connection, it can be created from a pool.
- Construction and submit a query strings.
- Iterative data and the results sent to the closure domain object.
- Deal with different stages of the large anomaly.
- Finally remember that the preparation of the code block to close the connection.
But throughout this code often to a greater or lesser extent "of the model." Usually, this is harmful, not only because of the code do not need to increase, but also because some things may be omitted, such as the closure of a very important link, if it did not materialize, could lead to the leakage of data resource pool.
Although I am sure we have repeatedly wrote such "model" code, but will be Spring JDBC methods and achieve direct control, its results will be interesting and contrasting. "Traditional" JDBC may achieve the following:
Connection con = null; try (String url = "jdbc: / / blah.blah.blah"; con = myDataSource (). GetConnection (); Statement stmt = con.createStatement (); String query = "SELECT TYPE FROM SENSORS "ResultSet rs = stmt.executeQuery (query); while (rs.next ()) (String s = rs.getString (" TYPE); logger.debug (s + "" + n);)) catch (SQLException ex ) (logger.error ( "SQL ERROR!", ex);) finally (con.close ();)
For some of the ways to do that. First, it is effective! The code is there will not be any mistakes. It will connect to the database, and from 'SENSOR' table to obtain the necessary data. The basic problem stems from the lack of abstract. In large-scale applications, must repeatedly cut and paste this code, or at least there will be other similar cases. The larger problem is that it relies on programmers do "do the right thing." We all know that, regardless of database operations is the result of what the sentence must be used to finally close the database. Sometimes we forget to do the do. I, like all of us feel guilty!
Prepare a small framework to solve this problem would be very easy. I believe we all have done so, but why not allow Spring to help us deal with this problem? I can not guarantee that I can come up with a more clean, more elegant solution. We look at Spring framework is how to deal with such a model JDBC scene.
Spring support a wide range of JDBC, Hibernate, JDO and iBatis template. Template model using the concept, and it converted to legitimate programming terminology. For example, the following code snippet encapsulates all the steps listed above:
DataSource ds = (DataSource) bf.getBean ( "myDataSource"); JdbcTemplate temp = new JdbcTemplate (ds); List sensorList = temp.query ( "select sensor.type FROM sensors," new RowMapper () (public Object mapRow (ResultSet rs, int rowNum) throws SQLException; return rs.getString (1);)));
This brief JDBC programming code to eliminate the lengthy, on behalf of the above-mentioned model of thinking. Please note that we use the Spring IoC enquiries to find the source of the data. Spring is also supporting the inspection has been extremely abnormal use of inspection so many JDBC inspection will be re-mapped to the anomaly is usually more useful and more friendly level of abnormal structure of the inspection. Spring in the context of documents similar to the configuration of the data source code below:
<bean Id="myDataSource" class="org.apache.commons.dbcp.BasicDataSource"> <property name="driverClassName"> <value> org.gjt.mm.mysql.Driver </ value> </ property> < property name = "url"> <value> jdbc: mysql: / / romulus / sensors </ value> </ property> <property name="username"> <value> heater </ value> </ property> <property name = "password"> <value> hotshot </ value> </ property> </ bean>
In this case, we use Apache commons toolbox includes a basic data source. It does not mean that we can use it. We can change the configuration used in the configuration and load JNDI data sources. Spring offers some practical tools and features to IoC stored in the configuration and return to the JNDI object. For example, if the allocation and use of JNDI context associated with the data source, you can enter the following code to replace the previous data source configuration:
<bean Id="myDataSource" class="org.springframework.jndi. JndiObjectFactoryBean"> <property name="tempSensorDS"> <value> ConnectionFactory </ value> </ property> </ bean>
The code provided by the Spring highlighted the flexibility on the test forms. The code can be in the "containers" operation (from the View JNDI data sources), after minor modifications can be in the "containers," running.
Although the template mechanism applies only to certain occasions, but we can generalize this concept, it will be used more widely occasions. For example, one will have to check abnormal changes did not check abnormal In addition, it may provide some exception handling for the middle or unified strategy exception handling mechanism would be helpful. We can also use the basic mechanisms underlying abnormal "softening" more in line with Italian people. We will be able to CommunicationsUnreliableException PacketFrameParityFaultException softening. The re-mapping of the soft abnormal situation that might not be so serious, we can reconsider the request.
Spring has had a similar packaging EJB call (introduced in the last one) mechanism, but is regrettable that it did not have any "generic" thing, at least in the sense abnormal softening of the case. But Spring is a very robust AOP (aspect-oriented programming) framework, we can use it to approximate such acts. Below is a softening on this field of application (recognized) careful design examples.
Let us look at this paper have already begun to explore some of the concepts. In the first quarter, we introduced a small remote sensors based on the application. Now we continue to explore this example. We will be a simple sensor interface start, the interface code as follows:
Public interface ProtocolAdapterIfc (public Integer getRemoteSensorValue () throws CommChecksumFault, CommConnectFailure, CommPacketSequenceFault;)
This is not what is so special about. Clearly realize the interface of any person will be a long-range value and return it to the caller. In the meantime caller may have to face some terrible disaster, the interface may have been thrown out of the inspection is unusual example.
Next we see a realization of the interface procedures. Implementation of the category is CarrierPigeon ProtocolAdapter, similar to the code:
Public class CarrierPigeon implements ProtocolAdapterIfc (private boolean isTired = true; private boolean canFlapWings = false; public Integer getRemoteSensorValue () throws CommChecksumFault, CommConnectFailure, CommPacketSequenceFault (if (isTired & &! CanFlapWings) (throw new CommConnectFailure ( "I'm Tired!")
return new Integer (42);))
For the sake of simplicity, has been omitted here attribute getter and setter methods. When you call getRemoteSensorValue (), CarrierPigeon method will check whether the use of excessive and the possibility of implementing it. If it indeed is the use of excessive and can not be implemented, we will not be able to receive any value, must be thrown out CommConnectionFailure, it is a check has been abnormal. Up to now, has been good. But do not pleased too early! I have decided not application programming staff in response to "fatigue carrier pigeon." It can be packaged in some kind of object and purpose to be caught before, but must deal with 20 different sensors. In addition, I prefer these things to deal appropriately transparent, with the increased understanding of the system may be abnormal changes in the procedures for handling logic. I want is a compatible API, the application programming staff to use it, and with the passage of time can be changed or improved. I would like to modularity exception handling, and allow application programming staff can not handle the soft check abnormal, and not very hard. Spring very much in line with the situation. Below are using this strategy points:
- Definition of a soft check anomaly has been the elimination of the minimum interface. This is the application programming interface will be used.
- Use Spring AOP structure, the development of a client calls and targeted to intercept calls between, in this case it was the "carrier pigeon."
- Using Spring installation of the interceptor and run.
First look at the soft Interface:
Public interface SensorIfc (public Integer getSensorValue ();)
Please note that in the limited scope of the method can rename it more meaningful. Also had inspected anomaly can be eliminated, as did the same here. Next, there could be even more interesting is that we want to get the Spring into its call stack of interceptors:
Import org.aopalliance.intercept.MethodInterceptor; public class SensorInvocationInterceptor implements MethodInterceptor (public Object invoke (MethodInvocation invocationTarget) throws Throwable (/ / Return object reference Object o = null; / / Convert it to the protocol interface type ProtocolAdapterIfc pai = (ProtocolAdapterIfc) invocationTarget.getThis (); try (o = pai.getRemoteSensorValue ();) catch (CommChecksumFault csf) (throw new SoftenedProtocolException ( "protocol error [checksum error:" + csf.getMessage ());) catch (CommConnectFailure cf) (throw new SoftenedProtocolException ( "protocol error [comm failure]:" + cf.getMessage ());) catch (CommPacketSequenceFault psf) (throw new SoftenedProtocolException ( "protocol error [message sequence error]" + psf.getMessage ()); return o);))
Spring MethodInterceptor through the realization of such interface and insert Spring system (we will discuss later), we will MethodInvocation parameters were realistic objective method. This will extract the real object we want. Remember, we changed to be called as SensorIfc the interface to achieve the target ProtocolAdapterIfc. We are doing this in order to streamline the call, is to remove all of the checks have been abnormal. The only call interceptors might be thrown to capture any of the examination anomalies, and they will be used SoftenedProtocolException the goal of re-packaging methods. In fact, we only re-packaged news, but to be aware of. SoftenedProtocolException expanded RuntimeException, which is not an abnormal examination. The end result of the operation is application developers do not have to deal with any inspection has been abnormal. If they really want to handle exceptions, they only (non-mandatory to) deal with a: SoftenedProtocolException. Yes!
So, how can we allow all this Spring completed? The answer is they must have the correct configuration files. We now to take a look at the configuration file, and understand the working principles:
<! - TARGET OBJECT -> <bean id="protocolAdapter" class="yourco.project.comm.CarrierPigeon"> <property name="isTired"> <value> true </ value> </ property ≷ <property name = "canFlapWings"> <value> true </ value> </ property ≷ </ bean ≷ <! - INTERCEPTOR -> <bean id="sensorInterceptor" class="yourco.project.springsupport. SensorInvocationInterceptor"/> <! - WIRE EVERYTHING UP, HAND BACK TO THE USER -> <bean id="temperatureSensorOne" class="org.springframework.aop.framework. ProxyFactoryBean"> <property name="proxyInterfaces"> <value> yourco. project.interfaces.SensorIfc </ value> </ property> <property name="target"> <ref local="protocolAdapter"/> </ property> <property name="interceptorNames"> <list> <value> sensorInterceptor < / value> </ list> </ property> </ bean>
Section by section, we look at the code, you can see it than we see in front of the Spring configuration files is slightly complex. "TARGET OBJECT" Note the following section I designated as a call to the target class. Remember that the interceptor had imported a parameter to indicate which target? This is the working principle. Based on the parameters of Spring now know to which object transfer come. "INTERCEPTOR" Below is the code section in the target before calling the method category. At this time, if the target has been dished out such inspections abnormal, it is necessary to begin to deal with anomalies, and softening. Spring it will be associated with the target type. The final one is to link the various elements. Users to request bond temperatureSensorOne bean in the bean. ProxyFactoryBean will generate and return to a proxy class, which used to achieve yourco.project.interfaces.SensorIfc interface. Target of course, is protocolAdapter bean, it examples from yourco.project.comm.CarrierPigeon support. Acting as long as the users call the method call interception and inserted in the bean-button sensorInterceptor, by yourco.project.springsupport.SensorInvocationInterceptor support. Please note that the number of interceptors can be used, because the attribute is a list, so many interceptors will be linked to the object method call, this is a very useful concept.
Run the application, in accordance with the inserted CarrierPigeon values, we can see some interesting behavior. If we did not use excessive CarrierPigeon and can, and we will see this output:
The sensor says the temp is: 42
Clearly "Pigeon" good condition and no problem, and calculate the temperature was 42. If CarrierPigeon Spring Festival, owing to a change in the value of the possible cause of the "carrier pigeon" the use of excessive or not, and we will be shown the following results:
Yourco.project.exceptions.comm.SoftenedProtocolException: protocol error [comm failure]: I'm Tired! At yourco.project.springsupport.SensorInvocationInterceptor.invoke (SensorInvocationInterceptor.java: 57) at org.springframework.aop.framework.ReflectiveMethodInvocation. proceed (ReflectiveMethodInvocation.java: 144) at org.springframework.aop.framework.JdkDynamicAopProxy.invoke (JdkDynamicAopProxy.java: 174) at. getSensorValue (Unknown Source) at yourco.project.main.Main.main (Main.java: 32 )
In such circumstances, "Pigeon" or the use of excessive or not and, therefore, the result was the SoftProtocolException, and attached a note in the news: "I'm tired!" Gouku!
I hope that people can begin to understand the powerful and Spring multiple functions. Spring framework emerged, and a developer of programming toolbox in true "Swiss army knife." Spring in achieving allow developers to focus on application of the basic components of this commitment as legend has done a good job, and this is precisely to the popularity of its business logic. Spring in your J2EE from some of the complicated aspects of liberation. Spring's powerful because it can make most things look like very ordinary Java objects, regardless of their nature or origin. Since Spring shoulder their own creation, and distribution of the burden of association, then the developers to do was to master the use of objects rather than the method of object structure. Spring is like in the grocery store to buy pre-cooked meals. You do decide to eat only what it home, heating, and then eat!
General Description
Spring is a very robust lightweight framework, it J2EE/EJB excellent compensate for the environmental deficiencies. Spring really great point is that it is not polarised. You can in a very simple manner using Spring (as I did), but the establishment of the common association, as a positioning mode to achieve. Later on, you will find its amazing features, and soon it will be more and more demands.
I found a Spring surprises are provided by the testing flexibility. It is now conducted through Junit increasing emphasis on test modules, which increases the test, rather than to reduce testing. J2EE containers used to test the extremely complex, so difficult. This stems from the difficult situation and containers business logic framework for the coupling between services. With Spring configuration mechanism to achieve can dynamically switch, and this will help to business objects from the container released. As we have seen, If you only want to test Web components, will be replaced by the activities of its agents or EJB has removed a business services and will not cause too much of an impact. With JDBC or Hibernate data access object, we can use a simple JDBC common, non-XA data sources connected to test these components, and to make them for a seamless, replacing it with a healthy based on JTA, the corresponding JNDI Link. Conclusion: If the code easy to test, and therefore a lot more testing, then quality will improve.
Concluding remarks
In this paper, a rough summary of IoC introduced, and details of the Spring. Spring framework has many functions, many of which function only in the differing views in this paper. From basic to complex dependency injection AOP operation, which formed the power of Spring, which is one of its main advantages. According to the problem need to use more or less IoC function is a very attractive idea, and I think that usually in the area of complex J2EE programming is popular. Now after reading the article, I sincerely hope that it will help you, and can be applied to your work. Welcome at any time to provide feedback!
↑ Back
J2EE questions LIBRARY (of the answers)
Abstract: Java Chinese issue has been plaguing many beginners, and if the Java System of Chinese issues principle, we will be able to take on the Chinese problem can be fundamental solution. .
A basic quiz
1. Category below what can be inherited?
Java.lang.Thread (T)
Java.lang.Number (T)
Java.lang.Double (F)
Java.lang.Math (F)
Java.lang.Void (F)
Java.lang.Class (F)
Java.lang.ClassLoader (T)
2. Abstract classes and interfaces distinction
(1) interface can be multiple implements, an abstract class can only be a single extends
(2) interface only definition of an abstract class can be defined and the realization
(3) The default interface for the definition of the field: public static final, abstract field of default is "friendly" (this package will be seen)
3.Hashtable principle, and tell the difference between HashMap and Hashtable
HashTable principle: the key code through the nodes identified nodes are stored, that is the key to the node code k, using certain function H (hash function), by function of the H (k), the interpretation of this value Node storage address.
HashMap and Hashtable very similar, but non-synchronous HashMap (unsynchronizded) and can be null as the key code.
4.forward and redirect the difference
Forward: an internal transfer in servlet
Redirect: Redirect, 2nd request, the second request will be lost, the first attributs / parameters, etc.
5 What is Web containers?
Achieve J2EE specification web application of the agreement. The agreement defines the procedures for running web environment, including: concurrency, security, life-cycle management.
6. Explained below on the terms J2EE
(1) JNDI: Java Naming & Directory Interface, JAVA naming directory services. Main function is to provide: a directory system for the rest of the application in its own index above left to meet quickly find and positioning Distributed Application functionality.
(2) JMS: Java Message Service, JAVA news services. Main various communications between applications. Including peer-to-peer and broadcasting.
(3) JTA: Java Transaction API, JAVA affairs services. Provide distributed transaction services. Application simply calls its interface can be provided.
(4) JAF: Java Action FrameWork, JAVA security authentication framework. Provide some security control framework for the development and deployment through various custom realize their individuality security control strategy.
(5) RMI: Remote Method Interface, Remote Method Invocation
7.EJB is based on the technology? SessionBean and EntityBean and tell the difference between StatefulBean and StatelessBean distinction.
EJB including Session Bean, Entity Bean, Message Driven Bean, based on JNDI, RMI, JAT, and other technology.
SessionBean in J2EE application process be used to complete some of the server-side operations, such as access to the database, called other EJB components. EntityBean is used to represent applications used in the data. For clients, SessionBean is a non-persistent objects , it implements some of the server running on the business logic; EntityBean is a persistent object, which represents a lasting memory stored in the view of the target entity, or an existing enterprise applications to achieve entities.
Session Bean also can be further broken down into Stateful Session Bean and Stateless Session Bean. Both the Session Bean logic of the system can be placed on the implementation of the method, different from the Stateful Session Bean can record the caller's state, it is usually to said, a user should be a relative of Stateful Session Bean entities. Stateless Session Bean Although he is logic components, but he is not responsible for recording user state, that is to say when a user calls Stateless Session Bean when EJB Container will not find specific Stateless Session Bean entities to implement this method, in other words, very few users may be in the implementation of some of the methods Stateless Session Bean, Bean will be the same in the implementation of the Instance. memory from the past , Stateful Session Bean and Stateless Session Bean, the Stateful Session Bean J2EE Server consume more memory, but Stateful Session Bean has the advantage is that he can maintain the status of the users.
The analytical method 8.XML
Sax, DOM, JDOM
9 What is a Web Service?
Web Service is to enable the original isolation of information between sites can communicate with each other, sharing a proposed interface.
Web Service by using the Internet to a unified, open standards, such as HTTP, XML, SOAP (Simple Object Access Protocol), WSDL, etc. So Web Service can support any of these standards in the environment (Windows, Linux) used.
Note: SOAP protocol (Simple Object Access Protocal, Simple Object Access Protocol), it is a decentralized and distributed environment for the exchange of information networks XML-based communication protocol. Under this agreement, software components or applications through standard HTTP protocol to communicate. Its design goal is simple and scalable, which helps large number of heterogeneous processes and interoperability between platforms, so that the application can be a wide range of user access.
Advantages:
(1). Cross-platform.
(2). SOAP protocol is based on XML and HTTP these industry standards, are all important corporate support.
(3) the use of SOAP, the data are not ASCII text mode binary transmission, debugging is very convenient and because of that, its data easily through the firewall, the firewall does not require a separate procedure to open a "loophole."
(4) In addition, the technical difficulty of achieving WebService than CORBA and DCOM much smaller.
(5). To achieve B2B integration, EDI relatively sound and more complicated; WebService and can be used to achieve low-cost, small companies can use.
(6) in the C / S process, the website can be achieved without WebService refresh the overall deal with the server and take a few.
Disadvantages:
(1). WebService use of the XML data package will lead to a large amount of data in the network transmission.
(2) does not provide for any WebService norms and implementation of the relevant details, including the object model, programming languages, this point, as it CORBA.
10. Multithreading There are several methods to achieve, what are? There are several synchronization method are?
Answer: There are two multi-threading method, namely inheritance Thread of the Runnable interface simultaneously with the realization of achieving two were synchronized, and notify wait
11.JSP dynamic and static INCLUDE INCLUDE difference?
Jsp with dynamic INCLUDE: include actions to achieve
It always checks the changes contained in the document, contains suitable for dynamic pages, and can be used with parameter include pseudo-static INCLUDE Codes, will be contained in document examination will not change applies to contain static pages
<% @ Include file = "included.htm"%>
Second, the Java programming procedures and operating results
1.Java programming, printing of the current moment yesterday
(Public class YesterdayCurrent
Public void main (String [] args) (
Calendar cal = Calendar.getInstance ();
Cal.add (Calendar.DATE, -1);
System.out.println (cal.getTime ());
)
)
2. Document literacy, and the realization of a counter
Public int getNum () (
Int i = 1;
Try (
String stri = "";
BufferedReader in = new BufferedReader (new FileReader (f));
While ((stri in.readLine ())!= = null) (
I = Integer.parseInt (stri.trim ());
)
In.close ();
) Catch (Exception e) (
E.printStackTrace ();
)
Return i;
)
Public void setNum () (
Int i = getNum ();
I + +;
Try (
PrintWriter out = new PrintWriter (new BufferedWriter (new FileWriter (f, false)));
Out.write (String.valueOf (i)); / / encoding may be reasons, the write directly int, it would appear java coding and coding confusion windows, insert the String
Out.close ();
) Catch (Exception e) (
E.printStackTrace ();
)
)
3. Pointed out that the operating results of the following procedures:
Class A (
(Static
System.out.print ( "1");
)
Public A () (
System.out.print ( "2");
)
)
Class B extends A (
(Static
System.out.print ( "a");
)
Public B () (
System.out.print ( "b");
)
)
Public class Hello (
Public static void main (String [] ars) (
A ab = new B (); / / here the implementation of the results: 1a2b
Ab = new B (); / / here the implementation of the results: 1a2bab
)
)
Note: the static code of the category, can be seen as the first category is loaded (the virtual machine loading) implementation of the code, and for the loading of, first of all, to the implementation of its base class structure, further implementation of its own structure
4. Write a model example Singleton
Public class Singleton (
Private static Singleton single = new Singleton ();
Private Singleton () ()
Public Singleton getInstance () (
Return single;
)
)
Third, the database
1. Delete the duplicate records Table
If duplicate records to be exactly the same record, then: (sql server2000 under test pass)
Select distinct * # into tmpp from tid
Delete from tid
Insert into tid select * from # tmpp
Drop table # tmpp
If id primary key (figure 1 by the kind of self), then: (sql server2000 under test pass)
Delete from tableA where id not in
(Select id = min (id) from tableA group by name)
2.delete from tablea & truncate table tablea difference
Truncate statement fast implementation, accounting for less resources, and only delete the log records page;
Delete the deletion of records on each require logging
↑ Back
How to develop J2EE automation project
Abstract: Let your project for constructing and running is very easy, because in fact you can step on the command line to create a building. This means that you can easily let a computer you are running for a day of Construction. Otherwise, you have to put a development staff from time to time to use a command line build document.
Editor's Note the phrase: Pragmatic Project Automation, Mike Clark to provide you with a powerful way to automate some of your software projects: one-step Ant to build (one-step builds), with CruiseControl continuing according to plan time to build (scheduling continuous builds), click on the button for the release of the software, easy to install and deploy applications, through email, RSS, your cell phone, and even lava lamp (lava lamps) to monitor the construction and operation procedures. Examples include methods are easy for beginners to practice, even Confirmed also have more advanced topics can teach them some new things. In this article, he described the automation project will bring you the benefits of the outline.
You about to be delivered tomorrow morning for a key demonstration version of the software. Wearing a suit sales mouth blowing bubbles show you the company's new application to support some very important rich. As you are looking for feel on the keyboard, your boss you have to stand next to remind you of this demonstration project will probably get this project finished, or so. Do not have any pressure!
Construction and testing step
For those who are in your "must have" feature of the display after the importation of the last line of code, almost all of the noon. IDE your favorite show your code compiled and adopted the unit testing. But when he integrated into the rest of the system, you can code as expected, as normal? In order to clarify it, you update your local work area, in order to synchronous version control system now in the document. Then you run the project Construction of the one-step process:
$ Ant
This command compile all the documents code Running Below Ant Construction of the configuration file of all the units tested.
List 1:
basedir=”.”>
<formatter Type="brief" usefile="false" />
When you write code, you in your IDE frequently click on the button to facilitate the construction of the identification of all things compiled. You have also been keen on when your JUnit test passed, happy to see a green (unit testing the success of signs), and then you use JUnit test runner (JUnit test runner) into your IDE of. But not the team that everyone in the office as you did like this IDE, and you do not want to do one in every building, someone will have to start IDE. Construction documents and the use of the IDE you separation, each team in the one-step people can be continued to build and test items. (Item using Maven to create one-step building.)
Do not surprised, build successful, and you realize that you are once again the world's great programmers. Not only in the code, do you bring this process of building confidence, he also allows you to the project in the IDE, you build confidence.
Feeling very good, you upload the document has been changed and those who avoid trouble. In order to prepare for demonstrations, many of you still do, you need to leave the first time earlier to participate in your son's tee-ball games. Clock tack the echoing…
Bubble crisis
Back to the office after lunch the road, you took note of the red in the boiling lava lamp (such lights lamp in a special liquid materials). Oh! When you want to leave to eat when the green lights are jubilant braved the bubble (Note all normal procedures). You leave, you project on schedule for the construction of the machine to the test now try to build and version control resources (version control repository) code. But the terrible mistake.
Allow you to run for the Construction of the project is very easy, because in fact you can step on the command line to create a building. This means that you can easily let a computer you are running for a day of Construction. Otherwise, you have to put a development staff from time to time to use a command line build document. Instead, you use CruiseControl settings in your project-specific building machine in a certain time interval automatically create Construction, the config.xml file as shown below:
List 2:
CruiseControl this config.xml file every five minutes so that was a wake-up, testing your CVS project resources, and see whether they need to build. Only when someone in your team changes a document already exists, or by adding a new version of the document in the control of resources, CruiseControl to try to create a building. He relies on how to use Maven, or an Ant build files for your project to create a building. You can use CruiseControl is set to run a cc-Ant build.xml Construction of the document, as follows:
List 3:
basedir=”checkout”> />
Cc-build.xml delete your document adopted at the last building projects at the copy and resources from the CVS download a copy of the new guide project operation Construction of the process. He then automatically runs the same in your command line compiler and testing project bulid.xml document. Running build documents, CruiseControl Construction issued to all registered results of the issuer. (Using Maven project also used the CruiseControl, but it Bishui set with the use of some of you do not like the other version control systems to monitor changes)
Every five minutes to do all these work again is a easy task, which is why you like CruiseControl to let you do. When you first set up when it seems too much trouble, but you have learned to appreciate the timely feedback to you the value of information. Five minutes of schedule task is compiling all of the code and run the unit test, made a quick integrity of the testing. CruiseControl you with a complete set of system set up to operate in less frequent intervals, the implementation of the test. If five minutes Construction failed, it would not be there more than five minutes. This allows you to more easily locate and repair the problem, thereby saving you valuable time. If in the last five minutes, and no change was submitted, then CruiseControl remain dormant.
, Construction failed! CruiseControl ignited a red lava lamp is a good thing, because you may miss your e-mail filled with the Construction Write box failure email. Anxious to find the root of the problem, you open the web page of building a state that you forgot to rush between upload a new document. This is very embarrassing, but at least you can now build in the earlier restoration demonstration before the complexity of the issues involved as to lead to a nightmare of the debugging session.
Rapid release
Soon after, a team that everyone in the office upload their code. Now you are ready to create a distribution of documents to demonstrate the deployment of its servers. But before you proceed only in a limited time, release process includes the following tedious steps:
1. Trunk road test in the code
2. Version control in the construction of a branch version
3. Proofreading version of the content branch
4. Construction and testing version of the code branches
(Repair all the problems)
5. This version of the package all of the files to a document circulated
6. Testing of the contents of the paper distributed
7. Version control of the branch for the label version
8. The distribution of documents to QA
This is up to you to the steps! In fact, the release of your software is always a time-consuming and error-prone process. Therefore, you can not always release a new version of your software. You have to release memories in the process and all the steps to correct input all the necessary orders of the pressure felt tired. Now your item step-by-step process of the release are automatic (or even with documentation) with a number of operators as the release button script.
Demonstration will have to spend a little preparation, you want an active and procedures trunk of the stability of the isolated work areas. But you do not want to release the next version before freezing trunk blocking the development of each person. Solution is in your version control resources in the creation of a version of branches. The first script control of a running version of the process of the release of 1-4 steps:
$ Release_branch 2_7_1
Successful operation of the script, and tell you to create a version of branches in the code compiled and passed the test. If there are problems, you should be in this version of branches in the path changes, test these changes, changes to the version submitted branches. You can also run other scripts such changes to the merger trunk.
Once you have a version of branches, you repair all the problems, you actually generate a prepared release. For these, you are running another script to control the steps 4-8, to a version.
$ Release_generate 2_7_1
Run this script is the result of an independent distribution of documents - Customers can install and publish the same document. You have already done faster; before you leave only a step.
Dirty details of the deployment
Deploy applications to the server is another demonstration of the multi-step, manual process, even if you do so slowly, and basically be wrong. But because your team needs frequent deployment of software - and that accurate and reliable to deploy at any time are very important - you have automated the deployment steps. When you run the script when the deployment of all the dirty details of the deployment of your implementation.
$ Deploy
In such circumstances, the script circulated documents to the transmission of packets demo server module to the deployment of all their respective paths. But in the actual script in the implementation of the application server, and step be perfected.
You do not want to automatically deploy applications, but because of a stupid configuration problems can not start. In the use of clean running before your application is a configuration of the figures needs to be properly installed. So prior to the commencement of the application server, and run a script to rapid diagnostic tests to identify the deployment of any potential problems.
In particular, you have taken noteæžåa database configuration is an ordinary deployment errors. Debugging this problem let you swap a lot of hair, so you use JUnit last week wrote the following diagnostic tests:
4 list:
Public class DiagnosticTests extends junit.framework.TestCase (
Public void testDatabaseConnection () (
Database database = new Database ();
Try (
Database.connect ();
) Catch (RuntimeException e) (
Fail ( "Unable to connect to the database, '" +
Database.getURL () + " '." +
"Please check the 'database.url' property.");
)
)
)
TestDatabaseConnection tried to use a database of examples of projects to link with the database. That category from the configuration file, read the configuration values, like database.url such attributes. If diagnostic tests unable to connect to the database, it appears to be running when you have to be applied to the same fate. Therefore, if the connect test methods in the diagnosis dished out a call when abnormal fail () method is called to print a useful information to help you fix the problem.
Extremely grateful to the deployment of a script error. Tell you this application has been deployed, all the diagnostic tests passed, the application server has also been launched. You have demonstrated in operation!
Leak monitors
You click on the application of several web pages to do a quick sound detection. It looks great, but you want to know tonight for tomorrow's demonstration drive, it would still outstanding, so you can Shuihao the. The project is online, so you can know that the entire evening is not what happened in the demonstration.
Do not worry. You from your toolbox automation procedures can find every few minutes in search of a web site as "Error" or "Exception." That the wrong word. If there is such a word, or web site becomes unavailable, the monitors will be sent an SMS message to you in the phone. If this is the case, if the application crashes, you will have more time to fix it before the demonstration. Out of the door in your office before you put monitors linked to the demonstration site:
$ Monitor http://demoserver:8080/whizbang
Tee-ball in the venue, you see your son on a home plate in the plate. Meanwhile, in your office, you reliable operation of the surveillance procedures alone. Your phone on the side, but he did not always sound, you like to sleep like a child because of the demonstration will not be the end of the fault.
Forward and upward
Demonstration was so successful to the extent that customers receive copies of applications has been ranked the door. Submit documentation to your company's Web site or burning the CD-ROM will slow down some of your team, if there is no automated scripts to control those tasks, will be the same. If someone happens to report an error, you can easily from the re-generation version control demonstration. When the amendment was wrong, you can click a button to create a new release.
Whether you where automation can rely on when problems occur earlier to inform you demonstrated to help reduce the risk of failure. Automation also save you time and ensure consistent results, and through you to provide repeatable method to build and deploy your software. When you continue to prepare and distribute new presentation software, automation can be repeated to play a role.
The actual automation projects
Unfortunately, many of the items on this story is not true, you may also include the item. Many teams to do by hand miscellaneous items, but people do such repetitive tasks such as computer does not do so good. These teams use different methods of risk running a process, a time of concern that only one machine instead of other machines, or doing the wrong thing. Frankly, you know you have continued to build than to do things better, according multi-step list, copy files to the server, surveillance operation procedures. But you how to quickly and effectively to the work of this convergence Kuaikuai together?
From this article, it seems you are now automated or under a project including a lot of work. Thank God, today you do not need all your automation project to begin the process of the clear benefits of automation. You automation of chores each project is an investment, and the immediate return of value added over time. You can use free tools available such as Ant, Maven, CruiseControl, JUnit, and a simple script to a rapid start step by step. Pragmatic Project Automation of this book to tell you how to use your computer at the time the same way you do repetitive tasks of the project, not troubling you. This means that you will have more time and energy to do really exciting - challenging - things like write high-quality code.
↑ Back
J2EE outlined J2EE technology from China Forum
Abstract: J2EE outlined J2EE technology from China Forum
What is Java2 platform, enterprise edition?
Sun's J2EE is the United States has just launched a brand-new concept of the model, the traditional model of Internet applications compared with unparalleled advantages.
Many of today's enterprises need to expand their scope of business, reducing their operating costs, shorten their customers and the response time, and this requires the existence of a simple and fast services to enterprises, partners and employees.
Typical said that the provision of these services must be the same application software enterprise information system (EIS) integration, and to provide new users to provide more extensive services. These services should have the following characteristics:
A. High Availability: to meet the current global business environment
B. Security: protect the user's privacy and the security of enterprise data
C. Dependent and can be extended: the guarantee that the correct commercial transactions and speedy These services are usually from the distribution of application components, including front-end and back-end data sources and data among them one or several layers, these intermediate layer provides the business functions and data and combine the functions of EIS. These middle tier client from the complex separated from the business logic, using technology to mature INTERNET users in the management by minimizing the time spent.
J2EE formal reduces development of this middle layer and the cost of complexity, thus making services can be launched quickly, and be able to compete more easily in the face of pressure.
J2EE through a standard definition of the structure to realize its advantages, as follows:
A. J2EE Application Programming Model - for the development of a multi-level, thin-client users of the standard design process model
B. J2EE Platform - a standard platform for the integration of J2EE applications, a series of designated interface and methods
C. J2EE Compatibility Test Suite - a set of compatibility test components used to detect whether or not the products compatible with the J2EE Platform
D. J2EE Reference Implementation - the ability to model J2EE
2. J2EE application model
J2EE is designed for customers, employees, suppliers, partners to provide enterprise-class services, such applications are inherently complex, and they have to visit all types of data and distributed to a large number of clients.
In order to better control and management of these applications, and support a wide range of business functions to users in the middle of the introduction, a middle layer is described in the information technology sector enterprises tightly controlled environment.
J2EE applications rely on the EIS layer to store enterprise business data. These data and to manage its system is the core of enterprises.
Initially, the double-layer structure (client-server) application model promised to improve scalability and a broader function, but, unfortunately, directly to users EIS and the complexity of the services to each user's computer installation and maintenance business logic caused by the problems in the management of a major constraint.
These further restrictions in the double-layer structure in the three-tier structure does not exist.
Now requirement is the development of the commercial services functions, but also the development of databases and other resources to the code, which is very complicated, because each of the multi-storey structure has its own server application model, it has been set up with experienced development teams will be difficult. In addition, following the expansion of the scale services, in order to reduce costs and speed up the response speed, but also often its primary code revision.
J2EE Application Model definition of a model to enable the realization of multi-application services, and eliminate the above problems, and to provide a scalable and easy to access and easy to manage way.
J2EE application model to achieve services for the multi-storey structure is divided into two parts:
Developer achieve commercial logic and expression, as well as by the J2EE platform provides standard network service.
Developers can rely on this platform for the development of intermediate services in the face of the system-level hardware to provide solutions
J2EE application model for the middle layer applications provide a compiler, arbitrary operating characteristics (write once, run anywhere), a standard model of the minimum cost of training developers.
J2EE application model through the establishment of multi-application procedures to minimize the complexity, Wai simplify and accelerate application development marks an important step forward.
3. Java technology foundation
J2EE application model started in the Java programming language and the Java virtual machine, they provide the continuous improvement of portability, security and the enhancement of human capacity development is the basis of the model application.
Application models usually include JavaBean component model, the JavaBean is prepared for the general function of the code based on Java technology more easily, using JavaBean visual development tools can be customized and combined these components.
4. Security
When other applications needs in each model, there are specific procedures in the safety of platform, J2EE platform in the development environment so that when the security constraints has been defined.
J2EE platform defines a standard open access control rules, when procedures in the enterprise platform has been developed by the programmers at the definition and interpretation. J2EE also need to provide a standard mechanism for the application of the registration procedures do not have to be registered with logic and mixed mechanism, the work to implement the same in a lot of different environments and does not need to change the source code.
For example: J2EE application developers can specify several security levels (eg, user, superuser, administrator), so they write code to check the level of the current user permissions when users access the data. In the development stage, developers give multiple users on the safe level, so that applications can be easily in the implementation of the judgement of explicit restrictions before the operation.
5. The middle layer
J2EE application model One of the major advantages is in the middle of the multi-storey applications. J2EE platform in the middle of the business function is achieved by the enterprises JavaBean.
Beans services allow these enterprises to focus on the development of business logic, and that the transmission of treatment EJB Server stable, scalable services complex work.
JavaServerPages Servlets technology to customers and provide easy access of the Internet-based service in the middle of the function. Jsp user interface technology enables developers to more easily provide any browser users with dynamic pages service. Servlets for Java technology-based developers greater freedom in the Java language to provide complete dynamic services.
6. Customer -
J2EE platform supports several types of customers.
Many J2EE service was designed to browser users services that are dynamically generated through Html page and forms to achieve interaction with the client, and Jsp and Servlets through these commercial data through one way or another format, so that the client more easily to work with it. These clients can be run on the JavaApplet browser and Java technology-based procedures.
It should be noted that security is a key part of multi-storey structure, in the safety of the J2EE platform and administrators have always resolved. In most cases, services or clients, do not require developers and security logic.
7. Html page based on the customer
Java2 can be achieved in the user's browser to directly provide dynamic Html page service, JavaServerPage technology through Html page insert Java code dynamically generated page is a very easy matter. In some cases, certain services need some comprehensive code can be passed from Jsp Calling JavaBean method to achieve.
8. J2EE statement
J2EE application model of an important goal is to make the smallest of applications. Achieve this is a way to improve the J2EE platform in the ordinary tasks run on the burden of the ordinary tasks, including the application of a mandatory safety goals, the implementation of its transaction processing, links the components it needs.
J2EE provides a simple, open way to illustrate these acts. These notes were scattered on the part of the code and development description, description of the development is part of the application package, based on xml note that application developers do not have to modify any component can be changed on the role of application.
↑ Back
J2EE explore the state of the J2EE technology network
Abstract: J2EE explore the state of the J2EE technology network
A state application management
You may recall, in the article, Web applications agreement was divided into two categories: state (stateless) and the state (stateful), the agreement states that it is "Memory" from a transmission to the next a transmission of information. Because of the state of connectivity in enterprise applications is the most basic needs of one, and because Web applications rely on HTTP (the internal state without agreement), the smart developers have already found a lot of skills to the simulation in a state of HTTP connections . A status information can be stored in the HTML form fields, in addition to hyperlinks or stored in the client side of the cookie.
Between the client and the server can be in a state of interactive Web-layer or business management. Web layer in the state management, we use the combination of servlet HTTPSession API. In the business of managing state, we use a state session EJB components. In the next chapter, we will explore the development of these two options.
Web -
Servlet Architecture HTTPSession API allows application development management across the network client / server interaction (or spoken) state. HTTPSession HTTPSession API interface defines the core functionality. It J2EE application provides a method, it can be identified across multiple pages of individual client requests, as well as the data stored in the client and that the associated server. Through the interface, servlet containers creation and management between the client and server's session. HTTPSession object from the conversation that it can be cross-from the same client and the number of pages linking persistent request a specific time. Servlet use of the interface to view and deal with the conversation of information, such as time and on the creation of a visit conversation time. The interface also allows servlet session will be bound to the object, thereby connecting to a cross-over (from the same client) the persistence of the way information and specific client connections.
Servlet Architecture
Servlet architecture and not because of the use of HTTPSession API and change. As in the absence of the state network, servlet implementation of the business on behalf of the client request and act as controller, view, or both at the same time. Servlet can also effectively handle user interaction, such as the format and content of that request processing and basic security requests, and more. As in the absence of the state network, servlet best for the management of client interaction, it is usually to use assistant category (such as JavaBeans) to cope with the treatment or operation and mutual back-end components (interface).
Therefore, the servlet containers HTTPSession interface allows the creation and management of customer opportunities, and to make conversation with the servlet can visit the relevant information will be targeted to bind the previous session and a visit to bind target. Up to now, has been good. But how servlet container tracking through the state without the agreement (such as HTTP) communications client? To achieve this, each HTTPSession object to provide a unique identification to ensure that each customer with the opportunity and if the session relevant information can be unique identifier. HTTP take into account the inherent nature of a state in each request, the session logo must be transmitted to the client server, servlet containers will be to facilitate the client and correct associated conversation. Conversation logo can be used in three ways for a transfer: As HTML form parameters (usually hidden field); as additional query string parameters after, or as a cookie attributes. No matter how the conversation logo transmission servlet containers will intercept it, check it, and find it linked HTTPSession object.
Servlet performance Servlet architecture created by the lightweight threading model will not be servlet or JSP document creation, to read or modify HTTPSession object has been destroyed. The object is to save it as a simple object reference bond - on the value of the hash table or similar set. Similarly, the realization of HTTPSession memory space itself is lightweight, only need to store (perhaps serialization) Conversation object identification and the corresponding session. In short, and can support HTTP servlet client interaction with the state, and the use of program design or containers with a minimum of resources.
A state application management
You may recall, in the article, Web applications agreement was divided into two categories: state (stateless) and the state (stateful), the agreement states that it is "Memory" from a transmission to the next a transmission of information. Because of the state of connectivity in enterprise applications is the most basic needs of one, and because Web applications rely on HTTP (the internal state without agreement), the smart developers have already found a lot of skills to the simulation in a state of HTTP connections . A status information can be stored in the HTML form fields, in addition to hyperlinks or stored in the client side of the cookie.
Between the client and the server can be in a state of interactive Web-layer or business management. Web layer in the state management, we use the combination of servlet HTTPSession API. In the business of managing state, we use a state session EJB components. In the next chapter, we will explore the development of these two options.
Web -
Servlet Architecture HTTPSession API allows application development management across the network client / server interaction (or spoken) state. HTTPSession HTTPSession API interface defines the core functionality. It J2EE application provides a method, it can be identified across multiple pages of individual client requests, as well as the data stored in the client and that the associated server. Through the interface, servlet containers creation and management between the client and server's session. HTTPSession object from the conversation that it can be cross-from the same client and the number of pages linking persistent request a specific time. Servlet use of the interface to view and deal with the conversation of information, such as time and on the creation of a visit conversation time. The interface also allows servlet session will be bound to the object, thereby connecting to a cross-over (from the same client) the persistence of the way information and specific client connections.
Servlet Architecture
Servlet architecture and not because of the use of HTTPSession API and change. As in the absence of the state network, servlet implementation of the business on behalf of the client request and act as controller, view, or both at the same time. Servlet can also effectively handle user interaction, such as the format and content of that request processing and basic security requests, and more. As in the absence of the state network, servlet best for the management of client interaction, it is usually to use assistant category (such as JavaBeans) to cope with the treatment or operation and mutual back-end components (interface).
Therefore, the servlet containers HTTPSession interface allows the creation and management of customer opportunities, and to make conversation with the servlet can visit the relevant information will be targeted to bind the previous session and a visit to bind target. Up to now, has been good. But how servlet container tracking through the state without the agreement (such as HTTP) communications client? To achieve this, each HTTPSession object to provide a unique identification to ensure that each customer with the opportunity and if the session relevant information can be unique identifier. HTTP take into account the inherent nature of a state in each request, the session logo must be transmitted to the client server, servlet containers will be to facilitate the client and correct associated conversation. Conversation logo can be used in three ways for a transfer: As HTML form parameters (usually hidden field); as additional query string parameters after, or as a cookie attributes. No matter how the conversation logo transmission servlet containers will intercept it, check it, and find it linked HTTPSession object.
Servlet performance Servlet architecture created by the lightweight threading model will not be servlet or JSP document creation, to read or modify HTTPSession object has been destroyed. The object is to save it as a simple object reference bond - on the value of the hash table or similar set. Similarly, the realization of HTTPSession memory space itself is lightweight, only need to store (perhaps serialization) Conversation object identification and the corresponding session. In short, and can support HTTP servlet client interaction with the state, and the use of program design or containers with a minimum of resources.
Choosing the right technology and the non-state J2EE architecture different J2EE application procedures do not provide the typical configuration to act as guides or blueprint. State management, appropriate architecture depend on the following factors:
Client is based on the Web (HTTP)?
State the need to include dialogue in the GUI?
Which will be in a server load conditions?
A state in the server components need to be able to continue to be effective after the collapse?
Affairs of the component which needs context?
How important is a state data?
Although some of these issues seems to be obviously one of the preferred technology, but many state programme actually need to use both servlet also need to use EJB components. The decision is crucial in determining the Web layer or in the management of state business, or at the same time in the two state management layer. In the next section, we will examine some possible enterprise applications programmes, and the most appropriate solution.
Application of the standard procedures client application with another client systems or components interoperable client. We will examine three typical client application programmes, and discuss each client with the most suitable state solution:
If the client is based on Java, and in the same server and firewall, then you should first decide whether the state interactive model is essential. Management of state session bean is resource-intensive, so you should consider a more lightweight alternative to. The best solution is to use RMI directly with the application server in the non-state dialogue session bean. If state solution is necessary, please consider using a simple affairs of the state without conversation bean, or in the business of the servlet to create thin layers. Spend any of the solutions can provide some of the costs of state experience. Finally, if your client must request and across multiple business processes of the state of tight coupling, and can not accept add Web layer, then a state of the session bean is obvious choice.
If you are using non-Java client and the server or use a firewall is not the same after the client, then the state management issues slightly different. In this package, you should first set the goal of state management. If the goal is through a GUI provides the user experience smoother, so that you can manage state Web layer. If the goal is to the complex across multiple requests linked to the business process, then the state management should be carried out in the business layer. Stress once again that you should always explore other options, such as the use of a non-state affairs session bean.
Some applications in a server vendors such as IIOP accept the call of the open EJB containers, thereby allowing the CORBA client will EJB component of the cost of CORBA applications. This allows the use of non-Java client agreements and IIOP stateless session bean communication. In this setting, bypassing the Web client layer, and use IIOP agreement directly with the business layer (session bean) communications. Then, in the architecture of firewalls and the Java-based application analysis is the same. Please refer to the first option, in order to understand the business of state management.
E-business on demand environment, as we discussed last month, non-state session bean demand for e-commerce (e-business on demand) applications carefully designed. They are very lightweight, it's easy to convergence for the pool, to ensure that the excellent scalability. Instead, the session bean is not a state for such applications and carefully designed. E-business on demand applications usually need to state management, but the best by a dedicated mechanism or through J2EE Service for processing. Another possibility is called EJB components, as if it is like CORBA components. When one or more integrated applications is CORBA components, the option particularly useful.
"Rich" GUI client has three basic "rich" GUI (HTML is not, nor is it the command line) client types: Java applet, independent applications and Java Web Start. The following solutions are applicable to this "rich" GUI components in any type:
If your client and server firewall was separated, you should be allowed to clients via HTTP servlet and direct communications. The servlet layer can be used to type simple assistant business processing. If your applications are more complex needs, or for enterprise resource at the request of a higher frequency, you should use the session bean to handle business processes. Here to emphasize once again, you should be a model state of the need for interaction as part of the decision-making process be considered.
If your client and server in the same firewall, direct RMI call may be your best choice. In such circumstances, servlet will bring additional costs and unnecessary complexity of the architecture. In applet or Java Web Start cases, through the provision of a applet or Java Web Start application links the first HTML document, servlet can activate affairs. Then, the best the client with one or more bean session of the RMI to establish direct connections. The programme set up with a typical application client programme (with the server with a firewall is not after) the same settings.
If you are using this machine GUI clients, and the need to manage complex business or affairs series, then you should consider once again calling EJB component, as it is like CORBA components. If can not do that, you can always let the client via HTTP servlet and communications, management and the corresponding session.
Web applications in a standard, Web-based application cases, the client side of the firewall which is not important; use servlet is essential. Because you will use HTTP as a transport protocol, it will be working on the Web layer. The only practical decision whether or not to use EJB component behind the scenes? EJB containers will depend on the relevant service demand. First of all, you will choose a common component type (such as servlet and session bean). Next, you choose some matching the application's user interface display and processing needs of the business request more specific types (such as JSP pages and state session bean). On the concerns of state management, Web applications in the client and other similar types of issues. Some standards (and answers) will help you for your Web application procedures for determining the appropriate state management solution:
Need to have direct experience with the state of the user interface with? If so, must use servlet HTTPSession API management and the state.
Your business processes from the client needs across a number of calls? If so, you have three options:
Use of state session bean to provide state business processes.
The use of non-state session bean, and that the persistent data in the cache server. Then the application of the cache can be stored in the client's HTTPSession object.
By calling the bean JavaBean method appointed as business (see reference), making bean batch from all client data, and only in the client business process to be submitted to the state when no contact session EJB components. Again used the HTTPSession API to persistent JavaBean examples.
You have the state of business process needs fault protection? If so, you have three options:
Use of the application server, the server for the state of the state resumed session bean provides automatic support.
SessionSycnhronization interface allows stateless session bean or state failure to respond to the Panel. This will allow you to roll back services, the implementation of persistent data or you may need to remove any other function. Usually, the server failure will not impede the transfer containers statement from the callback interface methods.
Many Web servers to provide fault protection HTTPSession achieve. If your server can do this, then you can use JavaBean as a business appointment.
Multi-client type
Finally the situation requires a combination of types of clients, such as Web-based browser and standard "rich" GUI desktop. In such circumstances, a state with no state Options Options no difference. Please refer to the first of this series of articles for more information.
Concluding remarks in this part (J2EE Pathfinder series of the second part), we explore the use of Java servlet session bean and the state to implement client request and provide the state of the relative merits of experience. This paper discusses the programme did not include all cases, but they represent a state of the communications environment in the servlet session EJB components and some of the most common usage.
In the next part, we will begin on persistent data management of the two parts, first of all entities will be relatively bean and JDBC. Wish us to "explore" happy!
↑ Back
. NET and J2EE the mutual learning?
Abstract:. NET and J2EE the mutual learning?
[Introduction] I wrote this Post from both done. NET development done J2EE development experience. In this process of change, I developed on a single platform limitations brought about by a lot of clear thinking is the idea of fragmentation. After watching the Zhenhe brother pages of the variable transmission method and use of the discussion, I could better understand that in different platform development, and ways of thinking is so different from the original idea of those scattered consistently in their minds emerged, I have the impulse to write this Post. In fact, I have always advocated a view: Technology is the same between the savvy Chuleibangtong, programmers at Lenovo we should have the advantage. We focus on. NET technology, the gap may work in time to see the rest. NET outside world.
Mentioned. NET and J2EE, generally thought between them fight each other, mutually exclusive relationship, after all, both in the hard work to the favor Luhuo programmers, and occupy more market share. I do not intend to advocate. NET is the how the powerful, J2EE is how the maturity, nor do they intend to explore NHibernate, etc. Project Spring.NET the origin, from a programmer just want to look at the angle of the two competing in the end the process of learning from each other what at the same time look into the two areas at the same time understand the need for knowledge. Well, let us get down to business again.
Remember the beginning of 2003, I went to DELL corporate internships, the task is to establish a Web Application for a number of departments are closely linked to use to improve inter-departmental collaboration degree. In choosing what Web Application of this technology to do when I gave up more familiar with the ASP, then choose the ASP.NET. Project is doing this, I told ASP.NET and the. NET up their relationship.
At that time, first contact with ASP.NET, the first impression is that it much better than ASP and ASP can not write like that in a nested HTML piles of Scriptlet, dynamic content presentation are included in one method, If Page.OnInit () and Page.OnLoad (), etc., these methods let me see Client-JS method of the shadow. ASP.NET page in the development process, I need to do is to introduce different pages in the Web Control or HTML Control, Controls and HTML tags similar to how, in addition to its ASP, and then look at the prefix up as Magic general runat = "server." This similarity to the JS familiar with HTML and I quickly mastered the basic ASP.NET applications, and I have a very high efficiency of the company to complete the tasks assigned to me, though I like Request, Response, this Session and Application the object is not quite understand. ASP.NET brought about by the progress of the revolutionary No wonder a friend of mine that ASP.NET yes. NET family of the most successful products.
I only take with the ASP to ASP.NET compared revealed its natural advantages, especially in the control design edge. In fact until later entered the field of the development of J2EE, I still ASP.NET development mode appreciation for the increase. Microsoft in technological innovation has been weakened uphold the principles of the development of the area, developers can develop in different areas can be in easy-to-use, highly. ASP.NET brought about the emergence of a WebForm, and the development of desktop procedures are WinForm, the same place the two can be seen everywhere, and this original desktop developers can smooth the transition to the development of the Web Application; ASP. NET controls for use in the design and the support it perfect, as well as web design personnel to enter the field of the development of ASP.NET has removed many obstacles.
In contrast J2EE areas, the development of Swing do, if we should learn from the Web development, the original almost no knowledge of the battlefield. Popularity is in the wealth of the 1950s, a certain level common ground while reserving differences so that developers can one-hundred-and no doubt is a very sensible approach. J2EE areas are beginning to realize this point, the concept of Swing will be applied to the development of the Web Wicket Framwork release indeed is a great progress ah. J2EE Web development in the reduction of the difficulty of attracting entry-level developers need to. NET has some good advice.
, And personal experience added. By the end of 2003, I entered a software company engaged in the development of J2EE. At that time, the company's technology department is responsible for the people in the interview I mentioned my lack of experience in the development of J2EE, full of confidence, I told him that I have made. NET projects, and. NET and J2EE are focused on enterprise-level applications on, it will certainly get started soon, there will not be any problems. However, work later that the difference between the platform of a big, and from. Transition to J2EE NET is not an easy thing.
Not the familiar Web Control, in its place is a simple Tag Library; no easy-to-use Event-Driven approach, showing immediate doGet is, doPost, doHead and service this seemingly ugly faces. Transformation process is painful, but brings evolutionary change. Development of the way so that I can change from a more in-depth look at the level of Web development, and I began to understand Web Application. Web development to a large extent the complexity of the origin is a non-Http state of connectivity protocols, Web Server Whether you are a Michael, or Jordon, as long as you use a browser on the same URL, it will receive the same resources. Here, you must clearly URL in the end what is the acronym. Perhaps you will stand up and refute the conclusions I have just mentioned, but only in this era of static HTML pages is absolutely correct.
With the development of the times, resources are no longer limited to static HTML pages, and the resulting so-called dynamic web page. The dynamic here is not that a Flash animation website, but the website will be in accordance with the contents of the Request different and changing. Although the Web personalization of the content, but we have still not sent from the Client Request, Response Server to return to this model. Http is due to a non-state connectivity protocols, in order to identify users access to the status of the same resources in the J2EE world, we must from the Request, Response and the object of this Session start, the control of these objects Life Cycle. Therefore, we have to carry out even the most simple Web applications, must be on the Request, Response and the object of this Session are fully understood. Pay attention to these basic object, let us for the Flow application to have a more accurate grasp to be able to better carry out module division to facilitate staff development collaboration. However, in the. NET world, and Session Request on the subject of this concern far less attention to Page, from the vibration River brother Post that typifies the situation.
ASP.NET development reduces development difficult, but to a certain extent hindered the development of the Web Application staff's overall grasp, as the Feedback spring fish brother mentioned, the struggle over the relationship between pages, "not conducive to overall system architecture a good design. " J2EE application allows Web Application programmers in the overall framework, there is a good reflection. NET is a good effort ah! Recommendations. NET programmers can try to use the J2EE technology to develop a simple Web Application, I believe that such a process will let you on the Web development of further understanding.
J2EE entered the field, in addition to development mode changed, with the buzz words are changed. The use of two high frequency vocabulary full of work for the day, one MVC, and the other is the Framework. I sigh in the use of J2EE Pattern in the breadth of feelings in the application of the model to achieve the MVC Framework huge to be able to develop a collaborative team Project. At that time I began to believe that the extensive application of Pattern to the changes brought about software development is enormous and far-reaching, began reading "Core J2EE Patterns" and benefit from it.
In the. NET world, the importance of the Pattern is far less J2EE, although such a change in the situation. Speaking of the MVC, to the weighty significance of such a statement do the words. JSP development has experienced two phases: JSP Model1 and JSP Model2. Model1 is in the JSP and the combination of JavaBean, to a certain extent, achieved MVC, but the Model Control and the coupling between still prevails and is truly realized Model2 MVC: JSP as a Presentation Layer, is responsible for data display; as Servlet a Request Dispatcher role Request will be distributed to different treatment Business modules, it is a commander, carrying the banner Controller and the VO is a data carrier, is triangular in the MVC Model. MVC is the concept of access to the necessary areas of J2EE development, you have done a simple application, from your first look at the article on J2EE development, and abundant open-source MVC Framework has also become our study MVC Pattern good teaching. With the initial understanding of J2EE, we can select some excellent MVC Framework to study, such as WebWork and Spring. This study overall system architecture design is very helpful.
Perhaps extremes meet is really an unchanging truth, in the field of J2EE Framework for the development is the pursuit of crazy, everyone in here to see: Wicket - Introduction. You will find that can be used to develop the Web Application Framework has reached 55 and is still growing. In fact J2EE Development Control is not the weakness of this level, but in the View. Many are gifted energy consumption in the manufacturing wheels repeat, did not try to improve one or more Framework, which can only make people feel bad ah! At this point, is not in the J2EE to. NET study well and what?
. NET world, the greatest concern should be to control the development, and a well-designed, powerful controls for improving the development efficiency is excellent boosters. Many. NET developers will be spent on the design of controls. NET like a cornucopia, the convergence wisdom of developers. J2EE in the world, in order to reduce wastage of resources, the emergence of the Wicket Framework. It emphasizes design and component reuse components so that developers concentrate on the development of components, so as to enhance the function of Framework has been ease of use. Hopefully, Wicket Framework for J2EE can change the world a little!
Then Then, really a bit of the Mustang unbridled feeling. Do not know that for a long time, we understand that my real intention? Open the case in this era of technology. NET programmers should be to understand J2EE, and vice versa. I would like to learn from each other, and seek common progress of this re-general, however it can be summed up this Luoluosuosuo thousands of characters it.
↑ Back
Deadlock problems in J2EE
Abstract: J2EE in deadlock
Most important applications are highly complicated and involves multiple abstraction layer. Concurrency and fight for the use of the resources, and lead to deadlock the issue is more one of the factors. Multiple abstraction layer to isolate and repair the environment Deadlock work more difficult.
Normally, when at the same time the implementation of two or more threads, each thread if all resources and has a request of the other resources, then there will be deadlock situation. If one thread can access to resources, all the threads are unable to continue, and we said that particular thread was obstructive, if each thread in the same group as all the other threads of some resources were blocked, We call this thread Group was deadlock.
In this paper, we will discuss the important occurred in a typical J2EE applications in the two categories Deadlock: "simple" Deadlock and cross-resources database deadlock. Although our discussion based on J2EE, but also applicable to other technology platform.
Database Deadlock
In the database, if a connecting link to the other occupants of the database lock required, it can be blocked another link. If two or more connections mutual obstruction, they can continue to carry out, a condition called Deadlock.
Database Deadlock difficult to deal with the problem, which is involved because the lock-in is not usually significant. Usually, the data firms implicit updated, it needs to lock the data, perform the update, and then to roll back or closed matters release lock. The database platform, configuration and the level of segregation for different tips, access locks may be fine-grained or coarse-grained, and it will be blocked (or non-obstruction) Other data on the same trip, table or database enquiries.
Access dependent on the internal lock generated query plan. When the size of data and step-by-step changes with the passage of time, the program may also be changed. In such an environment of access to a group of enquiries can try to lock in another environment group access to a completely different locks. When necessary, the database can be arbitrarily increase its locks. For example, the database may choose to lock the entire page, rather than locking in the same data page 10 rows, it would not lock on the obstruction of the read-write access to data.
Based on the database schema, read and write operations will require traversing or update multiple indexing, verification constraints, such as the implementation of triggers. Each request will introduce more locks. In addition, other applications may also access the same database schema is the certain object, and access is different from your application procedures have locks.
All of these factors combined database deadlock was almost impossible to eliminate. Fortunately, the database is usually recoverable Deadlock: Deadlock found when the database, it will be mandatory destruction of a connection (usually at least the use of the connection), and roll back its affairs. This will be the release of all the affairs and has been linked to the end of the lock, at least allow other connections in the access they are an obstruction locks.
This is a typical database because of the deadlock processing, database Deadlock Therefore, when problems arise, the database is often the only retry affairs. When the database connection be destroyed, it will be dished out applications capture anomalies, and identifies the database deadlock situation. If allowed to spread to abnormal Deadlock initialization code of the Panel, then the code can only start of a new panel to do both all previous work. It is necessary to correctly use this strategy, the success of the Panel submitted before the code does not have other operations. Note: To limit the number of re-examination, otherwise easily lead to deadlock the code block will be permanent cycle continue.
If there are problems on the re-test, this method a bit stupid. However, as free access to the database can be locked, so almost impossible to guarantee that two or more threads there are no database deadlock. This method can be guaranteed at least in certain rare cases Deadlock database, the application can operate normally. This is to retry require users to operate better.
In J2EE applications, developers can create a call to use EJB Bean care services (BMT) - developers start to roll back or specific issues or containers care services (CMT) - Calling the former method of launching services, and in the way or after the completion of the rollback affairs. If EJB providers retry-on-deadlock parameter, which can be done automatically containers care services this, then of course the best of all. If there is no such automatic functions, developers will ultimately only a re-examination of the deadlock and the use of mandatory calling EJB Bean care services. In this operation details, please see www.onjava.com/pub/a/onjava/2005/07/20/transactions.html.
Deadlock encountered problems and locked the other thread-locking frequency depends largely on the specific database platform, hardware, database schema and queries. Based on the lock in the use of a database concurrency control (such as MSSQL), the non-submission of the write operation will stop the read operation, an operation to prevent Reading write to the database more easily in deadlock. In the multi-version concurrency control (MVCC) databases (such as Oracle), the non-submission of the write operation does not prevent Reading - read operation only looked at the old version of the row. Although this will be the introduction of other problems, but will not cause the same amount of opportunities for deadlock. We need to familiarize themselves with these database lock mode, and are using their attention to the type.
In the find, repair and avoid deadlock database, there are some very good reference, but they can not completely eliminate the possibility of deadlock.
Deadlock-resources
When the deadlock situation is not entirely confined to the database, it will be harder to find it. Database of possession and request a lock recognition ability, the entire database can be detected in Deadlock In addition, database services in determining which things atom, which is not providing a good line, so you can easily rollback affairs, Deadlock to recover from. Other environment (such as Java Virtual Machine) or deadlock in the cross-environment Deadlock more dangerous because the environment can not (or not) of these Deadlock Detection and try to resume. To make matters worse, these will have Deadlock combined effect - if two threads occupy certain resources set Deadlock occurs when, any other attempt to visit one of the threads of resources will also be blocked, the thread has already acquired all resources have been obstructive. Deadlock these often difficult to find, but there are certain common mode of understanding will help identify and repair deadlock.
When the environment in a suspicious deadlock situation, you need to consider some issues. The answers to these questions will indicate you are dealing with the situation in the following circumstances which (if any), and provides repair detailed information on the following issues. Have to consider a number of important issues including:
- What thread involved, they call stack? This requires some detailed analysis of actual Deadlock thread from those who were only Deadlock thread blocked thread separated.
- Deadlock is always the case in this particular code path in (each of the implementation of these specific operation), or rely on two or more at the same time the implementation of the code path?
- The database connection? Each database connection possession of lock? Each attempts to gain access to the database linking lock? Response of each database connection threads Java Virtual Machine?
The next section on the occurrence of three common-resource deadlock situation.
Deadlock situation of the resources-1: client pool of resources resulting from the increase in depletion
We must introduce the first case of a deadlock due to load and is purely a result of a resource pool that is too small, and each thread needs more than the resources of the pool of available resources. For example, consider a database connection using the EJB call, the implementation of a nested EJB call (using the same connection pool different database connections). For example, if the nested EJB statement calling for RequiresNew, there will be deadlock situation.
Under normal load, or sufficient connection pool size of the circumstances, EJB access to a call from the database connection pool, and then call the nested EJB. Nested EJB call from the pool access another database connectivity to internal affairs, and then returned to the pool to connect. EJB will be submitted to the external call their own affairs, and to return to its connecting pool.
However, assuming that the connection pool up to 10 connections at the same time there are 10 pairs of concurrent external EJB call. Each of these threads need a database connection used to empty the pool. Now, each thread to implement nested EJB call (need to acquire a second database connection). All the threads are unable to continue, but do not give up their first database connection. In this way, 10-thread would be deadlock.
If the study of such deadlock situation will be found in the dump thread access to resources for a large number of threads, as well as an equal number of leisure activities with no obstruction database connection. When the application deadlock, if the operation can be detected in the connection pool, should be able to confirm a connection pool has virtually empty.
Deadlock repair of such methods include: increase the size of a connection pool or remodeling code, in order to use a single thread at the same time do not need a lot of database connection. If the needs of the largest single-threaded database connection for a few M, and the greatest possible number of concurrent calls for N, would avoid this problem, in the pool the required minimum number of connections (N * (M01)) +1. EJB or internal calls can be set to use different connection pool, even if the external call connection pool is empty, internal calls can also use their own connection pool to continue.
Deadlock situation of the resources-2: single-threaded, multi-conflict Database Connection
Implementation of the same thread nested EJB call will emerge when the second cross-resource deadlock situation, in such a case even in non-high-load system will usually occur. With the above example, the use of two different EJB call to connect to connect with a database. Only after the completion of nested calls to be able to call, so the call to the database connection was actually nested call obstruction of database connection, although the database did not notice this relationship. If the first (external) connection has access to the second (internal) needed to connect the database lock, the second connection will be permanently blocked the first link, and wait for a connection was submitted or rollback, which appeared dead Lock cases. Because the database does not note that the relationship between the two connections, so the database will not detect this situation for the deadlock.
As a concrete example, consider a data loading EJB call. Calling this EJB access a large object, and will be at different stages of their stored in the database. When the performance data loading, it will be updated a separate table for the record hangs data loading operation state. We hope that the status is updated immediately visible, but does not want the unfinished state that loading data, we should call "RequiresNew" EJB to complete. Overall, this imperfect data loading methods such as a list in the code shown.
List 1
<table Cellspacing="1" cellpadding="1" width="80%" summary="" border="1"> <tr> <td bgcolor="#cccccc"> public void bulkLoadData (DataBatch batch) (
Int batchId = batch.getId ();
/ / Since this executeUpdate call doesn Xian happen in a separate
/ / Transaction, it wouldn't be visible anyway, but the effect is
/ / Far worse: a cross-resource deadlock.
ExecuteUpdate ( "update batch_status set status = 'Started'" +
"Where batch_id =" + batchId);
ValidateData (batch);
UpdateBatchStatus (batchId, "Validated"); / / RequiresNew EJB call
LoadDataStage1 (batch);
UpdateBatchStatus (batchId, "complete Stage 1"); / / RequiresNew EJB call
LoadDataStage2 (batch);
UpdateBatchStatus (batchId, "complete Stage 2"); / / RequiresNew EJB call
FinalizeDataLoad (batch);
UpdateBatchStatus (batchId, "Complete"); / / RequiresNew EJB call
)
</ Td> </ tr> </ table>
In the above example, the use of updateBatchStatus ways to implement "RequiresNew" EJB call batch_status can actually update the database table, even if did not see the effect of current affairs, the state can immediately see the changes. ExecuteUpdate not call on the EJB call, so it bulkLoadData and other parts of the implementation of the same matters.
As mentioned above, even if it does not exist with this code will also lead to deadlock. When bulkLoadData call executeUpdate way, it will update the existing database, which involves access to the write lock. UpdateBatchStatus nested EJB on the call in a separate database will be connected to the implementation, and try to implement a very similar enquiries, but it will obstruction, because we can not get the necessary write lock. From the database perspective, as long as the first link or rollback affairs, and the second connection will be able to continue. However, the Java virtual machine does not allow for the completion of all the calls completed before updateBatchStatus bulkLoadD call, this deadlock situation has emerged.
This example shows that an update to block another update, it will result in any database deadlock. If the initial update query is a simple choice enquiries, then the only example in the use of lock-based concurrency control of the database led to the deadlock in this database, a connection can be read lock to prevent access to connect to write another lock. No matter under what circumstances, such deadlock that is not dependent on synchronization, not dependent on load, but also will show thread dump a database for Java threads response, but the two threads effective and relevant database connection together. In these database connection, one will be in a free state, but to block other connections.
There are many cases of this specific mutation, and can involve a number of threads connecting two or more databases. For example, external database connectivity EJB call may have access to the database lock, the lock blocked another unrelated to the database connection, but this has nothing to do database connection has been blocking access to the nested EJB call the operation of the database lock. This exception is dependent on synchronization, and will display more than wait for the response of Java threads database. With at least one Java thread will be two activities associated with the database connection.
Deadlock resources across the three circumstances: Java virtual machine locks and lock-in database conflict
Deadlock third case occurred in the database lock with the Java Virtual Machine when lock coexist. Under such circumstances, one has a thread attempts to gain access to the database lock and lock Java Virtual Machine (synchronous access to the lock). At the same time, another thread occupy Java virtual machine and try to lock access to the database lock. Once again, found a database linking obstructive another link, but can not stop connecting to continue, and we do not detect deadlock. Java Virtual Machine found synchronization locks, there is a thread, and there is another attempt to enter the threads, even if the Java virtual function Deadlock Detection and to deal with them, it is not detected in this situation.
To illustrate this deadlock situation, we, as a simple (imperfect) read-through cache as an example. The cache is a database table backup HashMap. If a cache hit, it returns a value from the HashMap. But in the cache missing circumstances, it would read values from the database will be added to the HashMap, and then return to the values, as shown in the list 2.
List 2
<table Cellspacing="1" cellpadding="1" width="80%" summary="" border="1"> <tr> <td bgcolor="#cccccc"> public class SimpleCache (
Private Map cache = new HashMap ();
Public synchronized Object get (String key) (
If (cache.containsKey (key)) (
Return cache.get (key);
Else ()
Object value = queryForValue (key);
Cache.put (key, value);
Return value;
)
)
Private Object queryForValue (String key) (
Return executeQuery ( "select value from cache_table" +
"Where key = '" + key + "'");
)
Public synchronized void clearCache () (
Cache.clear ();
)
/ / Other methods omitted for brevity
)
</ Td> </ tr> </ table>
This is a simple traversal cache. NOTE: get () method is synchronized, it is because we visited the non-thread-safe containers, and asked containsKey / cache put in the portfolio when the deletion of the atom.
The cache quite straightforward: it agreed to support the changes if the cache data in the table should call clearCache (), this could have been avoided dealing with outdated cache data. The cache will be a corresponding loss to re-enter the cache.
We are now considering possible changes to the data and to remove cache code:
<table Cellspacing="1" cellpadding="1" width="80%" summary="" border="1"> <tr> <td bgcolor="#cccccc"> public void updateData (String key, String value) (
ExecuteUpdate ( "update cache_table set value = '" + + value
" 'Where key ='" + key + "'");
SimpleCache.getInstance (). ClearCache ();
)
</ Td> </ tr> </ table>
The above code in a simple example to normal operation. However, the use of lock-based concurrency control of the database, the updateData queryForValue enquiries will prevent a choice for the implementation, because access to an update written statements will be locked, thereby preventing access to your enquiry on the same data line read lock. If there is no problem simultaneously, a thread can try to read the cache setting, and in another thread in the database updated by the value of cache deletion. If the first implementation of the database update statement, it will continue to implement the obstruction select statement. However, the implementation of the select statement from the thread synchronization get, so it SimpleCache on access to the locks. UpdateData to return to the thread, it must call clearCache (), but can not access Lock (clearCache () simultaneously).
When dealing with such a case example, there will be a wait for the response of database and Java threads access a Java Virtual Machine for locking threads. Each thread connecting with a database linked to one another link connecting obstruction. Repair methods occupy Java virtual machine is locked to avoid the implementation of database operations can be rewritten leCache the get () method, as follows:
Public Object get (String key) (synchronized (this) (if (cache.containsKey (key)) (return cache.get (key);)) Object value = queryForValue (key); synchronized (this) (cache.put ( key, value);) return value;)
Now that we know will happen this deadlock situation, we can use Thread.holdsLock () method to add queryForValue checks to try to avoid deadlock:
Private Object queryForValue (String key) (assert (! Thread.holdsLock (this)); return executeQuery (…);}
In the case of the Thread.holdsLock () was very useful, but only if we know what needs attention, it will lock a role to play. If there is a similar approach determine the current thread which occupy Java Virtual Machine locked, would be useful. Any implementation of the RPC calls of any kind, such as database access code fragments can be dished out unusual or record warning instructions occupy Java Virtual Machine lock when the implementation of these operations be dangerous.
Note: While we were on the mend in the deadlock, but it still shortcomings in the affairs of the updateData before empty the cache. If the call clearCache, appeared before the Panel to updateData missing cache, the cache will be loaded old data because the new data has not yet visible. Here is the restoration only to the changes in the empty cache. Note that this occurred in the MVCC in the database. Lock in on the database, the update will be put up blocking cache read operation, in the affairs of the update after the cache can read the correct value.
Experience rules
Following these guidelines can help you avoid deadlock, or at least in the event of deadlock can diagnose and repair them.
- Maintain Affairs brief.
- Understanding of the database lock (and Services separation layer).
- Assume that any database access are likely to fall into the database deadlock situation, but to correct try again.
- Services prior to the completion of the Panel will not update any non-state (state memory, cache, etc.).
- Ensure that at the peak with a large enough pool of resources.
- Not the same time try to get multiple sources. If necessary, according to the same access to a resource for each order.
- Learn how to get from the application server thread dump, as well as complete access to the database connection from the database list (including mutual obstruction connection), and know that each of which Java database connection threads associated. Java threads understanding between mapping and database connectivity of the most simple way to connect pool access patterns add logging function.
- When a nested EJB call, the call know what to use and call the same database connection. Even if the nested call in the same overall operation of the Panel, it will use a different database connection, and this will lead to cross-resource deadlock.
- Avoid the implementation of database calls and EJB call, or in the possession Java Virtual Machine lock, the other with the implementation of Java Virtual Machine unrelated to the operation. If there is a need carefully to the specific Java Virtual Machine lock on the use assert (! Thread.holdsLock (…)), to avoid future code changes do not inadvertently violate this rule.
Concluding remarks
J2EE applications in the cross-Deadlock resources is a big problem - it can lead to termination of the entire application process slowly, it is still difficult to be separated and repair, particularly when developers not familiar with how the time of deadlock environment. We discussed the situation will help you understand some common deadlock situation, and provide you with the idea of View deadlock. More importantly, we provide a general rule of thumb in a number of compliance with the code of practice, so as to avoid all similar deadlock.
↑ Back