Spring's historical Theory (data desensitization)

Source: Internet
Author: User
Tags new set

the structure of many companies is now migrating from Struts2 to SPRINGMVC. Have you ever wondered why you wouldn't use servlet+jsp to build a Java Web project, but instead adopt SPRINGMVC?

In that case, we start with the source. The source of Struts2 is also a servlet. The role of the servlet is to receive requests from the browser to the server and to return the service-side response (response) to the user's browser, which communicates via the HTTP protocol between the browser and the server. The process is that the browser according to the user's choice to assemble the relevant information according to the HTTP protocol Message Specification assembly request HTTP message, the message transmits through the network to the designated server, the server receives this message information through the specific Web container, for example: Tomcat,jetty,jboss such a web container , the Web container will parse the HTTP message, and if it is a user request, the final parsed message will be stored with a request object, and the server will use this request to finish the corresponding processing, and the service-side program encapsulates the result information into the response object. Then the response object is given to the Web container, and the Web container transforms the response object into a message of the HTTP protocol and passes the message back to the browser, and the browser finally parses the response message and displays the final result to the user.

The

Web container creates the Servlet interface, where the developer implements the business logic itself, and the programmer develops the servlet as a fill-in question, The context or context hint of the fill-in question is the request and response object, but the servlet interface in the Java EE specification is simple, with three methods Init,service and destory, but this interface is too general, So the specification also provides a HttpServlet class, this class according to the HTTP request type provides doget,dopost and so on, the most characteristic of the servlet interface is defined according to the characteristics of the HTTP protocol, Therefore, if the user is not particularly familiar with the HTTP protocol features in the development of the servlet, it will encounter more or less confusing problems, especially when encountering some complex special requests: For example, File upload, return special file format to the browser, it is not very convenient to use servlet development , servlet development also has a problem may be often overlooked, is the type of data requested to convert, HTTP protocol transmission is text form, to the Web container parsing is also the text type, if you encounter currency, numbers, dates such types require us to convert according to the actual situation, If the page is sending a lot of information, we have to do a lot of type conversions, which is not technically useful, is a physical activity and can easily lead to bugs. At the same time, Java Enterprise Development is around JavaBean, type conversion of good data to be encapsulated in the corresponding JavaBean, this kind of things for the project development is definitely not a good thing, so the old struts1 for this problem found a solution, is to define a DTO object (data Transfer object), specifically responsible for doing such things, but to struts2, the entire alternative servlet action itself is a javabean.

One of the technical features of Java's Enterprise development is the use of JavaBean, one of the features of STRUTS2 is that it is a typical javabean to replace the servlet's operating class. First, the STRUTS2 framework encapsulates the data of the page transfer and encapsulates the request information into this JavaBean attribute, so that when we develop the Web program, we eliminate the problem of type conversion and encapsulation. As I said before, the traditional servlet is defined according to the HTTP protocol, which processes the user's request in the way you request it (post or get), but for a program developer, a request, specific to a URL, In fact, for the service side is the service side of the external provision of a function, or a service side of the external action, if we use the Servlet development program we have to translate the HTTP action into a specific business action, which makes the program development become cumbersome, enhance the development of the difficulty, So struts2 alternative servlet JavaBean block the servlet HTTP request mode and the specific Business action transformation problem, each method in JavaBean can and each URL request one by one correspondence, this inevitably alleviate the difficulty of development.

Servlet another role is to construct the response object, so that the page to get the correct response, in fact, the modern browser is a multimedia tool, text, pictures, video, etc. can be displayed in the browser, the different resources will lead to HTTP response message differences, If we use the servlet development will be based on the different resources in the Java program in the hard-coded form of processing, such a program is difficult to reuse, and if the programmer to understand the processing of a resource is not in place, will lead to problems arise, Struts2 this logic out of the Java program in the form of a configuration file, and using configuration to manage it uniformly, this approach is similar to spring's AOP approach, so that results are handled more uniformly and more manageable. It also improves the robustness of the program and reduces the difficulty of development.

servlet in the MVC development model is the C layer is the control layer, the control layer like the Russian double-headed eagle (a head to the east to look at a head to the west), a head to the M-layer model layer, a head to the V-Layer view layer, the model layer is written in Java, The control layer is also a service-side language development, so the M layer and the C layer of communication does not have a natural barrier, but and the V Layer View layer is not the same, this is a cross-language communication, for the browser, it only know Html,javascript and CSS, browser is not understand the Java language of things, But in order for the server to be understood by the browser, we have to put the response information on the server to the page, so we need a technology to translate the Java information into the HTML page, which is a JSP technology provided in the Java EE specification, JSP is actually a service-side technology rather than the client technology , but it seems more like HTML technology, the earliest JSP development is directly to the Java code written to the page, this disadvantage everyone knows, after the Java EE specification provides a custom label technology, using a similar HTML tag way to parse Java code, The STRUTS2 framework provides a complete set of custom labeling techniques, which doesn't seem to sound like much, but it works very well, because custom labels are called customizations that everyone can define themselves, and if no specification is necessarily confusing, and a complete set of custom tags is a system engineering, A complete set of custom labels is equivalent to our own definition of a new set of development language, the people who do the program to hear this must understand that the development of a complete set of custom tags and the workload and development is difficult to imagine, and the custom label is closely linked to the control layer, the difficulty of adding a dimension, So the custom label provided by STRUTS2 will be a qualitative leap for business development.

  There are two important techniques in the servlet: listeners and filters, which are rarely used by listeners in web development, are very special cases, and most web development can ignore its use. The listener we use most probably is the listener created and destroyed for ServletContext, ServletContext is the global object of the entire Web application, and it binds to the life cycle of the Web application, This listener is therefore used to initialize and destroy the global information of the Web application, such as the initialization of the spring container. More interesting is the filter, there is an interceptor in the struts2, their role is to intercept the request, because the interceptor is the unique function of struts2, in the struts2 using the interceptor is naturally more comfortable than the use of filters, in fact, the interceptor technology is more advanced than the filter, Because interceptors use the reflection technology, the interceptor intercepts more faces, the ability to control requests is stronger, and the tasks it can accomplish are more colorful.

When I first approached Struts2, I was told that one of the goals of the struts design was to block the operation of the request and response objects in the control layer, because the sons of the two HTTP protocols would cause confusion in web development, But I often unconsciously use these two objects in actual development. And I do front-end development very like to use Ajax, when using AJAX technology I hate Struts2 's custom tags, I prefer to use JavaScript technology in the page to deal with a variety of information, the final struts2 in my eyes is a servlet variant, So there was a time when I often wondered if I could abandon struts2 and use servlets directly, because struts2 used too many reflection mechanisms, especially with annotations (annotations are implemented with reflection), and the performance of reflection in Java is very low, Using the servlet directly will definitely improve the efficiency of your Web application. It was hard to do, because I couldn't use spring technology flexibly in the servlet.

  ^_^  ^_^ ^_^ ^_^ ^_^  ^_^ ^_^ ^_^ ^_^  ^_^ ^_^ ^_^ ^_^  ^_^ ^_^ ^_^ ^_^  ^_^ ^_^ ^_^ ^_^  ^_^ ^_^ ^_^ ^_ ^  ^_^ ^_^ ^_^ ^_^  

Finish the transition from SERVLET+JSP technology to STRUTS2 technology. Next talk about spring.

Spring technology can be said to be the most important technology in Java Enterprise Development, but really understand the role and meaning of spring is really a troublesome thing, many people to spring understanding is actually stuck in the use phase (for example: declarative transactions are very useful and so on), Today's spring technology ecosystem is spectacular, spring is all-encompassing, its content is no less than its original Java language, and spring is such a large box based on the IOC and AOP technology, Only by deep understanding of these two technologies can we understand why spring is a box that can fit so many things.

  First of all, the first explanation for IOC,IOC technology is called inversion of control, and it's also an explanation that relies on injection, which is hard to read in two names, but when you understand how it works, you'll find out exactly how accurate the description is. The essence of IOC technology is the technique of building objects in other words, the technique of instantiating a class into an object, the instantiation of a class in Java through the new keyword, each time a new class creates an instance object, which is wasteful and sometimes dangerous. Because in the program development time we often only need a class can always produce only one instance object this time we have to use a singleton mode, in addition, in the design mode can also be factory-generated objects, the use of spring people see the above text will know, The bean definition in spring corresponds to the above one by one, the scope property single produces a singleton object, prototype produces a new object, and the bean can also produce objects in Factory mode, which can be said that spring's bean is the tool to make the object. Object-oriented programming is equivalent to the display of an entity in life, for example, we have an object is to complete the operation of hunting, then hunting this object contains two helper objects: Man and gun, only man and gun to the object of hunting, then the hunting object to complete the operation of hunting, But the object of building a man and a gun is not as simple as it looks, here's a gun, for example, to create a gun we need metal, we need machines, we need bullets, and the machine and the bullets are two new objects, each one of which is nested and interrelated, Guys, imagine how complicated it would be if we were to build a gun object in Java code, and if we were to construct a more complex aircraft carrier than a simple gun object, then the cost of constructing the object would be unimaginable, and how can we eliminate the interdependent relationship between these objects? Spring provides a way for spring to provide a container in which we define the dependencies of each object in the XML file, and build the object by the container, which we can get from the container when we need to use an instance in our Java code. Then the object's build operation is taken over by the spring container, so it is called control inversion, which means that the function of building objects in a Java program is taken over by the container, and the dependency injection is when the program wants to use an object, the container injects it into the program, which is called dependency injection. In Java development, we want to use the functionality provided by a class in two ways, one is to construct a new class, the new class inherits the class, and the other is to define a class in the new class, and then create an association between the two classes. Spring's IOC container is the implementation of this association (remember not the inheritance relationship OH), then a class to be assigned to the new class what is the way? Generally only twoType: One is through the constructor, one is through the setxxx way, which is also the spring container used to two standard injection methods.

Whether it is the above-mentioned inheritance, or the relevance of the method is to enhance the target of the ability of the development means, in the design mode has a proxy mode, the proxy mode of the inheritance pattern and the association mode is used together, the proxy mode is a combination of inheritance and association mode, However, the function of this complex is not to solve the problem of object injection, but to find a babysitter or a secretary for the specific object of operation, and this is the same as the novel second Head, the head of the second external representative of the concrete example object, the entrance and exit of the instance object is through this number second head, Because the specific instance object is a head, a chief is to do great things, so some transactional, repetitive work such as tea, arranging cars, such work is not to bother a head of the house, but the head of the second to help solve, this is the idea of AOP, AOP solution development in the transactional, Issues unrelated to the core business, but these issues are necessary for the implementation of the business scenario, and AOP is also a way to save code in real-world development.

Spring's core technology is the essence of a communication mechanism, spring is always doing its best to make communication between the two sides of the information unblocked, while reducing the cost of communication between the two sides, a good communicator in the real organization is the leader of the company, will communicate the leadership can mobilize the enthusiasm of various resources, Good communication leadership will do the sea to the hundred rivers, so that a variety of different people follow him, so today's spring is a big box, anything can be installed. Spring is much like a bank, it can not directly create material wealth, but all the resources to flow through it , it can control the direction of economic development, back to the program of the world, Spring's role is advertised as decoupling between the programs, spring can reduce the coupling between different modules, The reason is that in the program development, the communication between the different modules is through the object transmission, and the object can be smoothly passed is to reasonably build the object, and the management of the object to build a way to manage the object delivery, which is the benefits of spring to the system architecture design.

^_^  ^_^  ^_^  ^_^  ^_^  ^_^  ^_^  ^_^ ^_^  ^_^  ^_^  ^_^  ^_^  ^_^  ^_^  ^_^ ^_^  ^_^  ^_^  ^_^  ^_^  ^_^  ^_^  ^_^ ^_^  ^_^ ^_^ ^_^ ^_^

Speaking of spring, Spring's business, do you understand?

  What is a transaction? Why do transactions need to be managed? What is a spring transaction? a transaction is a uniform commit or rollback operation for a series of database operations (such as inserting multiple data), and if the insert succeeds, it succeeds, and if there is an exception in the middle, all actions before the rollback. This prevents dirty data from occurring and prevents problems with database data. In development, transaction management is generally done to avoid this situation. In JDBC, the transaction is managed by the connection object, which is automatically committed by default, it can be manually closed by hand, committed by the Commit method, the rollback method is rolled back, and if not committed, the data is not actually inserted into the database. Hibernate is a transaction management through transaction, similar to the approach of JDBC. Spring also has its own transaction management mechanism, typically managed using Transactionmananger, which can be done through spring injection.

My popular understanding is as follows: Spring just controls the transaction commit and rollback of the database, with the help of the reflection mechanism of Java, get the transaction open session before and after the transaction control method (usually the service layer method), then perform your data operation, if there is an exception thrown in your method, Spring catches the exception and rolls back all the data operations you have in the method, and if successful commits all the data, then spring will help you close things that need to be closed. So what spring wants to do is to focus the programmer on writing logic, without worrying about when the database will open and close the connection.

 Again the popular point: business, for one thing, on the submission, wrong on the rollback, when the rollback, is the business to do. The specific operation is managed by the spring configuration (and you can also write your own transaction management method out of the framework).

What are the advantages of using spring transactions?

Spring acts as the role of the management container in the SSH box fake. We all know that hibernate is used to make the persistence layer, because it makes JDBC a good package, programmers can not write a large number of SQL statements when interacting with the database. Struts is used to make the application layer, and he is responsible for invoking the business logic serivce layer. So the process of the SSH framework is basically: the JSP page----Struts------Service (Business logic processing Class)---Hibernate (left to right). Struts is responsible for controlling the service (Business logic processing Class), thus controlling the service life cycle, so that the dependencies between layers and layers are strong and belong to the coupling. At this point, the spring framework is used to control the action object (in Strus) and the service class, and the relationship between the two is loose, and spring's IOC mechanism (control inversion and dependency injection) is used here.
Spring's IOC (control inversion and dependency injection) control inversion: It is the (dependency) relationship between the container control program, rather than the traditional implementation, where the dependency injection is directly manipulated by the program code: dependencies between components are determined by the container at run time, and the container dynamically injects a dependency into the component. From the above we can see: The action is only as a service control tool, how these specific business methods are implemented, he simply does not care, and will not ask, he just know that these business implementation class provided by the method interface. In the past, when using the struts framework alone, the lifecycle of all business method classes, and even some of the business processes, were controlled by action. The coupling between layers and layers is too tight, which reduces the efficiency of data access and makes the business logic look complex and the amount of code is much. The spring container controls the life cycle of all action objects and business logic classes, and because the upper layer no longer controls the lower life cycle, the layers are fully decoupled from each other, making the program more efficient to run and easier to maintain.
  The second benefit of using spring (AOP application): Transaction handling: Transaction commit succeeds in previous JdbcTemplate, exception handling is done through Try/catch, and in spring. The spring container integrates transactiontemplate, which encapsulates all the functionality of transactional processing, including complex business functions such as transaction rollback during an exception, data submission when the operation succeeds. This is managed by the spring container, greatly reducing the amount of code for the programmer, and also has good administrative control over the transaction. Hibernate also has the management of transactions, hibernate in the transaction management is through the Sessionfactory creation and maintenance session to complete. Spring also integrates the Sessionfactory configuration without having to set the sessionafactory through Hibernate.cfg.xml. This will make good use of sping for transaction management. It avoids the need to get the session instance to start the transaction/COMMIT/ROLLBACK TRANSACTION and the tedious Try/catch operation for each data operation. These are good applications for the AOP (aspect-oriented programming) mechanism in spring. On the one hand, the development of business logic clearer, professional division of labor more easily. On the other hand, the application of SPIRNG AOP isolation reduces the coupling of the program so that we can combine the various facets in different applications to greatly improve the code reuse degree. Facilitates code reuse, especially the reuse of DAO code. Transactions are often closely associated with business rules. When the business logic changes, it means a significant change in DAO. The system scale reaches a certain degree, the change risk is quite big. The advantage of spring is that it does not change the existing DAO, only the existing service beans are configured to achieve transactional effect. At the same time, the transaction is unified in the service layer, the system structure is clearer.
Why do you say risk is windy?
Spring has two ways of configuring a transaction: The first, using XML, and the second, using the form of annotations.
Based on XML: Advantages: You can adjust the transaction management mode appropriately during the post-maintenance, and as long as you follow certain naming conventions, you can let the programmer not care about the transaction.
       Cons: The larger the system, the greater the XML configuration.
Note-based: Advantages: Configuration is convenient, as long as the programmer in the service layer code settings can be implemented. You do not need to know how many beans the system needs to give the container to inject.
       Cons: When you want to modify or delete a bean, you can't determine exactly how many other beans are dependent on the bean. (Workaround: You need to have a rigorous development document that will continue to adhere to the appropriate interface as much as possible when modifying the implementation to avoid making other beans that depend on it unavailable)

When we use SSH to develop the project, we usually set the transaction on the service layer, so when we call a method of the service layer it can ensure that all of the database updates that we perform in this method remain in one transaction. These methods that are called in the transaction layer either all succeed or all fail. Then the communication characteristics of the business are also mentioned here. If you are in this method of your service layer, in addition to calling the methods of the DAO layer, and invoking the other service methods of this class, how does the transaction rule when invoking the other service methods? I have to make sure that I fall in my way. This method is in the same transaction as my own method, otherwise how to guarantee the consistency of things. The propagation characteristic of a transaction is to solve this problem, "transactions are propagated" in spring there are multiple configurations for propagation characteristics we use only one of them in most cases: Propgation_ REQUIRED: This configuration item means that when I invoke the service layer method to open a transaction (the method that calls that layer to start creating a transaction, depends on the configuration of your AOP), then when invoking the other methods in this service layer, Creates a new transaction if the current method produces a transaction that is the result of the current method. This work is done by spring. We had to manually control the transaction without spring helping us to complete the transaction, for example, when we were using hibernate only in our project, instead of integrating into spring, we called other business logic methods in a service layer, In order to ensure that things must also pass the current Hibernate session to the next method, or by using the Threadlocal method, passing the session to the next method is actually a goal. Now that the work is done by spring, we can focus more on our business logic. Without having to worry about the issues of the business. By default, transactions are rolled back when runtimeexception occurs, so be aware of them. If you have your own exception handling mechanism to define your own exception in the event of a program error, you must inherit from the RuntimeException class so that the transaction is rolled back!

Characteristics of transactions: atomicity, consistency, isolation, persistence.
Spring Transaction Propagation Characteristics Summary: 1. As long as the bean defined as spring can use the @transactional annotation for the method inside. The transaction propagation of 2.Spring is unique to spring. Not a proxy for the underlying JDBC. 3. Using spring declarative transactions, Spring uses AOP to support declarative transactions, automatically deciding whether to open a transaction before the [method call] based on the transaction properties, and after the [method executes] decides the transaction commits or rolls back the transaction. 4.Spring supported propagation_nested and Propagation_requires_new differences: propagation_requires_new: Two transactions without a trust relationship, The success of a transaction does not depend on the condition of the B transaction. There may be a commit B failure that exists. A failure (for example, when executing to DOSOMETHINGB throws an exception) B commits, AB commits, and AB is likely to fail. Propagation_nested: Unlike propagation_requires_new, embedded transaction B trusts A. That is, a failed B failure exists. A success, B failed. A success, B success. Without a failure, B succeeds. 5. Pay special attention to the conditions of use of the propagation_nested: when using the JDBC 3.0 driver, only Datasourcetransactionmanager is supported as the transaction manager. A JDBC-driven Java.sql.Savepoint class is required. There are some JTA transaction manager implementations that may also provide the same functionality. With propagation_nested, you also need to set Platformtransactionmanager's Nestedtransactionallowed property to true; The Nestedtransactionallowed property value defaults to false;6. Pay special attention to propagation_requires_new conditions of use: Jtatransactionmanager as the transaction manager

Spring's historical Theory (data desensitization)

Contact Us

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

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

A Free Trial That Lets You Build Big!

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

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

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

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