In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-14 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >
Share
Shulou(Shulou.com)06/01 Report--
The concept of 1.AOP is Aspected Oriented Programming aspect-oriented programming.
The upside: AOP breaks down the program into aspects or concerns. This makes it possible to be modular and quite horizontally sliced. It can solve the crosscut problems that OOP and procedural methods cannot solve well, such as transaction, security, log and other crosscutting concerns.
There are several ways to implement AOP:
1. In Spring 1.2, aop is implemented through ProxyFactoryBean, that is, through dynamic proxy, Aspect must inherit MethodBeforeAdvice,MethodAfterAdvice and so on.
2. Spring 2.0 AOP needs to change the class FBI, and it no longer needs to implement some interfaces
3. Third, use annotations (@ AspectJ) to implement AOP
The difference between AOP and OOP:
1. Aspect-oriented programming AOP focuses on a certain step or stage of the business process, emphasizing reducing the degree of coupling between modules, so that the code has better portability.
two。 Object-oriented programming (oop) is the encapsulation of methods and attributes of entities extracted from business analysis.
It can also be said that AOP is oriented to the verb domain of the business, while OOP is oriented to the noun domain.
A very important feature of AOP is source code independence, which means that if we reference an AOP component in our system, even if we remove it, the system code should be able to compile. To achieve this, you can use the dynamic proxy pattern.
AOP centralizes the "aspect" code scattered in the system; AOP helps to improve system maintainability; AOP is a design pattern, and Spring provides an implementation
2.PROPAGATION_REQUIRED
If there is no current transaction, create a new transaction, and if one already exists, join it. This is the most common choice.
PROPAGATION_SUPPORTS
Supports the current transaction and executes in a non-transactional manner if there is no current transaction.
PROPAGATION_MANDATORY
Use the current transaction and throw an exception if there is no current transaction.
PROPAGATION_REQUIRES_NEW
Create a new transaction and suspend the current transaction if it exists.
PROPAGATION_NOT_SUPPORTED
The operation is performed in a non-transactional manner, suspending the current transaction if there is a current transaction.
PROPAGATION_NEVER
Executes in a non-transactional manner and throws an exception if a transaction currently exists.
PROPAGATION_NESTED
If a transaction currently exists, it is executed within a nested transaction. If there is no transaction currently, perform an operation similar to PROPAGATION_REQUIRED.
Dependency injection for 3.Spring:
There are usually two types of dependency injection: setting injection and construction injection:
Construction injection can determine the injection order of dependencies in the constructor, and priority injection of dependencies.
Setting value injection means that the IoC container uses the setter method of the property to inject the dependent instance. This injection method is relatively simple and intuitive.
4.DispatcherServlet is the implementation of the front-end controller design pattern, provides a centralized access point for Spring Web MVC, and is responsible for the assignment of responsibilities
And it integrates seamlessly with the Spring IoC container, so you can get all the benefits of Spring.
DispatcherServlet is mainly used for responsibility scheduling, and itself is mainly used to control the process. The main responsibilities are as follows:
1. File upload resolution. If the request type is multipart, file upload resolution will be performed through MultipartResolver.
2. Map the request to the processor through HandlerMapping (return a HandlerExecutionChain, which includes a processor and multiple HandlerInterceptor interceptors)
3. Support multiple types of processors (processors in HandlerExecutionChain) through HandlerAdapter
4. Parse the logical view name to the concrete view through ViewResolver
5. Localization analysis
6. Render specific views, etc.
7. If an exception is encountered during execution, it will be handed over to HandlerExceptionResolver for resolution.
DispatcherServlet, the core controller of Spring MVC, is responsible for receiving HTTP requests, loading configuration files, and initializing the upper and lower application object ApplicationContext.
5. In J2EE, using Servlet filters, you need to configure (filter), (filter mapping) elements in web.xml.
The method of the 6.Servlet interface has the init method.
The methods of Servlet include init (), destroy (), doGet (), doPost () and so on.
The core ideas of the 7.Spring framework include dependency injection, control inversion, and aspect-oriented.
8. How to get connection pooling in the Spring framework:
DBCP data source
C3P0 data source
Spring data source implementation class (DriverManagerDataSource)
Get JNDI data source
9. In Servlet, the way to achieve redirection is:
The sendRedirect method of javax.servlet.http.HttpServletResponse interface is used.
The sendRedirect method is redirected
The forward method is to forward the request
10.sendRedirect ():
Redirect to let the customer get the job done, that is, if the address bar changes, you can turn to external resources. The method parameter is String. Use the relative URL as a parameter. Build a complete URL with / relative to the original URL. Establishment of relative Web applications without /.
Forward ():
Request dispatch, internal forwarding of the server, is transparent to the customer (the address bar does not change).
Based on Servlet API, the forward method can be used to realize that the diverted address is not displayed in the address bar when turning.
11.1. The Session mechanism is referenced in Java Servlet API to track the status of customers. The javax.servlet.http.HttpSession interface is defined in Servlet API, and the Servlet container must implement this interface.
two。 When a Session starts, the Servlet container creates a HttpSession object, and the Servlet container assigns a unique identifier to the HttpSession, called Session ID. The Servlet container saves Session ID as a Cookie in the customer's browser. Every time a customer makes a HTTP request, the Servlet container can read the Session ID from the HttpRequest object, and then find the corresponding HttpSession object according to the Session ID to obtain the customer's status information.
3. When the forbidden Cookie,Servlet container in the client browser cannot obtain the Session ID as the Cookie from the client browser, the customer status cannot be tracked.
Another mechanism for tracking Session is proposed in Java Servlet API. If the client browser does not support the Cookie,Servlet container, it can override the URL requested by the customer and add Session ID to the URL information.
4. The HttpServletResponse API provides a method to rewrite URL: public java.lang.String encodeURL (java.lang.String url)
The implementation mechanism of this method is as follows:
● first determines whether Session is enabled for the current Web component, and returns the parameter url directly if Session is not enabled.
● then determines whether the client browser supports Cookie. If it supports Cookie, it directly returns the parameter url;. If it does not support Cookie, add the Session ID information to the parameter url, and then return the modified url.
We can modify the links in the web page slightly to solve the above problems:
Before modification:
After modification:
twelve。 Types of transaction attributes: propagation behavior, isolation level, read-only, and transaction timeout
A) the propagation behavior defines the transaction boundary of the called method.
The meaning of communication behavior
1.PROPERGATION_MANDATORY
The representation method must run in a transaction, and if the current transaction does not exist, an exception is thrown
2.PROPAGATION_NESTED
Indicates that if the current transaction exists, the method should run in a nested transaction.
3.PROPAGATION_NEVER
The representation method cannot run in a transaction, otherwise an exception is thrown
4.PROPAGATION_NOT_SUPPORTED
The representation method cannot run in a transaction. If a transaction currently exists, the method will be suspended
5.PROPAGATION_REQUIRED
Indicates that the current method must run in a transaction, and if there is a transaction, then the method runs in that transaction, otherwise, a new transaction will be created
6.PROPAGATION_REQUIRES_NEW
Indicates that the current method must run in its own transaction, and if there is a transaction, the transaction will be suspended while the method is running
7.PROPAGATION_SUPPORTS
Indicates that the current method does not need to run in a transaction, but if a transaction already exists, the method can also run in that transaction
B) isolation level
It may bring three side effects when manipulating data, namely, dirty reading, unrepeatable reading and phantom reading.
To avoid the side effects of these three, four isolation levels are defined in the standard SQL statement.
They are uncommitted read, committed read, repeatable read, serializable.
In spring transactions, five isolation levels are provided to correspond to the four isolation levels defined in SQL
As follows:
Isolation level meaning
1.ISOLATION_DEFAULT uses the default isolation level of the back-end database
2.ISOLATION_READ_UNCOMMITTED
Allow reading of uncommitted data (corresponding to uncommitted reads), which may lead to dirty, unrepeatable and phantom readings
3.ISOLATION_READ_COMMITTED
Allows data from one transaction to be read from another committed transaction (corresponding to committed reads). Dirty reading can be avoided, but unrepeatable reading and phantom reading cannot be avoided.
4.ISOLATION_REPEATABLE_READ
It is not possible for one transaction to update data that has been modified by another transaction but has not yet been committed (rolled back) (corresponding to repeatable readings).
Dirty reading and unrepeatable reading can be avoided, but phantom reading can not be avoided.
5.ISOLATION_SERIALIZABLE
This isolation level is that all transactions are in one execution queue, executed sequentially, rather than in parallel (corresponding to serializable). Dirty reading, unrepeatable reading and phantom reading can be avoided. However, this isolation level is inefficient, so it is not recommended unless it is necessary.
C) read-only
If all operations on the database in a transaction are read-only, that is, these operations only read the data in the database and do not update the data, then the transaction should be set to read-only mode (READ_ONLY_MARKER), which is more conducive to database optimization.
Because read-only optimizations are implemented by the database after the transaction starts, it makes sense only to mark transactions that have methods of propagating behavior (PROPAGATION_NESTED, PROPAGATION_REQUIRED, PROPAGATION_REQUIRED_NEW) that may start a new transaction as read-only.
If Hibernate is used as the persistence mechanism, after marking the transaction as read-only, the flush mode of Hibernate is set to FULSH_NEVER to tell Hibernate to avoid unnecessary synchronization with the database and defer all updates until the end of the transaction.
D) transaction timeout
If a transaction runs for a long time, in order to avoid wasting system resources as much as possible, you should set an effective time for the transaction to wait a few seconds and then roll back automatically.
Like setting the read-only property, transaction valid properties need to be given to propagations that have the potential to start new things
It makes sense if the transaction of the method of the behavior is marked as read-only.
Description of IoC in 13.Spring feature:
The so-called "control inversion" refers to the transfer of control from the application code to the external container, that is, the transfer of control.
IoC moves the responsibility of control creation into the framework, separating it from the application code.
When using Spring's IoC container, you only need to indicate the objects required by the component, and at run time, Spring's IoC container will provide it based on the XML configuration data.
14.Spring framework module, seven modules, as follows:
1. Spring Core: the Core wrapper is the most basic part of the framework, providing IOC and dependency injection features. The basic concept here is BeanFactory, which provides a classic implementation of the Factory pattern to eliminate the need for a procedural singleton pattern and really allows you to separate dependencies and configurations from the program logic.
2.Spring Context: a Core wrapper built on top of a Context wrapper that provides a framed method of object access, somewhat like a JNDI registry. The features of Context wrappers are derived from Beans wrappers and add support for internationalization (i18n) (such as resource binding), event propagation, how resources are loaded, and transparent creation of Context, such as through Servlet containers.
3.Spring DAO: DAO (Data Access Object) provides an abstraction layer for JDBC that eliminates lengthy JDBC coding and parses database vendor-specific error codes. Moreover, the JDBC wrapper provides a declarative transaction management approach that is better than programmatic, not only implementing specific interfaces, but also applicable to all POJOs (plain old Java objects).
4.Spring ORM: the ORM wrapper provides an integration layer for the commonly used "object / relational" mapping APIs. These include JPA, JDO, Hibernate, and iBatis.
With ORM wrappers, you can mix all the features provided by Spring for object / relational mapping
As mentioned earlier, simple declarative transaction management.
5.Spring AOP: Spring's AOP wrapper provides aspect-oriented programming implementations that conform to the AOP Alliance specification, allowing you to define, such as method interceptors (method-interceptors) and pointcuts, logically, thus weakening the functional coupling of the code and being clearly separated. Moreover, with the metadata feature of source-level, you can incorporate all kinds of behavior information into your code.
6.Spring Web: the Web package in Spring provides basic integration features for Web development, such as multi-party file uploads, IOC container initialization with Servlet listeners, and ApplicationContext for Web. When using Spring with WebWork or Struts, this package enables Spring to be integrated with other frameworks.
7.Spring Web MVC: the MVC wrapper in Spring provides a Model-View-Controller (MVC) implementation of Web applications. Spring's MVC framework does not just provide a traditional implementation, it provides a clear separation model between domain model code and Web Form. Also, you can take advantage of other features of the Spring framework.
15.spring 's description of the life cycle of bean:
If the Bean class has an implementation org.springframework.beans.factory.BeanFactoryAware interface
The factory calls the setBeanFactory () method to pass in the factory itself.
You can use the "init-method" attribute in the Bean definition file
Rg.springframework.beans.factory.DisposableBean interface
His destroy () method is executed.
Create:
Initialization: configure init-method/ to implement interface InitializingBean
Call: context.getBean () to call the method
Destroy: configure destroy-method/ to implement the DisposableBean interface.
The main purpose of DAO (data access objects) support provided by 16.Spring is to facilitate the use of different data access technologies in a standard way.
Simplify the development of DAO components.
Spring provides a set of abstract DAO classes for you to extend. These abstract classes provide methods to simplify code development. The use of IoC containers provides decoupling between DAO components and business logic components. All DAO components are injected into the business logic components by the container, and the business components do not need to care about the implementation of DAO components. Interface-oriented programming and the use of DAO mode improve the decoupling between system components.
The cost of system reconfiguration is reduced.
Convenient transaction management: Spring's declarative transaction management strength is at the method level.
Exception wrapper: Spring can wrap Hibernate exceptions and change them from CheckedException
For RuntimeException; developers to choose to handle irrecoverable exceptions in data at the appropriate layer
So as to avoid cumbersome catch/throw and exception declaration.
DAO provided by Spring supports JDBC, JDO, and Hibernate.
The difference between 17.spring mvc and struts2:
1.spring mvc is method-based design, while struts2 is class-based design.
2.struts2 has its own interceptor mechanism, and spring mvc uses an independent AOP approach.
3.spring mvc methods are basically independent of each other, with exclusive request response data, and all Action variables of struts2 are shared.
4. Mechanism: the entry to spring mvc is servlet, while struts2 is filter.
Add a few pieces of knowledge:
"Filter implements the javax.servlet.Filter interface, which is configured and labeled in web.xml to specify which to use
Which URL links are filtered by the Filter implementation class. Initialization occurs only when web starts.
The filter process is linear. After the url is sent, after the check, the original process can be maintained to continue to execute downwards.
It is received by the next filter, servlet, etc., but after servlet processing, it does not continue to pass down.
The filter function can be used to keep the process going the way it was, or to dominate the process, while the function of servlet is mainly used to dominate the process.
Features: the headers of Request and Response can be modified before the response. You can only forward the request, not send the response directly.
Filter can be used to filter character encodings, detect whether users have logged in, disable page caching, etc. "Servlet, servlet process is short, after the url comes, it will be processed, and then return or go to a specified page. It is mainly used to control before business processing. "
"where's Listener? We know that servlet and filter are for url and the like, while listener is for object operations, such as the creation of session, the occurrence of session.setAttribute, to do something when such events occur. "
5. Performance: spring will be slightly faster than struts. Spring mvc is method-based design, while sturts is class-based, each request will instantiate an action, each action will be injected with attributes, while spring is method-based and finer-grained (things at the granularity level compare sychronized and lock), but be careful as you control data in servlet.
Spring3 mvc is a method-level interception that injects request data into the method according to the comments on the parameters. In spring3 mvc, a method corresponds to a request context. The struts2 framework is class-level interception, creating an Action every time a request comes, and then calling the setter getter method to inject the data in the request; struts2 actually deals with request through the setter getter method; in struts2, an Action object corresponds to a request context.
6. Parameter passing: when struts accepts parameters, it can use properties to accept parameters, which means that parameters are shared by multiple methods.
7. Design idea: struts is more in line with the programming idea of oop, while spring is more cautious and extends on servlet.
8. The implementation mechanism of intercepter (interceptor): struts has its own interceptor mechanism, and spring mvc uses an independent AOP mode. As a result, the number of configuration files of struts is still larger than that of spring mvc, although the configuration of struts can be inherited, so I think, in terms of use, the use of spring mvc is simpler, and the development efficiency of Spring MVC is indeed higher than that of struts2. Spring mvc is method-level interception, a method corresponds to a request context, and a method corresponds to a url at the same time, so spring3 mvc is easy to implement restful url from the architecture itself. Struts2 is a class-level interception, and a class corresponds to a request context; implementing restful url is laborious, because a method of struts2 action can correspond to a url; and its class properties are shared by all methods, so it is impossible to identify the method it belongs to by annotations or other means. Spring3 mvc methods are basically independent, exclusive request response data, request data to be obtained through parameters, processing results returned to the framework methods through ModelMap do not share variables, and struts2 is quite messy, although the methods are also independent, but all its Action variables are shared, which does not affect the running of the program, but brings trouble to us when coding and reading the program.
9. In addition, the verification of spring3 mvc is also a bright spot. It supports JSR303, and it is more convenient to handle the request for ajax. You only need an annotation @ ResponseBody, and then return the response text directly.
18.spring 's IOC container can help us automatically new the object. After the object is handed over to spring, we don't have to manually new the object, that is, the transfer of control.
Spring uses BeanFactory to instantiate, configure, and manage objects, but it's just an interface with a getBean () method.
We usually do not use BeanFactory directly, but use its implementation class ApplicationContext, which automatically parses our configured applicationContext.
Spring dependency injection:
IOC spring is responsible for controlling the life cycle of objects and the relationship between objects.
BeanFacotry is the simplest container that provides basic dependency injection support. ApplicationContext is built on BeanFacotry and provides system architecture services.
19.spring does not provide an AOP log system.
AOP is the abbreviation of Aspect Oriented Programming, which means: a technology for aspect-oriented programming, which realizes the unified maintenance of program functions through precompilation and run-time dynamic agents. AOP is the continuation of OOP, is a hot spot in software development, is also an important content of Spring framework, and is a derivative paradigm of functional programming.
Through the support of AOP, Spring implements the log system with the help of Apache open source components such as log4j.
Spring is a collection of lightweight Java EE frameworks. An implementation of the dependency injection pattern is included in Spring. Declarative transactions can be implemented using Spring.
20.Servlet is a special Java class that must implement the Servlet interface directly or indirectly.
The Servlet client thread calls the service method to respond to the customer's request. The servlet interface defines the life cycle methods of servlet: init (), service (), and destory (). When multiple browser terminals request a web server, the server starts a thread for each client, not a process. Import javax.servlet.http.httpservletrequest, you see, this package shows that servlet is a special Java class, java and javax are Java's API package, java is the core package, and javax's x means extension, that is, the expansion package.
One of the features of 21.Spring is its simple and powerful transaction management capabilities, including programmatic transactions and declarative transactions.
1. There are more than 100 API involved in transaction management in Spring, and there are only three core ones: TransactionDefinition, PlatformTransactionManager and TransactionStatus. Transaction management is actually "performing commit or rollback operations according to given transaction rules". "given transaction rules" is expressed by TransactionDefinition, "perform commit or rollback operations according to..." is expressed by PlatformTransactionManager, and TransactionStatus is used to represent the status of a running transaction.
2. TransactionDefinition, which was introduced earlier, is used to define a transaction. It contains the static properties of the transaction, such as transaction propagation behavior, timeout, and so on. Spring provides us with a default implementation class: DefaultTransactionDefinition, which is suitable for most situations. If the class does not meet the requirements, you can implement your own transaction definition by implementing the TransactionDefinition interface.
3. PlatformTransactionManager is used to perform specific transaction operations.
Public interface PlatformTransactionManager {
TransactionStatus getTransaction (TransactionDefinition definition) throws TransactionException
Void commit (TransactionStatus status) throws TransactionException
Void rollback (TransactionStatus status) throws TransactionException
}
Depending on the persistence API or framework used at the underlying level, the main implementation classes of PlatformTransactionManager are roughly as follows:
DataSourceTransactionManager: suitable for data persistence operations using JDBC and iBatis.
HibernateTransactionManager: suitable for data persistence operations using Hibernate.
JpaTransactionManager: suitable for data persistence operations using JPA.
There are also JtaTransactionManager, JdoTransactionManager, JmsTransactionManager and so on.
4. Programmatic transactions require you to add transaction logic directly to the code, and you may need to explicitly call beginTransaction (), commit (), rollback () and other transaction management related methods in the code. For example, if you need transaction processing when executing a method, you need to open the transaction at the beginning of a method and after processing. Close the transaction at the end of the method. Declarative transactions are done by adding comments around the a method or defining it directly in the configuration file, which requires a transaction and is intercepted and added before and after the a method through the configuration file in spring. The difference between the two. Programmatic transactions are more intrusive, but the processing granularity is finer. One is equivalent to a manual transaction and the other is a system automatic transaction. Programming trial transactions require manual code to commit transactions, roll back transactions, and so on. Declarative transaction is to define when a transaction is needed in the configuration file, when the system will automatically commit, if there is an exception, automatic rollback, there is no need to write commit or rollback in the code.
Spring transactions:
Spring transactions can be divided into programmatic transactions and declarative transactions.
Spring provides a transaction interface PaltformTractionManager interface, and spring implements different implementations for different transactions.
The biggest advantage of declarative transactions is that there is no need to manage transactions programmatically, so there is no need to mix transaction management code with business logic code.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.