1. Why use Spring?

1). Convenient decoupling and simplified development

With the IoC container provided by Spring, dependencies between objects can be left to Spring to control, avoiding excessive program coupling caused by hard coding.

2). AOP programming support

Spring provides AOP functionality that facilitates section-oriented programming such as performance monitoring, transaction management, logging, and so on.

3). Support for declarative transactions

4). Convenient integration of various excellent frameworks

5). Reduce the difficulty of using Java EE apis

For example, JDBC, JavaMail, remote calls and so on provide easy encapsulation.


2. What is IoC and why is it used?

  • IoC stands for Iversion of Controller.

The idea is that instead of creating an object, you just describe how it was created. You don’t assemble your components and services directly in code, but describe which components require which services in the configuration file, and then a container (IOC container) takes care of assembling them.

It can teach us how to design loosely-coupled, better programs.


3. What is AOP and why is it used?

  • AOP full name: aspect-oriented Programming, section Oriented Programming.

AOP, faceted programming, is about extracting reusable functions and then embedding those generic functions into the application when appropriate, such as transaction management, permission control, logging, performance statistics, and so on.

AOP doesn’t help us solve any new problems, it just provides a better way to solve existing problems with less effort, making systems more robust and maintainable.


4. What is Spring transaction management?

A transaction is a unified commit or rollback of a series of database operations (such as inserting multiple pieces of data), if the inserts are successful, then all of them are successful, and if one of them fails, then all of the previous operations are rolled back. This prevents dirty data and prevents problems with database data.

Transaction management is commonly used in development to avoid this situation.

Spring’s declarative transaction usually refers to the configuration declaration of the transaction in the configuration file, including a lot of declaration properties, it is through the Spring Proxy for you to do the Proxy, do not need to write extra code, just declare in the Spring configuration file can be; Usually used in database operations;

Programmatic transactions are transactions that are done in a hard-coded way that requires writing code and the logic in the transaction can be customized. It can be something in the database, or it can be something else.

Spring also has its own transaction management mechanism, which is usually managed using TransactionMananger and can be done through Spring injection.


5. The Spring framework supports the following five scopes for beans:

  • Singleton: By default, beans have only one instance per Spring IOC container.
  • Prototype: A bean definition can have multiple instances.
  • Request: Each HTTP request creates a bean, which is only valid in the Web-based Spring ApplicationContext context.
  • Session: In an HTTP session, one bean definition corresponds to one instance. This scope is valid only in the case of web-based Spring ApplicationContext.
  • Global-session: In a global HTTP session, one bean definition corresponds to one instance. This scope is valid only in the case of web-based Spring ApplicationContext.


6. What is Spring’s MVC framework?

Spring comes with a full-featured MVC framework for building Web applications. Spring can be easily integrated with other MVC frameworks, such as Struts, which uses inversion of control to separate business objects from control logic. It also allows you to declaratively bind request parameters to business objects.

Spring MVC is an MVC based Web framework. Spring MVC is a module of the Spring framework. Spring MVC and Spring do not need to be integrated through an intermediate integration layer.


7. How do I enable annotations?

<context:annotation-config/>

If you use the < context: component – scan base – package = “com. The TGB. Web. Controller. The annotation” > < / context: component – scan > the above content can be omitted


Spring MVC request flow?

  • Step 1: Send a request to the front-end controller (DispatcherServlet)
  • Step 2: The front-end controller requests HandlerMapping to find the Handler based on the XML configuration and annotations
  • Step 3: HandlerMapping returns a Handler to the forward controller
  • Step 4: The front-end controller calls the processor adapter to execute the Handler
  • Step 5: The processor adapter executes the Handler
  • Step 6: Handler completes execution and returns the ModelAndView to the adapter
  • Step 7: The processor adapter returns the ModelAndView to the forward controller. ModelAndView is an underlying object of the SpringMVC framework, including Model and View
  • Step 8: The front controller requests the view parser to parse the view into a real view (JSP) based on the logical view name
  • Step 9: The View parser returns the View to the front controller
  • Step 10: The front controller renders the view. View rendering populates the request field with model data (in the ModelAndView object)
  • Step 11: The front-end controller responds to the user


9. Web. XML configuration



10. Annotated processor mapper and adapter?

Spring3.1 after using org. Springframework. Web. Servlet. MVC) method. The annotation. The RequestMappingHandlerMapping annotation mapper.

Use after spring3.1 org. Springframework. Web. Servlet. MVC) method. The annotation. RequestMappingHandlerAdapter annotations adapter.

Replace the above annotation mapper and annotation adapter configuration with MVC :annotation-driven


11. Integration process of Spring and Mybatis?

Step 1: Integrate the DAO layer

  • Mybatis and Spring integration, through Spring management mapper interface.
  • Register in Spring using mapper’s scanner to automatically scan the Mapper interface.

Step 2: Consolidate the Service layer

  • Manage the service interface through Spring.
  • Configure the Service interface in the Spring configuration file using configuration mode.
  • Implement transaction control.

Step 3: Integrate SpringMVC

  • Since SpringMVC is a Spring module, no integration is required


The main configurations are:

1).mybatis config file sqlmapconfig.xml configures alias automatic scan (entity class)

2). Mapper scanner (database access interface)

3). Database connection pool configuration

4). Declarative transaction configuration

<context:component-scan base-package=”cn.itcast.ssm.controller”></context:component-scan>

6). Configure annotation mapper and adapter: < MVC :annotation-driven></ MVC :annotation-driven>

7). View the parser: < bean class = “org. Springframework. Web. Servlet. The InternalResourceViewResolver” >

8). Configuration control class: DispatcherServlet front-end controller

9). Configure the Spring configuration file loading class: ClassLoadListener


12. View resolver config prefix and suffix?



Sqlmapconfig. XML, mybatis own configuration file?


14. Configure the data source?


15. Transaction Control (ApplicationContext-Transaction. XML)?

Use the Spring declarative transaction control approach in applicationContext-Transaction.xml.


16. Load the Spring configuration?


17. Static resource access is not blocked?

<resources mapping=”/resources/**” location=”/resources/” />

<resources mapping=”/images/**” location=”/images/” />

<resources mapping=”/js/**” location=”/js/” />


What does 18.@RequestMapping do?

1). A url mapping

2). Narrow the request mapping

3). Restrict HTTP request methods


19. The return value of the Controller method?

1 returns ModelAndView

When the method is finished, define the ModelAndView and set the Model and view separately.

2 return string

If the controller method returns string,

1). Returns the logical view name. Real view (JSP path)= prefix + logical view name + suffix

2). Redirect redirect: return a string format for: “redirect: queryItem. The action”

3). Forward page forward: The return string is in the format of “forward: queryitem.action”.

3 return void

Request and Response can be defined on the controller method parameter, using request or Response to specify the result of the response:

1). Use the request to the page, as follows: request. GetRequestDispatcher (” path “page). The forward (request, response);

2). Can also be redirected via the Response page: Response.sendreDirect (” URL “)

3). The response result can also be specified by response, for example, the response JSON data is as follows:

response.setCharacterEncoding(“utf-8”);

response.setContentType(“application/json; charset=utf-8”);

The response. GetWriter (). The write (” json string “);


20. Parameter binding

1 Default supported type

You can use the following types of objects by defining them directly on the Controller method parameter. During parameter binding, if the following types are encountered, directly bind the parameters.

1). HttpServletRequest: Get the request information from the request object

2). HttpServletResponse: Processes the response information in response

3). HttpSession: Use the session object to get the object stored in the session

4). Model/ModelMap: Model is an interface and ModelMap is an interface implementation. Action: Populates the Request field with Model data.

2 Simple Types

Bind parameters of simple types with @requestParam.

If @requestParam is not used, the request parameter name must be the same as the parameter name of the Controller method.

If you use @requestParam, you don’t have to restrict the request parameter names to be the same as the controller method parameter names.

The required attribute specifies whether the argument must be passed in or not. If set to true, no argument is passed in, an error is reported.

3 the pojo binding

The input name in the page is the same as the attribute name in the Controller’s POJO parameter, binding the data in the page to the POJO. (usename, age; Don’t need the user. The username, user. The age)

4 User-defined parameter binding Implements date binding

For poJO objects in the Controller parameter, custom parameter bindings are required if there is a date type in the property. Convert the request date data string to a date type consistent with the type of the date attribute in the POJO.


21.Spring MVC vs. Struts2?

1). Struts2 is a class-level interception, where a class corresponds to a request context. SpringMVC is a method-level interception, where a method corresponds to a request context, and a method corresponds to a URL. So SpringMVC is easy to implement restful urls from an architectural standpoint

2). Because of the above reasons, SpringMVC methods are basically independent of each other, and enjoy the request response data. The request data is obtained through parameters, and the processing results are returned to the framework through ModelMap. However, all the Action variables are shared, which does not affect the operation of the program, but makes it difficult for us to code and read the program. Every time a request comes in, we create an Action, and an Action object corresponds to a request context.

3). Since Struts2 needs to encapsulate each request, encapsulating variables of the servlet life cycle such as Request and session into a Map for each Action to use and ensuring thread safety, it is relatively memory consuming in principle.

4). SpringMVC integrated Ajax, very easy to use, just a @responseBody annotation can be implemented, and then directly return the response text can be, while Struts2 interceptor integrated Ajax, in Action processing generally must install plug-in or write code to integrate into the. It’s also relatively inconvenient to use.

5). Springmvc is method-oriented (closer to service interface development), Struts2 is class-oriented.

6). Springmvc can be singleton development, Struts2 can only be multi-example development.


22. Garbled code handling?

1). Post gibberish

Add post garbled filter: CharacterEncodingFilter to web. XML

2). There are two solutions for garbled Chinese parameters in GET request:

A. Modify the Tomcat configuration file to add the same code as the project code, as follows:

<Connector URIEncoding=” UTF-8 “connectionTimeout=”20000″ port=”8080″ protocol=”HTTP/1.1” redirectPort=”8443″/>

B. Re-encode the parameters:

String userName = new String(request.getParamter(“userName”).getBytes(“ISO8859-1″),”utf-8”)

Iso8859-1 is the default Tomcat encoding. You need to use UTF-8 encoding to encode the tomcat encoding


23. Collection type binding

1). Array binding:

The controller method uses :(Integer[] itemId)

The page uses itemId as the name

2).list binding:

The poJO attribute name is itemsList

Page: itemsList[index]. Attribute name

3). Map binding:

Pojo attribute name: Map<String, Object> itemInfo = new HashMap<String, Object>();

< inputType =”text”name=”itemInfo[‘name’]”/>


24. The spring check?

1). Front-end verification is often used in projects, such as JS verification in pages. For high security requirements, you are advised to perform verification on the server.

Springmvc uses Hibernate’s validation framework (which has nothing to do with Hibernate).

Validation: The page submits the requested parameters to the Controller method and validates them with Validation. If the verification fails, the error information is displayed on the page.


25. Data echo?

1) @modelAttribute can also upload the return value of a method to the page: annotate @modelAttribute on the method

@modelAttribute: model.addattribute (“id”, id);

3). Springmvc echoes POJO data by default. When the POJO data is passed to the Controller method, SpringMVC automatically puts the POJO data into the Request field with key equal to the POJO type (lowercase).

Public String testParam(PrintWriter out, @requestParam (“username”) String username)


26. Exception handling?


27. Upload pictures?

1). When submitting data of encType =”multipart/form-data” in the page form, springMVC needs to parse the data of type multipart.

2). Configure the multipart type parser in springMVC. XML.


3). Attach MultipartFile or attach MultipartFile[] attachs


28. Json processing

1). Load jar packages for JSON conversion: SpringMVC uses Jackson’s package for JSON conversion (@requestBody and @responseBody use the following package for JSON conversion)

2). Configure the JSON converter. Join in the annotations adapter RequestMappingHandlerAdapter messageConverters. If you use < MVC :annotation-driven /> it will be added automatically.

3). ajax


4). Controller (ResponseBody, RequestBody)


5). Note that if the contentType in Ajax is not set to JSON, the key/value parameter is passed. After the above Settings, the json type is passed.


29. Interceptors?

1). Define the interceptor to implement the HandlerInterceptor interface. Three methods are provided in the interface.

A. PreHandle: executed before entering the Handler method. It is used for identity authentication and authorization, such as identity authentication. If the authentication passes, the current user has not logged in

B. PostHandle: After entering the Handler method and before returning to The modelAndView, the application scenario starts from modelAndView: Transfer common model data (such as menu navigation) to the view from here, or specify the view uniformly from here

AfterCompletion: Execute the Handler. Application scenarios: Unified exception processing and log processing

2). Interceptor configuration:

A. For HandlerMapping configuration (not recommended) : Springmvc interceptors are set up to intercept HandlerMapping. If interceptors are configured in a HandlerMapping, the handler that succeeds in the HandlerMapping will eventually use the interceptor. (Generally not recommended)

B. Global-like interceptors: SpringMVC configures global-like interceptors, and the SpringMVC framework injects configured global-like interceptors into each HandlerMapping


30. What are the ways of autowiring in Spring?

1. No: automatic assembly is not enabled.

ByName: Finds and injects JavaBean dependent objects by the name of the property. For example, if the class Computer has an attribute printer, specifying its autowire attribute as byName, the Spring IoC container will look for the bean with an ID /name attribute printer in the configuration file and inject it using the Seter method.

ByType: Finds javabean-dependent objects by their type and injects them. For example, Class Computer has an attribute printer of type printer. If you specify its autowire attribute as byType, the Spring IoC container will look for the bean with Class printer and inject it using the Seter method.

4. Like byType, find dependent objects byType. It differs from byType in that instead of using Seter method injection, it uses constructor subinjection.

Autodetect: Automatically selects an injection method between byType and Constructor.

6. Default: determined by the default-Autowire attribute of the parent

tag.


The application scenarios, principles and benefits of AOP in Spring?

  • AOP–Aspect Oriented Programming; Used to encapsulate crosscutting concerns, which can be used in the following scenarios:

Authentication permission, Caching, Context passing, Error handling, Lazy loading, Debugging, logging, tracing, tracing, tracing Profiling and Monitoring record tracking optimization calibration, Performance optimization Performance optimization, Persistence, Resource Pooling resource pool, Synchronization, and Transactions.

  • Principle: AOP is section-oriented programming, is through the way of dynamic proxy for the program to add unified functions, centralized to solve some common problems.
  • Advantages: 1. Good isolation between each step coupling greatly reduced 2. Source code independence, and then extend the function without modifying the source code operation


32. The function and principle of IOC in Spring? Object creation process?

IOC–Inversion of Control When a role needs the assistance of another role, in traditional programming, it is usually the caller who creates the instance object of the called. But the job of creating the called in Spring is no longer done by the caller, so it’s called inversion of control. Spring does the job of creating the called and then injecting it for direct use by the caller.


Spring common annotations for creating objects?

@Component@Controller@ Service@ Repository


34. Design patterns used in Spring?

Simple factory, factory method, singleton pattern, adapter, wrapper, proxy, observer, policy, template method


What are the advantages of Spring?

1. The coupling between components is reduced and the decoupling between software layers is realized

2. You can use many services that are easy to provide, such as transaction management, messaging services, etc

3. Containers provide singleton support

4. The container provides AOP technology that makes it easy to implement functions such as permission interception and runtime monitoring

5. Containers provide a number of helper classes to speed up application development

6. Spring provides integration support for mainstream application frameworks, such as Hibernate, JPA, Struts, etc

7. Spring is a low-intrusive design with minimal code contamination

8. Independent of various application servers

9. Spring’s DI mechanism reduces the complexity of business object replacement

10. The open nature of Spring does not force applications to rely entirely on Spring. Developers are free to choose part or all of Spring

36. What are the differences between Spring beans’ scopes?

Beans in the Spring container fall into five categories. All scope names are self-explanatory, but to avoid confusion, let’s explain:

  • Singleton: This scope of beans is the default. This scope ensures that no matter how many requests are received, there is only one instance of a bean in each container, and the singleton pattern is maintained by the bean Factory itself.
  • Prototype: The protoscope is the opposite of the singleton scope, providing one instance for each bean request.
  • Request: An instance is created in the scope of the request bean for each network request from the client. After the request completes, the bean is invalidated and collected by the garbage collector.
  • Session: Similar to request scope, ensure that there is an instance of a bean in each Session and that the bean is invalidated after the Session expires.
  • 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 that all portlets share global stored variables, the global variables need to be stored in global-session.

The global scope has the same effect as session scope in the Servlet.


37. How many ways does Spring manage transactions?

There are two ways:

1. Programmatic transactions, hard-coded in code. (Not recommended)

2. Declarative transactions, configured in configuration files (recommended)

Declarative transactions fall into two categories:

A. Declarative TRANSACTIONS based on XML

B. Annotation-based declarative transactions


38. What are the core classes in Spring and what do they do?

  • BeanFactory: Generates a new instance that implements the singleton pattern
  • BeanWrapper: Provides uniform get and set methods
  • ApplicationContext: Provides an implementation of the framework, including all the functionality of the BeanFactory


39. How can a Bean be invoked?

There are three ways to get the Bean and call it: 1. Use BeanWrapper HelloWorld hw=new HelloWorld(); BeanWrapper bw=new BeanWrapperImpl(hw); Bw. SetPropertyvalue (” MSG “, “HelloWorld”); System. The out. Println (bw. GetPropertyCalue (” MSG “));

BeanFactory InputStream is=new FileInputStream(” config.xml “); XmlBeanFactory factory=new XmlBeanFactory(is); The HelloWorld hw = (HelloWorld) factory) getBean (” HelloWorld “); system.out.println(hw.getMsg());

3, use ApplicationConttext ApplicationContext actx = new FleSystemXmlApplicationContext (” config. The XML “); The HelloWorld hw = (HelloWorld) actx) getBean (” HelloWorld “); System.out.println(hw.getMsg());


40. What is IOC and what is DI, and what is the difference?

DI is a programming pattern and architectural model, sometimes referred to as inversion of control, although technically dependency injection is a special implementation of IOC. Dependency injection means that one object applies another object to provide a special capability, such as: Pass a database connection as a parameter to an object’s structure method instead of creating a connection inside the object itself. The basic idea of inversion of control and dependency injection is to reduce the dependency of a class by converting its dependencies from inside the class to outside the class

With inversion of control, when an object is created, it is passed a reference to the object on which it depends by an external entity that controls all objects in the system. In other words, dependencies are injected into objects. So, inversion of control is a reversal of responsibility for how an object gets a reference to an object it depends on.


41. Spring has two kinds of proxy?

If the target object implements several interfaces, Spring uses the JDK’s java.lang.Reflect.proxy class to Proxy them.

  • Advantages: The system is more loosely coupled because of interfaces
  • Disadvantages: Create interfaces for each target class

If the target object does not implement any interface, Spring uses the CGLIB library to generate subclasses of the target object.

  • Advantages: Because the proxy class inherits from the target class, no interface is required.
  • Cons: System coupling is not as good as using JDK dynamic proxies because there are no interfaces.


42. SpringMVC flow?

1. The user sends a request to the DispatcherServlet of the front-end controller

2. When DispatcherServlet receives a request, it invokes the HandlerMapping processor.

3. The processor mapper finds the specific processor based on the request URL, generates the processor object and the processor interceptor (if any) and returns it to the DispatcherServlet.

4. The DispatcherServlet invokes the handler through the HandlerAdapter processor adapter

5. Execution processor (Controller, also known as back-end Controller).

6.Controller Returns to ModelAndView

7. The HandlerAdapter returns the Controller execution result ModelAndView to the DispatcherServlet

8.DispatcherServlet passes ModelAndView to the ViewReslover view parser

9.ViewReslover parses and returns a specific View

10. The DispatcherServlet renders the View (that is, populates the View with model data).

11.DispatcherServlet responds to user


43. Advantages of Springmvc?

1. It is based on component technology. All application objects, from controllers and views to business objects and the like, are Java components. And tightly integrated with other infrastructure provided by Spring.

2. Don’t rely on the Servlet API(this is the goal, but it does depend on servlets when implemented)

3. You can use any view technology, not just JSPS

4. Supports mapping policies for requested resources

5. It should be easy to expand