[Java interview questions summary 7] Spring framework comprehensive articles (with answers)

Chapter 7 Spring/SpringMVC

1. What is the Spring framework? What are the main modules of the Spring framework?

Spring is an inversion of control and aspect-oriented container framework.

Spring has seven functional modules:

1. Core

The Core module is the core library of Spring, and Core implements the IOC function.

2. AOP

The Apring AOP module is Spring's AOP library, which provides an AOP (interceptor) mechanism and provides common interceptors for users to customize and configure.

3. orm

Provide management and support for commonly used ORM frameworks, hibernate, mybatis, etc.

4. Dao

Spring provides support for JDBC and encapsulates JDBC.

5. Web

Support for Struts2.

6. Context

The Context module provides a framework for accessing Beans, and other programs can access Spring Bean resources through Context, which is equivalent to resource injection.

7, MVC

The MVC module provides a set of lightweight MVC implementations for Spring, namely Spring MVC.

2. What are the benefits of using the Spring framework?

1. Lightweight framework and container

Spring is a container that manages the life cycle and configuration of objects. Based on a configurable prototype prototype, your bean can be simple, or it can generate a new instance every time it is needed.

2. Inversion of control IOC

Spring achieves loose coupling through inversion of control.

3. Support AOP

Spring provides support for AOP, which allows centralized processing of some common tasks, such as security, transactions, and logs, thereby improving the reusability of the program.

4. Lightweight framework

5. Convenient for testing

Spring provides support for Junit4, which can facilitate testing of spring programs through annotations.

6. Many APIs in Java are encapsulated

7. Facilitate the integration of various excellent frameworks

Such as Struts, hibernate, mybstis.

8. Support declarative transaction processing

Only need to configure to complete the management of the transaction, without manual programming.

Three, Spring IOC, AOP examples

1. The background of IOC theory

We all know that in a software system designed with an object-oriented method, its underlying implementation is composed of N objects, and all objects cooperate with each other to finally realize the business logic of the system.

If we open the back cover of a mechanical watch, we will see a situation similar to the above. Each gear drives the hour, minute, and second hands to rotate clockwise to produce the correct time on the dial. Figure 1 depicts such a gear set, which has multiple independent gears that mesh with each other and work together to complete a certain task. We can see that in such a gear set, if there is a problem with one gear, it may affect the normal operation of the entire gear set.
The meshing relationship between gears in a gear set is very similar to the coupling relationship between objects in a software system. The coupling relationship between objects is inevitable and necessary. This is the basis of collaborative work. Now, with the increasing scale of industrial applications, the dependencies between objects are becoming more and more complex, and multiple dependencies between objects often appear. Therefore, architects and designers analyze and analyze the system. Design will face greater challenges. A system with too high coupling between objects will inevitably lead to a situation where the whole body is affected.

Coupling relationships will not only appear between objects, but also between the modules of the software system, and between the software system and the hardware system. How to reduce the coupling between systems, modules and objects is one of the goals that software engineering always pursues. In order to solve the problem of excessive coupling between objects, software expert Michael Mattson proposed the IOC theory to achieve "decoupling" between objects. At present, this theory has been successfully applied to practice, and many J2EE projects All adopt IOC framework product Spring.

2. What is inversion of control

IOC is the abbreviation of Inversion of Control. Most books are translated as "inversion of control", and some books are translated as "inversion of control" or "inversion of control".
In 1996, Michael Mattson first proposed the concept of IOC in an article about discussing object-oriented frameworks. For the basic ideas of object-oriented design and programming, we have already talked a lot before, and will not repeat them. In simple terms, it is to decompose a complex system into mutually cooperating objects. After these object classes are encapsulated, the internal implementation is transparent to the outside. , Thereby reducing the complexity of solving the problem, and can be flexibly reused and extended. The viewpoint put forward by IOC theory is roughly like this: the decoupling between dependent objects is achieved with the help of "third parties", as shown in the following figure:

As you can see, due to the introduction of the "third party" in the middle position, that is, the IOC container, the four objects of A, B, C, and D have no coupling relationship, and the transmission between the gears is all dependent on the "third party" , The control of all objects is handed over to the "third-party" IOC container. Therefore, the IOC container becomes the key core of the entire system. It acts like a "glue" to glue all the objects in the system. To play a role together, if there is no such "glue", the object and the object will lose contact with each other. This is why some people compare the IOC container to the "glue".
Let's do another experiment: remove the IOC container in the middle of the picture above, and then take a look at this system (the system after the IoC container is removed):

The picture we are seeing now is all that we need to complete to realize the entire system. At this time, the four objects of A, B, C, and D are no longer coupled and have no connection with each other. In this case, when you are implementing A, you don’t need to think about B, C, and D anymore. The dependencies between objects have been reduced to a minimum. Therefore, if the IOC container can be implemented, it will be a wonderful thing for system development. Every member participating in the development only needs to implement their own class, and has nothing to do with others!
Let's take a look again, why does Inversion of Control (IOC) have such a name? Let’s compare:
Before the software system introduced the IOC container, as shown in Figure 1, object A depends on object B. Then when object A is initialized or run to a certain point, it must actively create object B or use Object B created. Whether you are creating or using Object B, you have control over it.
After the software system introduces the IOC container, this situation has completely changed. As shown in Figure 3, due to the addition of the IOC container, the direct connection between object A and object B is lost. Therefore, when object A runs to need object B At the time, the IOC container will actively create an object B and inject it into the place where the object A needs it.
Through the comparison before and after, it is not difficult to see: the process of object A obtaining dependent object B has changed from active behavior to passive behavior, and the right of control is reversed. This is the origin of the name "inversion of control".

3. The alias of IOC: Dependency Injection (DI)

In 2004, Martin Fowler discussed the same question. Since IOC is an inversion of control, then what is the aspect of control that has been inverted? After detailed analysis and demonstration, he came up with the answer: "Get The process of relying on objects is reversed." After the control is reversed, the process of obtaining dependent objects changes from self-management to active injection by the IOC container. Therefore, he gave a more appropriate name to "Inversion of Control" called "Dependency Injection". His answer actually gives a method to implement IOC: injection. The so-called dependency injection means that the IOC container dynamically injects a certain dependency into the object during its operation.

Therefore, Dependency Injection (DI) and Inversion of Control (IOC) are the same thing described from different perspectives, that is, through the introduction of IOC containers, the use of dependency injection to achieve decoupling between objects.
Let's give a life example to help understand the process of dependency injection. Everyone should be familiar with USB interfaces and USB devices. USB provides great convenience for us to use computers. Nowadays, many external devices support USB interfaces.

Now, we use the host computer and USB interface to achieve a task: read a file from an external USB device.
When the host computer reads the file, it doesn't care at all what external device is connected to the USB interface, and it does not need to know. Its task is to read the USB interface, and the connected external device only needs to comply with the USB interface standard. Therefore, if I connect a USB flash drive to the host computer, the host reads files from the USB flash drive; if I connect an external hard drive to the host computer, the host computer reads files from the external hard drive. The power to connect external devices is my control, that is, the control power belongs to me. As for what device is connected to the USB interface, the computer host cannot decide, it can only passively accept it. When the host computer needs external equipment, you don’t need it to tell me at all, and I will take the initiative to help it hook up the external equipment it wants. You see how well my service is in place. This is a common example of dependency injection in our lives. In this process, I played the role of IOC container.
Through this example, the idea of ​​dependency injection is very clear: when the host computer reads a file, I will connect the external device it depends on for him. The entire external device injection process is exactly the same as the process in which a dependent object is injected into another object while the system is running.
We apply dependency injection to the software system, and then describe this process:
Object A depends on Object B. When Object A needs to use Object B, the IOC container will immediately create an Object B and send it to Object A. The IOC container is an object manufacturing factory. Whatever you need, it will be sent to you. You can use it directly, and you no longer need to care about how the things you use are made or how they are finally destroyed. , All this is done by the IOC container.
In the traditional implementation, the internal code of the program controls the relationship between the components. We often use the new keyword to achieve the combination of the relationship between the two components, this implementation will cause coupling between the components. IOC solves this problem well. It will realize the relationship between components from the inside of the program to the external container, which means that the container dynamically injects a certain dependency between the components into the component at runtime.

4. What benefits does IOC bring to us

Let's start with the example of USB. What are the benefits of using USB external devices over using internal hard drives?
First, as an external device of the computer host, the USB device has no relationship with the computer host before it is inserted into the host. Only after being connected by us, the two will be connected and related. Therefore, no matter what problem occurs in either of the two, it will not affect the operation of the other. This feature is reflected in software engineering, that is, maintainability is relatively good, it is very convenient for unit testing, and easy to debug programs and diagnose faults. Each Class in the code can be tested individually, without affecting each other, as long as its function is correct, which is the benefit of low or no coupling between components.
Second, the irrelevance between the USB device and the computer host brings another benefit. The manufacturer of the USB device and the manufacturer of the computer host can be completely unrelated to each other, doing their own things. The only thing that needs to be complied with is the USB interface standard. This feature is reflected in the software development process, but the benefits are too great. Each member of the development team only needs to care about the realization of their own business logic, and does not need to care about the progress of other people at all, because your task has nothing to do with others, your task can be tested separately, and your task does not need to be dependent on There is no need to confuse other people's components anymore. Therefore, in a large and medium-sized project, team members have a clear division of labor and clear responsibilities. It is easy to divide a large task into small tasks, and the development efficiency and product quality will be greatly improved.
Third, the same USB peripheral device can be plugged into any device that supports USB, it can be plugged into a computer host, or it can be plugged into a DV machine, and the USB peripheral device can be used repeatedly. In software engineering, this feature is good reusability. We can isolate common components that are common and reuse them in other parts of the project or other projects. Of course, this is also the basic feature of object-oriented. Obviously, IOC not only better implements this principle, but also improves the reusability of modules. Any implementation that conforms to the interface standard can be plugged into a module that supports this standard.
Fourth, as with USB peripherals, the module has hot-swappable features. The method of IOC generation of objects is converted to an external method, that is, the object generation is defined in the configuration file. In this way, when we change an implementation subclass, it will become very simple. Just modify the configuration file. Hot-swappable features.
The above benefits are not enough to impress us, let us use the IOC framework in the project development process?

5. Technical analysis of IOC container

The most basic technology in IOC is "Reflection" programming. Currently, languages ​​such as .Net C#, Java and PHP5 are all supported. Among them, PHP5 technical books are sometimes translated as "mapping". Regarding the concept and usage of reflection, everyone should be very clear. In layman's terms, it is to dynamically generate objects based on the given class name (string mode). This programming method allows the object to determine which type of object it is when it is generated. The application of reflection is very extensive. Many mature frameworks, such as Hibernate and Spring frameworks in Java, NHibernate and Spring.Net frameworks in .Net, all use "reflection" as the most basic technical means.
In fact, reflection technology appeared very early, but it has been ignored and has not been further utilized. The reflection programming method at the time was at least 10 times slower than the normal object generation method. The current reflection technology has been improved and optimized, and it is very mature. The speed of the reflection method for generating objects and the usual object generation methods is not much different, about 1-2 times the difference.
We can regard the working mode of the IOC container as a sublimation of the factory model. We can regard the IOC container as a factory. The objects to be produced in this factory are defined in the configuration file, and then use the reflection programming of the programming language. , According to the class name given in the configuration file to generate the corresponding object. From the implementation point of view, IOC is to change the object generation code previously written in the factory method to be defined by the configuration file, that is, to separate the factory and the object generation independently, the purpose is to improve flexibility and Maintainability.

6. Some products of IOC container

The IOC containers under the Sun ONE technology system include: the lightweight ones include Spring, Guice, Pico Container, Avalon, and HiveMind; the heavyweight ones include EJB; the less important ones include JBoss, Jdon, and so on. As one of the three swordsmen of SSH (Struts, Spring, Hibernate) in Java development, Spring framework is used in large, medium and small projects. It is very mature and widely used. EJB is also used in key industrial projects, such as some telecommunications. business.
The IOC containers under the .Net technology system include: Spring.Net, Castle, and so on. Spring.Net is an IOC container ported from Java's Spring, and Castle's IOC container is the Windsor part. They are all lightweight frameworks and relatively mature, among which Spring.Net has been gradually applied to various projects.

7. What should be paid attention to when using the IOC framework

Using IOC framework products can bring great benefits to our development process, but we must also fully understand the shortcomings of introducing the IOC framework, be aware of it, and prevent abuse of the framework.

(1) Due to the introduction of a third-party IOC container in the software system, the steps to generate objects have become a bit complicated. It was originally a matter between the two, but there was an extra procedure out of thin air. Therefore, when we first started using the IOC framework , It will feel that the system becomes less intuitive. Therefore, the introduction of a brand new framework will increase the cost of training for team members to learn and understand, and in the future operation and maintenance, new entrants must have the same knowledge system.

(2) Since the IOC container generates objects through reflection, there is a certain loss in operating efficiency. If you want to pursue operational efficiency, you must weigh this.

(3) In terms of specific IOC framework products (such as: Spring), a lot of preparation work is required, which is relatively cumbersome. For some small projects, it may objectively increase some work costs.

(4) The maturity of the IOC framework product itself needs to be evaluated. If an immature IOC framework product is introduced, the entire project will be affected, so this is also a hidden risk.
We can roughly conclude that some projects or products with a small workload are not suitable for using IOC framework products. In addition, if team members lack knowledge and ability, and lack in-depth understanding of IOC framework products, don't introduce them rashly. Finally, projects or products that particularly emphasize operational efficiency are not suitable for the introduction of IOC framework products, as is the case with WEB2.0 websites.

4. What is Inversion of Control (IOC)? What is dependency injection?

Realize the decoupling between dependent objects with the help of Spring.

The operation of object A requires object B, from active creation to IOC container injection, which is the inversion of control.

The process of obtaining dependent objects is reversed. The process of obtaining dependent objects is changed from self-creation to injection by the IOC container. This is dependency injection.

5. What is the difference between BeanFactory and ApplicationContext?

1. BeanFactory is the lowest-level interface of Spring. It contains bean definition, manages bean loading, instantiation, and controls bean life cycle. The characteristic is that an object is created every time an object is obtained.

ApplicationContext is a sub-interface of BeanFactory, which has all the functions of BeanFactory and extends many advanced features. All objects are created every time the container is started.

  1. Additional features of ApplicationContext:
  2. Inherit MessageSource and support internationalization;
  3. Unified resource file access method;
  4. Provide to register the bean in the listener;
  5. Loaded a configuration file at the same time;
  6. Load multiple (inherited) contexts, so that each context focuses on a specific level, such as the web layer of the application;

2. BeanFactory is usually created programmatically, and ApplicationContext can be created in a declarative way, such as using ContextLoader.

3. Both BeanFactory and ApplicationContext support BeanPostProcessor, BeanFactoryPostProcessor, but BeanFactory needs to be registered manually, and ApplicationContext is automatically registered.

6. What is JavaConfig?

JavaConfig is a new concept in Spring 3.0, which replaces the cumbersome xml files in Spring in the form of annotations.

JavaConfig combines the advantages of xml decoupling and java compile-time checking.

  1. @Configuration, indicating that this class is a configuration class;
  2. @ComponentScan, equivalent to xml's <context:componentScan basepackage=>;
  3. @Bean, equivalent to xml's <bean id="student" class="com.guor.entity">;
  4. @EnableWebMvc, equivalent to xml's <mvc:annotation-driven>;
  5. @ImportResource, equivalent to <import resource="application-context-cache.xml"> of xml;
  6. @PropertySource, used to read the properties configuration file;
  7. @Profile, generally used for multi-environment configuration, can be annotated with @ActiveProfile("dev") when activated;

7. What is the ORM framework?

ORM (Object-relational mapping), object-relational mapping.

It is to solve the problem of mismatch between object-oriented and relational databases.

Advantages of ORM framework:

  1. Higher development efficiency
  2. Data access is more abstract and portable
  3. Support object-oriented packaging

8. How many configuration methods does Spring have?

1. xml configuration file

<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans"       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"       xsi:schemaLocation="http://www.springframework.org/schema/beans    http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">     <bean id="jackma" class="com.tyq.dto.User">        <property name="name" value="jackma" />        <property name="age" value="55" />        <property name="dog" ref="jm" />     </bean>     <bean id="jm" class="com.tyq.dto.Dog">        <property name="name" value="jack" />        <property name="breed" value="金毛" />        <property name="age" value="2" />    </bean></beans>

2. Annotation-based approach

Projects are getting bigger and bigger, and xml-based configuration is too troublesome. Spring 2.x era provides annotations for declaring beans.

(1) Definition of Bean

@Component, @Controller, @Service, @Repository.

(2) Bean injection

@Autowire

3. Java-based approach

After Spring 3.x, Bean can be assembled through Java code.

@Configurationpublic class DemoConfig {    @Bean    public User jackma(){        return new User();    }    @Bean    public Dog dog(){        return  new Dog();    }    @Bean  //两个狗    public Dog haqi(){        return new Dog();    }}
@Component("jackma")public class User {    private String name;    private int age;    private Dog dog;   //get,set方法略}

It turned out to be the configuration class. Bean registration and discovery are carried out through @Bean, @Component, and getBean methods.

9. Please explain the life cycle of Spring Bean?

  1. Create bean instance through constructor or factory method;
  2. Assign values ​​to bean properties;
  3. Call the bean's initialization method;
  4. Use bean;
  5. When the container is closed, call the destruction method of the bean;

10. What is the difference between the scope of Spring Bean?

The beans in the Spring container can be divided into 5 ranges:

  1. Singleton: This bean scope is the default. This scope ensures that no matter how many requests are accepted, there is only one bean instance in each container, singleton mode;
  2. Prototype: Provide an instance for each bean;
  3. request: Create an instance for each network request from the client within the scope of the request bean. After the request is completed, the bean will be invalidated and recycled by the garbage collector;
  4. session: create an instance for each session, the bean will disappear after the session expires;
  5. global-session: global-session is related to portlet applications. When your application is deployed to work in a portlet container, it contains many portlets. If you want to declare global storage variables that are shared by all portlets, then global variables need to be stored in global-session.

11. How to disable Actuator endpoint security in Spring Boot?

By default, all sensitive HTTP endpoints are secure, and only users with the Actuator role can access them. Security is implemented using the standard HTTPServletRequest.isUserInRole method. We can use management.security.enable = false to disable security. It is only recommended to disable security when the actuator endpoint is accessed behind a firewall.

12. What is Spring inner beans?

In the Spring framework, whenever a bean is used, only one property is called. This bean can be declared as an inner bean. Inner beans can be implemented in the form of setter injection "property" and construction method injection "construction parameters". For example, in our application, a Customer class references a Person class. What we need to do is to create a Person instance and then use it internally in Customer.

package com; public class Customer {    private Person person;} class Person{    private int id;    private String name;    private int age;}
<bean id="CustomerBean" class="com.Customer">	<property name="person">		<bean class="com.person">			<property name="id" value=1 />			<property name="name" value="素小暖" />			<property name="age" value=18 />		</bean>	</property></bean>

13. Are singleton beans in the Spring framework thread-safe?

The Spring framework does not perform any multi-threaded encapsulation of singleton beans. The thread safety and concurrency issues of singleton beans need to be solved by the developer. But in fact, most Spring beans have no mutable state, so to some extent, Spring's singleton beans are thread-safe. If your bean has multiple states, such as a view model, you need to ensure thread safety by yourself.

The most obvious solution is to change the scope of polymorphic beans from singleton to prototype.

14. Please explain the automatic assembly of Spring Bean?

Spring supports IOC, automatic assembly does not need to be instantiated, and is directly taken from the bean container.

1. Configured in xml

<bean id="employeeDAO" class="com.guor.EmployeeDAOImpl" autowire="byName" />
2. @Autowired automatic assembly

15. How to turn on automatic assembly based on annotations?

To use it  @Autowired, you need to register  AutowiredAnnotationBeanPostProcessor, which can be achieved in the following two ways:

Import the <bean>next import  in the configuration file<context:annotation-config>

<beans>    <context:annotation-config /></beans>

Introduce directly in the bean configuration fileAutowiredAnnotationBeanPostProcessor

<beans>    <bean class="org.springframework.beans.factory.annotation.AutowiredAnnotationBeanPostProcessor"/></beans>

16. What is Spring Batch?

1. What is spring batch?

Spring batch is a lightweight and complete batch processing framework. Its main purpose is to help enterprises build robust and efficient batch processing applications.

Spring batch is a sub-project of Spring. It uses the Java language and is developed based on the spring framework, making it easier for developers or enterprises who have already used the Spring framework to access and utilize enterprise services.

Spring batch provides a large number of reusable components, including logs, tracking, transactions, task job statistics, task restart, skip, repetition, and resource management.

For batch processing tasks with large data volume and high performance, spring batch also provides advanced functions and features to support.

For example: partition function, remote function.

In general, spring batch can support simple, complex and large data batch processing jobs.

2. Spring batch business scenario

Periodic batch submission

Parallel processing of a task

Message-driven application hierarchical processing

Massively parallel batch processing

Restart after the task fails manually or by scheduling

Sequential execution with dependent steps (using workflow-driven extension)

Skip some records during processing

Batch transaction: used for small batch or some stored procedure/script scenarios

17. What is the difference between spring mvc and struts?

1. The difference in interception mechanism

Struts2 is a class-level interception. Each request will create an Action. When integrating with Spring, the scope of the ActionBean injection of Struts2 is the prototype model, and then the request data is injected into the attribute through the setter and getter. In Struts2, an Action corresponds to a request and response context. When receiving parameters, it can be received through attributes, which means that attribute parameters are shared by multiple methods. A method of Action in Struts2 can correspond to a url, but its class attribute is shared by all methods, so it is impossible to use annotations or other ways to identify its own method, and it can only be designed as multiple cases.

Spring MVC is a method-level interception. A method corresponds to a Request context, so the method is basically independent and has exclusive request and response data. And each method corresponds to a URL at the same time, and the parameter transmission is directly injected into the method, which is unique to the method. The processing result is returned to the framework through ModeMap. During Spring integration, SpringMVC's Controller Bean defaults to Singleton, so by default, only one Controller will be created for all requests. There should be no shared attributes, so it is thread-safe. If you want to change the default scope, Need to add @Scope annotation modification.

Struts2 has its own interception Interceptor mechanism, SpringMVC uses an independent Aop method, which leads to Struts2's configuration file volume is still larger than SpringMVC.

2. The difference in the underlying framework

Struts2 is implemented using Filter (StrutsPrepareAndExecuteFilter), and SpringMVC (DispatcherServlet) is implemented using Servlet. Filter is initialized after the container starts; it crashes after the service stops, later than Servlet. Servlet is initialized when it is called, before Filter is called, and destroyed after the service stops.

3. Performance

Struts2 is a class-level interception. Each time a request corresponds to a new Action instance, all attribute value injections need to be loaded. SpringMVC implements zero configuration. Because SpringMVC is based on method interception, there is a singleton bean injection that is loaded once. Therefore, SpringMVC development efficiency and performance are higher than Struts2.

4. Configuration

Spring MVC and Spring are seamless. The management and safety of this project is also higher than Struts2.

18. Please give an example to explain the @Required annotation?

The @Required annotation is applied to the setter method of the bean property, which indicates that the affected bean property must be placed in the XML configuration file during configuration.

19. Please give an example to illustrate the @Qualifier annotation?

If you define multiple beans of one type in xml, and you want to use one of the bean objects as attributes in the java annotations, then you can use @Qualifier plus @Autowired to achieve this purpose, if you don’t add @Qualifier For this annotation, the exception "No qualifying bean of type [com.tutorialspoint.Student] is defined: expected single matching bean but found 2: student1, student2" will appear at runtime.

Twenty, Spring common annotations

Spring common annotations (absolutely classic)

21. How to implement permission verification in the project? Several tables are needed for permission verification

Through understanding, the most common right management model is RBAC (Role-Based Access Control).

1. Access control classification

  1. Menu function
  2. url control (control access to different controllers)

2. The advantages and disadvantages of RBAC

(1) Advantages

Simplifies the relationship between users and permissions,
easy to expand and easy to maintain

(2) Disadvantages

The RBAC model does not provide a control mechanism for the operation sequence. This defect makes it difficult for the RBAC model to adapt to systems that have strict requirements for the operation sequence.

3. Security principles supported by RBAC

(1) The principle of least privilege

RBAC can configure the role to the minimum set of permissions required to complete the task.

(2) The principle of separation of responsibilities

You can complete sensitive tasks together by invoking mutually independent and mutually exclusive roles, such as requiring a bookkeeper and financial administrator to participate in unified posting operations.

(3) The principle of data abstraction

It can be embodied by the abstraction of permissions, for example, financial operations use abstract permissions such as borrowing and depositing, instead of using typical read and write permissions.

4. Permission control in ancient times

At that time, there was no RBAC, and there was no such concept. It was just a bunch of programmers who were tinkering with each other about what they should do when logging in.

1. Create a new user and grant permissions to this user.
2. But once there are more users and the permissions become complicated, the workload is quite large.

5. RBAC

RBAC 1.0

Directly on the picture above, it is clear at a glance, when the program is not very complicated, RBAC is designed like this, and our company's authorization verification module is designed like this.

Simple, five tables, solve.

RBAC 2.0

Based on the RBAC 1.0 model, access control of roles is carried out

One of the basic restrictions in RBAC2 is the restriction of mutually exclusive roles. Mutually exclusive roles refer to two roles whose respective permissions can restrict each other. For this type of role, a user can only be assigned to one role in a certain activity, and cannot obtain the right to use two roles at the same time.

The model has the following constraints

  • Mutually exclusive roles: The same user can only be assigned to at most one role in a set of mutually exclusive roles, supporting the principle of separation of responsibilities. Mutually exclusive roles refer to two roles whose respective permissions restrict each other. For this type of role, a user can only be assigned to one role in a certain activity, and cannot obtain the right to use two roles at the same time. A common example: in audit activities, a role cannot be assigned to the accountant role and the auditor role at the same time.
  • Cardinality constraints: the number of users assigned to a role is limited; the number of roles a user can have is limited; the number of access permissions corresponding to the same role should also be limited to control the allocation of advanced permissions in the system. For example, the leader of the company is limited;
  • Prerequisite role: You can assign a role to a user only if the user is already a member of another role; correspondingly, you can assign access rights to a role, only if the role already has another type of access rights. It means that if you want to obtain a higher level of authority, you must first have a lower level of authority. Just like in our lives, the president of the country is elected from among the vice-presidents.
  • Mutual exclusion at runtime: For example, a user is allowed to have membership in two roles, but the two roles cannot be activated at the same time during runtime.

6. Theoretical analysis of the realization of rbac

Enter the login page;
get the user name and password passed through the post;
use orm to filter and search;
if the value can be found, the login is successful: after the login is successful, the rbac initialization function is called. The main function of the initialization function is to obtain the user's authority and The menu is saved in the session, and the customer list page is redirected; if it fails, the page will give a friendly prompt;

7, the key code of url permission control

Twenty-two, talk about the controller, the path problem of the interface call

1. How does Spring MVC match the request path?

@RequestMapping is used to map requests, such as get requests, post requests, or REST style and non-REST style. This annotation can be used on a class or method. If it is used on a class, it means that it is the parent path of all methods in the class.

@RequestMapping("/springmvc")@Controllerpublic class SpringMVCTest {    @RequestMapping("/testRequestMapping")    public String testRequestMapping(){        System.out.println("testRequestMapping");        return SUCCESS;    }}

A @Controller annotation is also added to the class. The annotation is responsible for processing the request distributed by the DispatcherServlet in SpringMVC. It encapsulates the data requested by the user into a model after being processed by the business processing layer, and then returns the model to the corresponding view for display.

We can locate the testRequestMapping method through the "springmvc/testRequestMapping" path, and then execute the method body in the method.

RequestMapping can implement fuzzy matching paths, such as:

  • ? Represents a character;
  • * Means any character;
  • **Match multi-layer paths;

/springmvc/**/testRequestMapping can match paths like /springmvc/stu/getStudentInfo/testRequestMapping.

2. How does SpringMVC get the requested parameters

(1) @PathVariable

This annotation is used to map the placeholder bound in the request URL. @PathVariable can bind the placeholder parameters in the URL to the input parameters of the controller processing method.

@RequestMapping("/testPathVariable/{id}")public String testPathVariable(@PathVariable(value="id") Integer id){    System.out.println("testPathVariable:" + id);    return SUCCESS;}

In index.jsp we add a connection to trigger a request:

<a href="springmvc/testPathVariable/1">testPathVariable</a>

(2) @RequestParam

This annotation is also used to obtain request parameters, so what is the difference between this annotation and @PathVariable?

@RequestMapping(value="/testRequestParam")public String testRequestParam(@RequestParam(value="username") String username, @RequestParam(value="age", required=false, defaultValue="0") int age){    System.out.println("testRequestParam" + " username:" + username + " age:" +age);    return SUCCESS;}

Add a hyperlink tag in index.jsp

<a href="springmvc/testRequestParam?username=jackie&age=12">testRequestParam</a>

3. REST style request

CRUD should be the most business in SpringMVC

@RequestMapping(value="/testRest/{id}", method=RequestMethod.PUT)public String testRestPut(@PathVariable(value="id") Integer id){    System.out.println("test put:" + id);    return SUCCESS;}     @RequestMapping(value="/testRest/{id}", method=RequestMethod.DELETE)public String testRestDelete(@PathVariable(value="id") Integer id){    System.out.println("test delete:" + id);    return SUCCESS;}     @RequestMapping(value="/testRest", method=RequestMethod.POST)public String testRest(){    System.out.println("test post");    return SUCCESS;}     @RequestMapping(value="/testRest/{id}", method=RequestMethod.GET)public String testRest(@PathVariable(value="id") Integer id){    System.out.println("test get:" + id);    return SUCCESS;}

Twenty-three, how to prevent repeated submission of forms

1. Block the submit button via JavaScript (not recommended)

2. Add a unique key constraint to the database (simple and crude)

3. Use Session to prevent repeated submission of forms (recommended)

4. Use AOP to customize the cut-in implementation

Twenty-four, what design patterns are applied in Spring

1. Simple factory model

The essence of the simple factory pattern is that a factory class dynamically decides which class to instantiate based on the parameters passed in.

The BeanFactory in Spring is the embodiment of the simple factory model, which obtains the bean object according to a unique identifier passed in.

2. Factory method pattern

The application delegates the creation and initialization responsibilities of the object to the factory object, the factory bean.

Define the factory method, and then incorporate it into the Spring container to manage it through the config.xml configuration file. You need to specify the static method name through the factory-method.

3. Singleton mode

Spring uses the singleton mode of double judgment and locking, and obtains beans from singletonObjects through the getSingleton method.

     /**     * Return the (raw) singleton object registered under the given name.     * <p>Checks already instantiated singletons and also allows for an early     * reference to a currently created singleton (resolving a circular reference).     * @param beanName the name of the bean to look for     * @param allowEarlyReference whether early references should be created or not     * @return the registered singleton object, or {@code null} if none found     */    protected Object getSingleton(String beanName, boolean allowEarlyReference) {        Object singletonObject = this.singletonObjects.get(beanName);        if (singletonObject == null && isSingletonCurrentlyInCreation(beanName)) {            synchronized (this.singletonObjects) {                singletonObject = this.earlySingletonObjects.get(beanName);                if (singletonObject == null && allowEarlyReference) {                    ObjectFactory<?> singletonFactory = this.singletonFactories.get(beanName);                    if (singletonFactory != null) {                        singletonObject = singletonFactory.getObject();                        this.earlySingletonObjects.put(beanName, singletonObject);                        this.singletonFactories.remove(beanName);                    }                }            }        }        return (singletonObject != NULL_OBJECT ? singletonObject : null);    }

4. Agency mode

In Spring's AOP, Advice is used to enhance the function of the proxied class. The principle of Spring's realization of the AOP function is the proxy mode (① JDK dynamic proxy, ② CGLIB bytecode generation technology proxy.) The method-level aspect enhancement of the class.

5. Decorator mode

Decorator mode: dynamically add some extra features to an object.

Configure all DataSources in Spring's ApplicationContext. These DataSources may be different databases, and SessionFactory sets the DataSource to different data sources according to each request of the user to achieve the purpose of switching data sources.

There are two manifestations in Spring:

One is that the class name contains Wrapper, and the other is that the class name contains Decorator.

6. Observer mode

Define a one-to-many relationship between objects. When the state of an object changes, all objects that depend on it are notified and automatically updated.

The observer pattern in Spring is generally used in the implementation of the listener.

7. Strategy mode

The strategy mode is a behavioral mode, calling different methods, adapting to changes in behavior, and emphasizing the characteristics of calling subclasses of the parent class.

getHandler is the only method in the HandlerMapping interface, which is used to find a matching handler based on the request.

8. Template method mode

The overall structure of the query method of Spring JdbcTemplate is a template method + callback function. The execute() called in the query method is a template method, and the expected callback doInStatement(Statement state) method is also a template method.

25. Please give an example of how to inject a Java Collection in Spring?

There are four ways of Spring injection,

  1. set injection;
  2. Constructor injection;
  3. Annotation-based injection;
  4. xml configuration file injection;

To inject a java collection, it is to inject a collection class:

  1. list
  2. set
  3. map
  4. props: This tag supports the injection of key-value pairs whose keys and values ​​are both string types.

Both list and set use value tags; map uses entry tags; props uses prop tags;

Chapter 8 mybatis

1. What is the difference between #{} and ${} in mybatis?

  1. #{}With quotation marks, ${} without quotation marks;
  2. #{} can prevent SQL injection;
  3. ${} is often used in database table names and order by clauses;
  4. Generally you can use #{} instead of ${};

2. Does mybatis support lazy loading? What is the principle of lazy loading?

1. Does mybatis support lazy loading?

Lazy loading actually means delaying the timing of data loading, such as delaying the timing of nested queries.

Lazy loading can query the main table first, do the related query in real time as needed, and return the result set of the related table, which improves efficiency to a certain extent.

Mybatis only supports the lazy loading of association object association and collection object collection. Association is one-to-one, and collection is one-to-many query. You can configure lazyloadingEnable=true/false in the mybatis configuration file.

2. What is the principle of lazy loading?

Use CGLIB to establish a proxy object for the target object, and enter the interceptor method when the method of the target object is called.

For example, when a.getB().getName() is called, the interceptor method invoke() finds that a.getB() is null, it will separately send the prepared SQL statement to query the associated B object, query B and then call a. setB(b), the property b of the object of a has a value, and then getName() is called. This is the principle of lazy loading.

3. Talk about the first level cache and the second level cache of mybatis?

The first-level cache is a session-level cache, which is enabled by default. When querying the database once, the query result is cached. If the subsequent query exists in the first-level cache, there is no need to access the database;

The second-level cache is a sessionFactory level cache and needs to be configured to enable it. When querying SQL statements, first check the first-level cache, if it does not exist, access the second-level cache to reduce database access pressure.

4. What executors does mybatis have?

1. Mybatis has three basic Executor executors:

(1), SimpleExecutor

Every time an update or select is executed, a Statement object is opened, and the Statement object is closed immediately when it is used up.

(2) PauseExecutor

Execute update or select, use sql as the key to find the Statement object, use it if it exists, create it if it does not exist, and do not close the Statement object after using it, and place it in the Map for the next use. In short, the Statement object is reused.

(3) BatchExecutor

Execute update, add all sql to the batch through addBatch(), and wait for executeBatch() to be executed uniformly. It caches multiple Statement objects, and each Statement object is after addBatch() is completed, waiting to execute executeBatch() one by one. Batch processing. Same as JDBC batch processing.

2. Scope of action:

These characteristics of Executor are strictly limited to the scope of the SqlSession life cycle.

3. How to specify which type of Executor to use in Mybatis?

In the configuration file of mybatis, you can specify the default ExecutorType actuator type, or you can manually pass the ExecutorType type parameter to the method of creating SqlSession of DefaultSqlSessionFactory.

5. What are the differences between mybatis and hibernate?

1. The biggest difference between the two

For simple logic, there are corresponding code generation tools, which can generate simple and basic dao layer methods;

For advanced queries, mybatis needs to manually write SQL statements and resultMap, while hibernate has a good mapping mechanism;

2. Comparison of development difficulty

hibernate> mybatis

3. Log statistics

Hibernate has its own log statistics function, and mybatis needs to use log4j to record logs.

4. Database expansion comparison

hibernate> mybatis

5. Comparison of caching mechanism

Because hibernate has a good management mechanism for query objects, users do not need to care about sql, so if dirty data appears in the second-level cache, the system will report an error.

And mybatis, if you can't get the latest data, you should avoid the use of cache, the appearance of dirty data will bring great hidden dangers to the normal operation of the system.

6. How to choose

  1. Mybatis needs to write SQL and mapping rules, the workload is greater than hibernate;
  2. The tools supported by mybatis are also limited, and there are not many plug-ins like hibernate that can help generate mapping code and association relationships;
  3. For systems with less stringent performance requirements, such as management systems, ERP, etc., hibernate is recommended;
  4. For systems with high performance requirements, fast response, and flexibility, such as e-commerce systems, mybatis is recommended;

Six, myBatis query multiple id, common attributes of myBatis

myBatis queries multiple IDs (I actually answered using objects to pass...)

Page<UserPoJo>  getUserListByIds(@Param("ids") List<Integer> ids);
<!--根据id列表批量查询user--><select id="getUserListByIds" resultType="com.guor.UserPoJo">    select * from student    where id in    <foreach collection="ids" item="userid" open="(" close=")" separator=",">        #{userid}    </foreach></select>

Seven, mybatis first level cache, second level cache

1. The first level cache: refers to the cache of the sqlSession object in mybatis. When we execute the query, the result of the query will be stored in the sqlSession at the same time. When querying again, first go to the sqlSession to query, and if some, take it out directly. When the sqlSession disappears, the first level cache of mybatis also disappears. When the modify, add, delete, commit(), close() and other methods of sqlSession are called, the first level cache will be cleared.

2. The second level cache: refers to the cache of the sqlSessionFactory object in mybatis. The sqlSession created by the same sqlSessionFactory object shares its cache, but the cache is data instead of objects. When it hits the secondary cache, the stored data is constructed into an object to return. When querying data, the query process is Level 2 Cache> Level 1 Cache> Database.

3. If the second-level cache is enabled, the data in the first-level cache of sqlSession will be added to the second-level cache after sqlSession performs close(). In order to remove the cached data for deserialization, the pojo to be cached needs to be implemented. Serializable interface, because the secondary cache data storage medium is diverse, it may not only exist in the memory, but may also exist in the hard disk.

4. The mybatis framework is mainly carried out around sqlSessionFactory, and the specific steps are as follows:

  1. Define a configuration object, which contains data sources, transactions, mapper file resources, and settings that affect database behavior.
  2. By configuring the object, you can create a sqlSessionFactoryBuilder object.
  3. Obtain an instance of sqlSessionFactory through sqlSessionFactoryBuilder.
  4. Create a qlSession instance through the sqlSessionFactory instance, and operate the database through sqlSession.

5. Code example

mybatis-config.xml

<?xml version="1.0" encoding="UTF-8"?>  <!DOCTYPE configuration PUBLIC "-//mybatis.org//DTD Config 3.0//EN"  "http://mybatis.org/dtd/mybatis-3-config.dtd">   <configuration>       <!-- 加载类路径下的属性文件 -->      <properties resource="db.properties"/>       <!-- 设置类型别名 -->      <typeAliases>          <typeAlias type="cn.itcast.javaee.mybatis.app04.Student" alias="student"/>      </typeAliases>       <!-- 设置一个默认的连接环境信息 -->      <environments default="mysql_developer">           <!-- 连接环境信息,取一个任意唯一的名字 -->          <environment id="mysql_developer">              <!-- mybatis使用jdbc事务管理方式 -->              <transactionManager type="jdbc"/>              <!-- mybatis使用连接池方式来获取连接 -->              <dataSource type="pooled">                  <!-- 配置与数据库交互的4个必要属性 -->                  <property name="driver" value="${mysql.driver}"/>                  <property name="url" value="${mysql.url}"/>                  <property name="username" value="${mysql.username}"/>                  <property name="password" value="${mysql.password}"/>              </dataSource>          </environment>           <!-- 连接环境信息,取一个任意唯一的名字 -->          <environment id="oracle_developer">              <!-- mybatis使用jdbc事务管理方式 -->              <transactionManager type="jdbc"/>              <!-- mybatis使用连接池方式来获取连接 -->              <dataSource type="pooled">                  <!-- 配置与数据库交互的4个必要属性 -->                  <property name="driver" value="${oracle.driver}"/>                  <property name="url" value="${oracle.url}"/>                  <property name="username" value="${oracle.username}"/>                  <property name="password" value="${oracle.password}"/>              </dataSource>          </environment>      </environments>       <!-- 加载映射文件-->      <mappers>          <mapper resource="cn/itcast/javaee/mybatis/app14/StudentMapper.xml"/>      </mappers>   </configuration>  
public class MyBatisTest {     public static void main(String[] args) {        try {            //读取mybatis-config.xml文件            InputStream resourceAsStream = Resources.getResourceAsStream("mybatis-config.xml");            //初始化mybatis,创建SqlSessionFactory类的实例            SqlSessionFactory sqlSessionFactory =  new SqlSessionFactoryBuilder().build(resourceAsStream);            //创建session实例            SqlSession session = sqlSessionFactory.openSession();            /*             * 接下来在这里做很多事情,到目前为止,目的已经达到得到了SqlSession对象.通过调用SqlSession里面的方法,             * 可以测试MyBatis和Dao层接口方法之间的正确性,当然也可以做别的很多事情,在这里就不列举了             */            //插入数据            User user = new User();            user.setC_password("123");            user.setC_username("123");            user.setC_salt("123");            //第一个参数为方法的完全限定名:位置信息+映射文件当中的id            session.insert("com.cn.dao.UserMapping.insertUserInformation", user);            //提交事务            session.commit();            //关闭session            session.close();        } catch (IOException e) {            e.printStackTrace();        }    }}

Eight, how does mybatis prevent sql injection

Note: Any program with SQL injection vulnerability is because the program accepts variables or parameters passed by the URL from the client user, and this variable or parameter is a part of the SQL statement, for the content entered by the user or the parameters passed , We should always be vigilant. This is the principle of [external data cannot be trusted] in the security field. Looking at the various attack methods in the web security field, most of them are caused by developers violating this principle, so Naturally, it can be imagined that the detection, filtering, and verification of variables are started to ensure that the variables are what the developers expected.

1. Check the variable data type and format

Data type check, before sql is executed, the data type must be checked. If it is a mailbox, the parameter must be in the format of the mailbox, if it is a date, it must be in the date format;

As long as there are variables with a fixed format, before the SQL statement is executed, it should be checked strictly in accordance with the fixed format to ensure that the variable is in the format we expected, which can largely avoid SQL injection attacks.

If the id in the above example is of type int, what will be the effect? Unable to inject, because input injection parameters will fail. For example, in the name field above, we should determine a user name rule when users register, such as 5-20 characters, which can only consist of uppercase and lowercase letters, numbers, and Chinese characters, and do not contain special characters. At this point we should have a function to complete the unified user name check. However, there are still many scenarios where this method cannot be used, such as blogging, commenting systems, and barrage systems. Users must be allowed to submit any form of characters, otherwise the user experience will be too bad.

2. Filter special symbols

3. Bind variables and use prepared statements

Chapter 9 hibernate

1. Why use hibernate?

  1. Hibernate encapsulates jdbc, which simplifies the repetitive code of JDBC;
  2. Hibernate has a encapsulation class hibernateTemplate for dao, which can be inherited to implement a simple CRUD interface.
  3. Hibernate uses annotations and configuration files to map entity classes and mapping files;
  4. Hibernate has a transaction management mechanism to ensure data security;
  5. Hibernate has a first-level cache and a second-level cache;

2. How to view the printed sql statement in the console in hibernate?

spring.jpa.properties.hibernate.show_sql=truespring.jpa.properties.hibernate.format_sql=truespring.jpa.properties.hibernate.use_sql_comments=true

3. How many query methods does hibernate have?

1. Navigation object map query: navigate to other objects based on the loaded objects.

For example, for a Customer object that has been loaded, calling its getOrders().iterator() method can navigate to all associated Order objects. If a lazy loading retrieval strategy is used at the association level, then when this method is executed for the first time, hibernate will Load the associated Order object from the database, otherwise get the Order object from the cache.

2. OID method: Retrieve the object according to the OID of the object

Session's get() and load() methods provide this function. If you know the OID in the application, you can use this method to retrieve the object.

The usage of get() and load() is exactly the same, both require two parameters, one is the persistent object class name class, the other is the row number OID, which returns a fixed row of data, but it should be noted that when the input When the OID does not exist, get() will return an empty object, and load() will directly report an error.

3. HQL retrieval method: (hibernate query language)

Using the object-oriented HQL query language, the find() method of the session is used to execute HQL query statements. In addition, hibernate also provides the query interface, which is a special HQL query interface provided by hibernate, which can execute various complex HQL query statements.

It has the following functions:

  1. Set various query conditions in the query statement;
  2. Support projection query, that is, only some attributes of the object can be retrieved;
  3. Support paging query;
  4. Support connection query;
  5. Support group query;
  6. Provide built-in functions;
  7. Ability to call user-defined SQL functions;
  8. Support sub-queries;
  9. Support dynamic binding parameters;

E.g:

Query query = session.createQuery(“from UserPo”);

Obtain a query object, note that the parameter string is not a SQL statement, and the name of the persistent object is behind from;

List list = query.list();

You can get the data collection of the corresponding table in the database.

4. QBC retrieval method: Query By Criteria API to retrieve objects

This API encapsulates query statements based on string format and provides a more object-oriented interface.

例:Criteria criteria = session.createCriteria(UserPo.class);

Create a Criteria object, the parameter is the associated persistent object, criteria.add(Restrictions.ge("id",2)); add the query condition to the object, and the subsequent operations are the same as the Query object.

5. Local SQL

Using the SQL query statement of the local database, hibernate will be responsible for mapping the retrieved JDBC ResultSet result into a persistent object graph.

4. Can hibernate entity classes be defined as final?

The entity class of hibernate can be defined as final, but this approach is not good.

Because hibernate will use the proxy mode to improve performance in the case of delayed association, if you define the entity class as a final class, because Java does not allow the final class to be extended, hibernate can no longer use the proxy, so it will limit The use of methods that can improve performance.

However, if your persistent class implements an interface, and all public methods defined in the entity class are declared in the interface, you can avoid the adverse consequences mentioned earlier.

5. What is the difference between using Integer and int for mapping in hibernate?

Hibernate is an object-oriented ORM, so it is generally defined as an encapsulation type. It depends on the definition in the database. If there is a null value in the corresponding field in the database, Integer must be defined. You can also define the basic types and write them clearly in the configuration file.

Chapter 10 Spring Boot

1. What is Spring Boot? What are the advantages of Spring Boot?

1. Introduction to Spring Boot

Based on the Spring 4.0 design, it not only inherits the original excellent features of the Spring framework, but also further simplifies the entire construction and development process of spring applications by simplifying the configuration. In addition, SpringBoot resolves version conflicts and instability of dependent packages by integrating a large number of frameworks.

2. What are the advantages of Spring Boot?

  1. Quickly build the project, you can select some necessary components;
  2. Configuration-free integration of mainstream frameworks;
  3. Embedded Tomcat container, the project can run independently;
  4. Delete the cumbersome xml configuration file;
  5. Greatly improve the efficiency of development and deployment;
  6. Provide starter to simplify maven configuration;

3. What are the disadvantages of SpringBoot?

  1. The version iteration is fast, and some modules have changed a lot;
  2. Since no configuration is required, it is difficult to locate when an error is reported;

2. What is the monitor in Spring Boot?

The listener, also called listener, is a servlet listener, which can be used to monitor the creation, destruction, addition, modification, and deletion of certain objects in the web application, and then make the corresponding response processing. When the state of the scope object changes, the server automatically calls the method in the listener object, which is often used to initialize information when the system is loaded, count the number of online users and online users, and count the number of website visits.

How to configure the listener:

Add the listener to the Spring container management through @Component;
add context.listener.classes configuration in application.properties;
add @EventListener annotation to the method;

3. What is YAML?

YAML is a superset of JSON, which can easily store external configuration in a hierarchical structure. YAML can be used as an alternative to the properties configuration file.

Precautions for the use of YAML:

  1. In the properties file, it is divided by ".", and in yml, it is divided by ".";
  2. The data format of yml is very similar to the format of json, both are in KV format, and the value is assigned through ":";
  3. Be sure to add a space after each colon;

4. How to use Spring Boot to implement paging and sorting?

The use of Spring Data Jpa can be achieved to pass the pageable to the repository method.

5. How to use Spring Boot to implement exception handling?

1. Use @ExceptionHandler annotation to handle local exceptions (only ArithmeticException and NullPointerException exceptions in the current controller can be processed, the disadvantage is that it can only handle exceptions from a single controller)

@Controllerpublic class ExceptionHandlerController {		@RequestMapping("/excep")	public String exceptionMethod(Model model) throws Exception {		String a=null;		System.out.println(a.charAt(1));		int num = 1/0;		model.addAttribute("message", "没有抛出异常");		return "index";	} 	@ExceptionHandler(value = {ArithmeticException.class,NullPointerException.class})	public String arithmeticExceptionHandle(Model model, Exception e) {		model.addAttribute("message", "@ExceptionHandler" + e.getMessage());		return "index";	}}

2. Use @ControllerAdvice + @ExceptionHandler annotations to handle global exceptions (the array can be filled in after the value)

@ControllerAdvicepublic class ControllerAdviceException {		@ExceptionHandler(value = {NullPointerException.class})	public String NullPointerExceptionHandler(Model model, Exception e) {		model.addAttribute("message", "@ControllerAdvice + @ExceptionHandler :" + e.getMessage());		return "index";	}}

3. Configure the SimpleMappingExceptionResolver class to handle exceptions (configuration class)

@Configurationpublic class SimpleMappingException {	@Bean	public SimpleMappingExceptionResolver getSimpleMappingExceptionResolver(){ 		SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();		Properties mappings = new Properties();		//第一个参数为异常全限定名,第二个为跳转视图名称		mappings.put("java.lang.NullPointerException", "index");		mappings.put("java.lang.ArithmeticException", "index");		//设置异常与视图映射信息的		resolver.setExceptionMappings(mappings);		return resolver;	}}

4. Implement the HandlerExceptionResolver interface to handle exceptions

@Configurationpublic class HandlerException implements HandlerExceptionResolver {	@Override	public ModelAndView resolveException(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) { 		ModelAndView modelAndView = new ModelAndView();		modelAndView.addObject("message", "实现HandlerExceptionResolver接口"); 		//判断不同异常类型,做不同视图跳转		if(ex instanceof NullPointerException){			modelAndView.setViewName("index");		}		if(ex instanceof ArithmeticException){			modelAndView.setViewName("index");		}		return modelAndView;	}}

Five, single sign-on

1. Concept

Single sign-on SSO means that in an environment where multiple systems coexist, a user does not need to log in to other systems after logging in at one place, that is, a user's login can be trusted by all other systems.

2. The main points of single sign-on

  1. Store trust
  2. Verify trust;

3. Three ways to achieve single sign-on

(1) Use cookies as credentials

The simplest way to implement single sign-on is to use cookies as a medium to store user credentials.

After the user logs in to the parent application, the application returns an encrypted cookie. When the user accesses the child application, the cookie is carried, and the application is authorized to decrypt the cookie for verification. If the verification is passed, the current user is logged in.

Disadvantages:

cookie is not secure

Security can be guaranteed through encryption, but if the other party masters the decryption algorithm, it will be over.

Cannot implement non-logging across domains

(2) Realized through JSONP

For cross-domain issues, you can use JSONP to achieve. After the user logs in in the parent application, the cookie that matches the session will be stored in the client. When the user needs to log in to the child application, authorize the application to access the JSONP interface provided by the parent application, and include the parent application domain name in the request Cookie, the parent application receives the request, verifies the user's login status, and returns encrypted information. The child application verifies the user by parsing the returned encrypted information, and logs in the user if it passes the verification.

Disadvantages:

Although this method can solve the cross-domain problem, it does not solve the problem of cookie security.

(3) By way of page redirection

最后一种介绍的方式,是通过父应用和子应用来回重定向进行通信,实现信息的安全传递。

父应用提供一个GET方式的登录接口A(此时的父应用接口固定,攻击者无法去伪造),用户通过子应用重定向连接的方式访问这个接口,如果用户还没有登录,则返回一个登录页面,用户输入账号密码进行登录,如果用户已经登录了,则生成加密的token,并且重定向到子应用提供的验证token的接口B(此时的子应用接口固定,攻击者无法去伪造),通过解密和校验之后,子应用登录当前用户。

缺点:

这种方式较前面的两种方式,是解决了安全性和跨域的问题,但是并没有前面两种方式简单,安全与方便,本来就是矛盾的。

4、使用独立登录系统

一般来说,大型应用会把授权的逻辑和用户信息的相关逻辑独立成一个应用,称为用户中心。用户中心不处理业务逻辑,只是处理用户信息的管理以及授权给第三方应用。第三方应用需要登录的时候,则把用户的登录请求转发给用户中心进行处理,用户处理完毕后返回凭证,第三方应用验证凭证,通过后就登录用户。

5、sso(单点登录)与OAuth2.0(授权)的区别?

(1)sso(单点登录)

  • 通常处理的是一个公司的不同应用间的访问登录问题,如企业应用有很多子系统,只需登录一个系统,就可以实现不同子系统间的跳转,而避免了登录操作;
  • 通过cookie、jsonp、重定向来实现;

(2)OAuth2.0(授权)

  • 解决的是服务提供方(如微信)给第三方应用授权的问题,简称微信登录;
  • 是一种具体的协议,只是为用户资源的授权提供了一个安全的、开放的而又简易的标准,OAuth2.0(授权)为客户开发者开发web应用,桌面应用程序,移动应用及客厅设备提供特定的授权流程。

六、Spring Boot比Spring多哪些注解

Spring Boot常用注解(绝对经典)

七、打包和部署

Spring和Spring Boot都支持maven和Gradle通用打包管理技术。

Spring Boot相对Spring的一些优点:

  • 提供嵌入式容器支持;
  • 使用命令java -jar独立运行jar;
  • 部署时可以灵活指定配置文件;

最近项目是分布式的项目,都是通过分项目打包部署,然后部署在docker中运行。

八、Spring Boot如何访问不同的数据库

可以使用druidDataSource创建DataSource,然后通过jdbcTemplate执行sql。

九、查询网站在线人数

通过监听session对象的方式来实现在线人数的统计和在线人信息展示,并且让超时的自动销毁。

对session对象实现监听,首先必须继承HttpSessionListener类,该程序的基本原理就是当浏览器访问页面的时候必定会产生一个session对象,当关闭该页面的时候必然会删除session对象。所以每当产生一个新的session对象就让在线人数+1,当删除一个session对象就让在线人数-1。
还要继承一个HttpSessionAttributeListener,来实现对其属性的监听。分别实现attributeAdded方法,attributeReplace方法以及attributeRemove方法。
sessionCreated//新建一个会话的时候触发,也可以说是客户端第一次喝服务器交互时触发。
sessionDestroyed//销毁会话的时候,一般来说只有某个按钮触发进行销毁,或者配置定时销毁。
HttpSessionAttributeListener有三个方法需要实现
attributeAdded//在session中添加对象时触发此操作 笼统的说就是调用setAttribute这个方法时候会触发的
attributeRemoved//修改、删除session中添加对象时触发此操作  笼统的说就是调用 removeAttribute这个方法时候会触发的
attributeReplaced//在Session属性被重新设置时。

十、easyExcel如何实现

Asynchronous reading
Create a new ExcelModelListener listener class, and inherit the AnalysisEventListener class

package com.zh.oukele.listener; import com.alibaba.excel.context.AnalysisContext;import com.alibaba.excel.event.AnalysisEventListener;import com.zh.oukele.model.ExcelMode; import java.util.ArrayList;import java.util.List; /*** *  监听器 */public class ExcelModelListener extends AnalysisEventListener<ExcelMode> {     /**     * 每隔5条存储数据库,实际使用中可以3000条,然后清理list ,方便内存回收     */    private static final int BATCH_COUNT = 5;    List<ExcelMode> list = new ArrayList<ExcelMode>();    private static int count = 1;    @Override    public void invoke(ExcelMode data, AnalysisContext context) {        System.out.println("解析到一条数据:{ "+ data.toString() +" }");        list.add(data);        count ++;        if (list.size() >= BATCH_COUNT) {            saveData( count );            list.clear();        }    }     @Override    public void doAfterAllAnalysed(AnalysisContext context) {        saveData( count );        System.out.println("所有数据解析完成!");        System.out.println(" count :" + count);    }     /**     * 加上存储数据库     */    private void saveData(int count) {        System.out.println("{ "+ count +" }条数据,开始存储数据库!" + list.size());        System.out.println("存储数据库成功!");    } }

11. What is Swagger? Have you implemented it with Spring Boot?

Swagger is a visual representation tool used to generate RestFul Web services, which enables visual updates of documents and servers;

After defining Swagger, you can call the server-side interface to view the return value of the interface and verify the correctness of the returned data;

Highlights from the past issue:

Summary of Java knowledge system (2021 version)

Summary of basic knowledge of Java multithreading

[Summary of the most complete Java framework in the full stack] SSH, SSM, Springboot

Super detailed springBoot study notes

Summary of common data structures and algorithms

Java design patterns: a comprehensive analysis of 23 design patterns

Summary of Java interview questions (with answers)