Historical Theory of Spring (Data desensitization) and Historical Theory of spring Desensitization

Source: Internet
Author: User

Historical Theory of Spring (Data desensitization) and Historical Theory of spring Desensitization

At present, the architecture of many companies has been migrated from Struts2 to SpringMVC. Have you ever wondered why SpringMVC is used instead of Servlet + JSP to build a Java web project?

In this case, let's start with the source. The source of Struts2 is actually Servlet. Servlet is used to receive requests sent from the browser to the server, and return the response processed by the server to the user's browser. The browser communicates with the server over http, the process is that the browser assembles the request http packet according to the http Protocol packet specification according to the user's selection. The packet is transmitted to the specified server through the network, the server receives the packet information through a specific web container, such as tomcat, jetty, and jboss. The web Container will parse the http packet. If it is a user request, the finally parsed packet information will be stored in a request object. After the server uses this request to complete the corresponding processing, the server program encapsulates the result information into the response object, then, the response object is handed over to the web container, and the web Container converts the response object into an http packet, and sends the packet back to the browser. The browser finally parses the response packet, displays the final result to the user.

Web containers create servlet interfaces. servlet interfaces are the places where developers implement their own business logic. developers can develop servlet interfaces by filling in blank questions, the context or context prompt of the blank question is the request and response object. However, the servlet interface in the javaEE specification is very simple. There are three methods: init, service, and destory, but this interface is too general, therefore, the specification also provides an HttpServlet class, which provides doGet, doPost, and other methods based on the http request type. The biggest feature of the servlet interface is to define according to the characteristics of the http protocol, therefore, if you are not familiar with the http protocol during servlet development, you will encounter more or less confusing problems, especially when you encounter complicated and special requests, such as file upload, when a special file format is returned to the browser, it is not very convenient to use servlet for development. Another problem in servlet development may be overlooked, that is, the type conversion of requested data. The tp protocol is transmitted in the form of text, and it is also the text type after being parsed by the web Container. If you encounter a type such as currency, number, and date, we need to convert it according to the actual situation, if the page sends a lot of information, we have to do a lot of type conversion, this kind of work is not technical, it is a physical activity and it is easy to cause program errors. At the same time, enterprise development in java is centered around javabean, and data converted by types must be encapsulated into corresponding javabean. This transfer is definitely not a good thing for project development, so the old struts1 found a solution for this problem, that is, to define a DTO object (data transmission object) to be specifically responsible for such a thing, but in struts2, the action that replaces servlet itself is a javabean.

A Technical Feature of Java Enterprise development is the use of javabean. One of the features of struts2 is that it replaces the servlet operation class as a typical javabean, first, the struts2 framework converts and encapsulates the data transmitted on the page, and then encapsulates the request information into the javabean attribute, in this way, the type conversion and encapsulation problems are eliminated when developing web programs. As mentioned above, traditional servlets are defined based on the http protocol, it processes user requests in the form of your requests (post or get), but for a program developer, a request is specific to a url, in fact, the server is a function provided by the server, or an external action by the server. If we use servlet to develop programs, we have to convert http actions into specific business actions, this makes program development cumbersome and makes development more difficult. Therefore, struts2 replaces servlet's javabean and shields the http request methods and specific services in the servlet. Every method in javabean can correspond to each url request one by one, which inevitably reduces the difficulty of development.

Another role of Servlet is to construct a response object so that the page can get the correct response. In fact, modern browsers are a multimedia tool that can display text, images, visual screens, and other things in the browser, different resources will lead to differences in http response packets. If we use servlet development, we need to use hard encoding in java programs based on different resources. Such programs are difficult to reuse, in addition, if the programmer does not understand the processing of a certain resource, it will lead to problems. struts2 splits this logic from the java program in the form of a configuration file, the configuration method is used for unified management. This method is similar to spring's AOP method, which makes the result processing method more unified and more conducive to management, it also improves program robustness and reduces the difficulty of development.

In the MVC development mode, Servlet is the control layer in the C layer, and the control layer is like a Russian dual layer (one head is east and one head is west, one header looks at the M-layer model layer, and one header looks at the V-layer view layer. The model layer is also written in java, and the control layer is also developed in the server language, therefore, there is no natural obstacle to communication between the M layer and the C layer, but it is different from the V layer view layer. This is a cross-language communication. For browsers, it only understands html, javascript and css, the browser cannot understand the java language, but to make the server's things accepted by the browser, we must put the server's response information on the page, therefore, a technology is required to convert java information into html pages. This is the jsp technology provided in the javaEE specification. jsp is actually a server technology rather than a client technology, however, it seems to be more like html technology. In the earliest jsp development, java code is directly written to the page. Everyone knows the disadvantages. Later, the javaEE specification provides the custom tag technology, use an html Tag-like method for parsing Java code, the struts2 framework provides a complete set of custom tag technology, which does not seem to sound so much, but it plays an extraordinary role, the reason why custom tags are called custom tags is that everyone can define them by themselves. If there is no specification, it will inevitably lead to confusion, and a complete set of custom tags is a system project, A complete set of custom tags is equivalent to defining a new development language on our own, when programmers hear this, they will surely understand that the workload and Development difficulty of developing a complete set of custom tags are unimaginable, and the custom tags are closely linked to the control layer, it is difficult to add a dimension, so the custom tag provided by struts2 will bring about a qualitative overflight for business development.

  Servlet also has two important technologies: Listeners and filters, which are used in a few scenarios in web development, in most web development, we can ignore its usage. The most commonly used listener may be the listener for creating and destroying ServletContext. ServletContext is the Global Object of the entire web application, it is bound to the lifecycle of the Web application. Therefore, this listener is used to initialize and destroy the global information of the Web application, such as the initialization operation of the spring container. What is interesting is that filters have an interceptor in struts2. They are used to intercept requests, because the interceptor is a unique function of struts2, the use of interceptor in struts2 is naturally more convenient than the use of filter. In fact, the technology used by the interceptor is more advanced than the filter. Because the interceptor uses the reflection technology, the interceptor intercepts more planes, the ability to control requests is stronger, and the tasks that can be completed are more diverse.

When I first came into contact with struts2, someone told me that one of the purposes of struts design was to block requests and response objects in the control layer, these two http protocol sons may cause confusion in web development, but I often unconsciously use these two objects in actual development. I also like to use ajax for front-end development. When using ajax technology, I hate struts2's custom tags. I prefer to use javascript technology to process various types of information on pages, in the end, struts2 is a servlet variant in my eyes. Therefore, for some time, I often wondered if I could discard struts2 and directly use servlet, because struts2 uses too many reflection mechanisms, in particular, annotations are used for configuration (annotations are implemented using reflection). Reflection execution efficiency in java is very low. using servlet directly can definitely improve the execution efficiency of web applications. In fact, this is very difficult to do, because at that time I was unable to flexibly use spring Technology in servlet.

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

Let's talk about the transition from Servlet + jsp technology to Struts2 technology. Next, let's talk about Spring.

Spring technology can be said to be the most important technology in java Enterprise development, but it is really troublesome to understand the role and significance of spring, many people understand spring at the usage stage (for example, declarative transactions are very useful). Today's spring technology ecosystem is spectacular and spring is all-encompassing, its content is no less than its source java language, and such a large box of spring is built on ioc and aop technology, only by understanding these two technologies can we understand why the spring box can hold so many things.

The first is ioc. The first explanation of ioc technology is control inversion. It also has dependency injection, which is hard to be understood literally, but when you understand its principles, you will find how accurate their descriptions are. The essence of Ioc technology is the technology of object construction. In other words, it is the technology of converting a class instance into an object. Classes are instantiated in java through the new keyword, every time a new class is added, a new instance object will be generated. This is a waste, and sometimes this waste is quite dangerous, during program development, we often only need a class to generate only one instance object. In this case, we need to use the singleton mode. In addition, in the design mode, we can also generate objects in the factory mode, people who have used spring can see the above text, and bean definitions in spring correspond to the above content one by one. The scope attribute single generates a singleton object, and prototype generates a new object, bean can also generate objects through the factory method. spring bean is a tool for manufacturing objects. In object-oriented programming, objects are equivalent to displaying an entity in life. For example, if an object is used to complete hunting, then the hunting object contains two secondary objects: People and guns, only when people and guns are assigned a hunting object can the hunting object complete the hunting operation. However, it is not as simple as it looks to build a person and a gun. Here we take a gun as an example, to create a gun, we need metal, machine tools, and bullets. Machine tools and bullets are two new objects. These objects are nested and correlated with each other, imagine how complicated it is if we construct a gun object in java code. If we want to construct a more complex aircraft carrier instead of a simple gun object, it is hard to imagine the high cost of constructing this object. How can we eliminate the mutual dependency between such objects? Spring provides a method in which spring provides a container. We define the dependencies of each object in the xml file, and the container builds the object, when we need to use an instance in java code, we can get it from the container, so the object construction operation is taken over by the spring container, so it is called control inversion, control inversion means that the function of building an object in a java program is taken over by the container. Dependency injection means that when the program wants to use an object, the container will inject it into the program, this is called dependency injection. In java Development, we want to use the functions provided by a class. One method is to construct a new class and the new class inherits the class, another way is to define a class in the new class, so the two classes establish an association relationship, the ioc container of spring implements this Association (remember that it is not an inheritance relationship). So what can be done to assign a class to a new class? Generally, there are only two types: constructor and setXXX, which are two standard injection methods used by spring containers.

Both the Inheritance Method and association method mentioned above are the development methods to enhance the target object capabilities. There is a proxy mode in the design mode, proxy mode combines the inheritance mode and association mode. Proxy mode is a combination of inheritance mode and association mode. However, the role of proxy mode is not to solve the problem of object injection, instead, find a nanny or secretary for the specific operation object. This is the same as head 2 in the novel. This head 2 represents the actual instance object, the entry and exit of the Instance Object are all through this no. 2 head, because the specific instance object is No. 1 Head, and No. 1 head is to do things, so some transactional and repetitive work such as tea, you don't have to bother with the big drive of head 1. Instead, head 2 helps solve the problem. This is the idea of aop, which solves the transaction issues in program development, these problems are irrelevant to the core business, but they are necessary for the implementation of business scenarios. In actual development, aop is also a way to save code.

The essence of Spring's core technology is a communication mechanism. spring always tries its best to smooth the communication information and reduce the communication costs, in a real organization, a person who is good at communication must be the leader of the company. The leaders who are good at communication can mobilize the enthusiasm of various resources. The leaders who are good at communication will be able to achieve the goal of Haina baichuan, let different people follow him, so today's spring is a big box, everything can be installed in the past.Spring is like a bank. It cannot directly create material wealth, but all resources need to flow through it,It can control the trend of economic development and return to the program world. spring is advertised as the decoupling between programs. spring can reduce the coupling between different modules, the reason is that in program development, information communication between different modules is completed through object transmission, and whether objects can be smoothly transmitted is to properly construct objects, the Building Method of managed objects can manage object delivery, which is the benefit of spring for system architecture design.

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

Speaking of Spring, do you understand Spring transactions?

  What is a transaction? Why do transactions need to be managed? What is a Spring transaction?A transaction is a unified commit or rollback operation on a series of database operations (such as inserting multiple data records). If the insertion is successful, the operation succeeds together. If one of the operations has an exception, all operations before rollback. This prevents dirty data and database data problems. In development, transaction management is generally performed to avoid this situation. In JDBC, the transaction is managed through the Connection object. By default, the transaction is automatically committed. You can manually close the automatic commit, commit using the commit method, and roll back using the rollback method, if no data is submitted, the data is not inserted into the database. In Hibernate, Transaction management is performed through Transaction, which is similar to that in JDBC. Spring also has its own transaction management mechanism, which is generally managed using TransactionMananger. This function can be completed through Spring injection.

My general understanding is as follows: spring only controls the transaction commit and rollback of the database. With the help of the java reflection mechanism, the transaction control method (usually the service layer method) start the session before and after obtaining the transaction, and then execute your data operations. If an exception is thrown in your method, spring will capture the exception and roll back all your data operations in this method, if yes, submit all the data, and spring will help you close things that need to be disabled. So what spring wants to do is to focus programmers on writing logic without worrying about when to enable or disable the database connection.

 Let's talk about it more broadly: transactions, for one thing, commit right, roll back if they are wrong, and when to roll back are all things to be done by transactions. The specific operations are managed by spring configuration (you can also write the transaction management method by yourself without the framework ).

Advantages of using Spring transactions?

 

In the SSH box, Spring acts as the management container. We all know that Hibernate is used as a persistence layer, because it encapsulates JDBC well. programmers do not need to write a large number of SQL statements when interacting with the database. Struts is used for the application layer. It is responsible for calling the serivce layer of the business logic. Therefore, the SSH Framework process is roughly: Jsp page ---- Struts ------ Service (business logic processing class) --- Hibernate (left to right ). Struts is responsible for controlling the Service (business logic processing class) and thus controlling the Service lifecycle. In this way, the dependency between layers is strong and is coupled. In this case, the spring framework is used to control the Action objects (in Strus) and Service classes. The relationship between the two is loose, and the Ioc mechanism of Spring (control inversion and dependency injection) it is used here.
Spring Ioc (control inversion and dependency injection) control inversion: control the (dependency) Relationship between programs by containers. In non-traditional implementations, dependency injection is directly controlled by program code: the dependency between components is determined by the container's runtime, and the container dynamically injects a dependency into the component. From the above, we can easily see that from the beginning to the end Action is just a Service control tool, and how these specific business methods are implemented, he will not care about it or ask, he only needs to know the method interfaces provided by these business implementation classes. In the past, when the Struts framework was used independently, the lifecycle of all business method classes and even some business processes were controlled by actions. The coupling between layers is too tight, which not only reduces the efficiency of data access, but also makes the business logic look very complex and has a lot of code. The Spring container controls the lifecycle of all Action objects and business logic classes. Because the upper layer no longer controls the lifecycle of the lower layer, the layer and layer are completely decoupled, making the program running more efficient, it is easy to maintain.
The second advantage of using Spring (AOP application): Transaction Processing: In the past JDBCTemplate, the transaction was committed successfully, and Exception Processing was completed through Try/Catch, but in Spring. The Spring container integrates TransactionTemplate, which encapsulates all transaction processing functions, including complex business functions such as rollback of abnormal current events and data submission during successful operations. These are all managed by Spring containers, which greatly reduces the amount of code for programmers and provides good management control over transactions. Hibernate also manages transactions. In hibernate, transaction management is completed by creating and maintaining sessions through SessionFactory. Spring also integrates SessionFactory configuration and does not need to set SessionaFactory through hibernate. cfg. xml. In this way, the powerful transaction management functions of Sping can be well utilized. This avoids getting Session instances for each data operation to start transactions, commit transactions, and roll back transactions. There are also tedious Try/Catch operations. These are the good applications of the AOP mechanism in Spring. On the one hand, it makes the development business logic clearer and the professional division of labor easier. On the other hand, the application Spirng AOP isolation Reduces Program coupling so that we can combine each aspect in different applications to greatly improve code reuse. It facilitates code reuse, especially Dao code reuse. Transactions are often closely related to business rules. When the business logic changes, it means a significant change to dao. The scale of the system reaches a certain level, and the risk of modification is quite high. The advantage of Spring is that you do not need to change the existing dao. You only need to configure the existing service bean to achieve the transaction effect. At the same time, the transaction is unified at the service layer, and the system structure is clearer.
Why is the risk high?
Spring has two ways to configure transactions: xml and annotation.
XMl-based approach: the advantage is that the transaction management mode can be adjusted appropriately during later maintenance, and programmers do not have to worry about transactions as long as they follow certain naming rules.
Disadvantage: the larger the system, the larger the xml configuration.
Annotation-Based Method: Advantages: easy to configure. Programmers only need to set code at the service layer. You don't need to know the number of beans required by the system. Just give them to the container for injection.
Disadvantage: When you want to modify or delete a bean, you cannot determine how many other beans depend on it. (Solution: strict development documents are required. When you modify the implementation, follow the corresponding interfaces as much as possible to avoid making other beans dependent on this unavailable)

When we use SSH to develop a project, we usually set the transaction in the Service layer. When we call a method on the Service layer, it can ensure that all database update operations executed in this method are kept in one transaction, the methods called in the Transaction layer are either all successful or all failed. The propagation feature of transactions is also mentioned here. In this method of your Service layer, besides calling the Dao layer method, you also call other Service methods of this class, so how do I specify this transaction when calling other Service methods, I must ensure that the method I used in my method is in the same transaction as my own method; otherwise, how can I ensure the consistency of things. The propagation feature of transactions is to solve this problem. "transactions will be propagated." In Spring, there are multiple configurations for the propagation feature. In most cases, we only use one of them: PROPGATION_REQUIRED: this configuration item means that a transaction is started when I call the service-layer method (the specific method to call that layer to start transaction creation depends on your aop configuration ), when other methods in the service layer are called, if the current method generates a transaction, it will use the transaction generated by the current method; otherwise, a new transaction will be created. This work is done by Spring to help us. In the past, when we had no Spring to help us complete the transaction, we had to manually control the transaction. For example, when we only used hibernate in our project and didn't integrate it into spring, we call other business logic methods in a service layer. To ensure that things must pass the current hibernate session to the next method, or use the ThreadLocal method, passing sessions to the next method is actually a purpose. Now that spring is used to help us complete this task, we can focus more on our business logic. You don't have to worry about transactions. By default, transactions are rolled back when RuntimeException occurs. If you have an Exception handling mechanism to define your own Exception in case of a program error, you must inherit from the RuntimeException class to roll back the transaction!

// Transaction Features: atomicity, consistency, isolation, and persistence.
Summary of Spring transaction Propagation Features: 1. As long as the bean is defined as spring, @ Transactional annotation can be used for the methods in it. 2. Spring transaction propagation is unique to Spring. It is not a proxy for the underlying jdbc. 3. using spring declarative transactions, spring uses AOP to support declarative transactions. Based on the transaction attributes, it automatically determines whether to enable a transaction before the [method call]. after the [method execution] determines whether the transaction is committed or rolled back. 4. The difference between PROPAGATION_NESTED supported by Spring and PROPAGATION_REQUIRES_NEW: There is no trust relationship between the two transactions. The success of A transaction does not depend on the situation of B transaction. A may fail to submit B. A fails (for example, if an exception is thrown when doSomeThingB is executed). B commits, AB commits, and AB fails. PROPAGATION_NESTED: Unlike PROPAGATION_REQUIRES_NEW, embedded transaction B will trust. That is, A fails to B. A succeeds, B fails. A is successful, B is successful. If A does not exist, B fails. 5. Pay special attention to the usage conditions of PROPAGATION_NESTED: When the JDBC 3.0 driver is used, only cetcetransactionmanager can be used as the Transaction Manager. Java. SQL. Savepoint class that requires a JDBC driver. Some JTA Transaction Manager implementations may also provide the same functionality. When using PROPAGATION_NESTED, you also need to set the nestedTransactionAllowed attribute of PlatformTransactionManager to true, while the default value of nestedTransactionAllowed is false. 6. Pay special attention to the usage condition of PROPAGATION_REQUIRES_NEW: J

 

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.