The most detailed Spring and SpringMVC summary

1. Why use Spring?

(1) Facilitate decoupling and simplify development

通过Spring提供的IoC容器,可以将对象之间的依赖关系交由Spring进行控制,避免硬编码所造成的过度程序耦合。

(2) AOP programming support

通过Spring提供的AOP功能,方便进行面向切面的编程,如性能监测、事务管理、日志记录等。

(3) Support for declarative transactions.

(4) Facilitate the integration of various excellent frameworks.

(5) Reduce the difficulty of using Java EE API

如对JDBC,JavaMail,远程调用等提供了简便封装。

2. What is IoC and why use IoC?

description:

IoC stands for Iversion of Controller, inversion of control. The concept is that you don't need to create an object, but only need to describe how it is created. You don't assemble your components and services directly in the code, but you need to describe which components need which services in the configuration file, and then a container (IOC container) is responsible for assembling them.

the reason:

It can guide us how to design loosely coupled and better programs.

3. What is AOP and why use AOP?

description:

AOP full name: Aspect-Oriented Programming, aspect-oriented programming. It is to extract the reusable functions, and then weave these general functions into the application at the right time, such as transaction management, permission control, logging, performance statistics, etc.

the reason:

AOP does not help us solve any new problems, it just provides a better way to solve some existing problems with less workload, making the system more robust and maintainable.

4. What is Spring's transaction management?

A transaction is a unified commit or rollback operation for a series of database operations (such as inserting multiple pieces of data). If the insertion is successful, then both succeed. If there is an exception in the middle, then all previous operations are rolled back. This can prevent dirty data from appearing and prevent problems with database data. To avoid this situation during development, transaction management is generally performed.

Spring's declarative transaction usually refers to the configuration statement of the transaction in the configuration file, which includes a lot of declarative properties. It uses Spring Proxy to help you do the proxy. You don't need to write additional code yourself, just declare it in the Spring configuration file. Yes; usually used in database operations;

Programmatic transaction refers to transaction processing through hard coding. This processing method requires writing code, and the logic in the transaction can be customized by yourself; it can be the stuff of the database or other operations.

Spring also has its own transaction management mechanism, which is generally managed by TransactionMananger, which can be accomplished through Spring injection.

5. The Spring framework supports the following five bean scopes:

(1) singleton: default value, bean has only one instance in each Spring ioc container.

(2) Prototype: A bean definition can have multiple instances.

(3) request: A bean is created for each http request, and the scope is only valid in the context of a web-based Spring ApplicationContext.

(4) Session: In an HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the case of web-based Spring ApplicationContext.

(5) Global-session: In a global HTTP Session, a bean definition corresponds to an instance. This scope is only valid in the case of web-based Spring ApplicationContext.

6. What is Spring's MVC framework?

Spring is equipped with a full-featured MVC framework for building web applications. Spring can be easily integrated with other MVC frameworks, such as Struts. Spring's MVC framework uses inversion of control to clearly isolate business objects from control logic. It also allows to bind request parameters to business objects in a declarative manner.

spring mvc is a web framework based on mvc. 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 to enable annotations:

 <context:annotation-config/>

If you use context:component-scanbase-package="com.tgb.web.controller.annotation"
</context:component-scan>, the above content can be omitted

8. The request process of Spring MVC:

The first step: initiate a request to the front controller (DispatcherServlet);

Step 2: The front controller requests HandlerMapping to find the Handler that can be searched according to the xml configuration and annotations;

The third step: the processor mapper HandlerMapping returns Handler to the front controller;

Step 4: The front controller calls the processor adapter to execute the Handler;

Step 5: The processor adapter executes the Handler;

Step 6: Handler execution is complete and returns ModelAndView to the adapter;

Step 7: The processor adapter returns ModelAndView to the front controller. ModelAndView is a low-level object of springmvc framework, including Model and view;

Step 8: The front controller requests the view resolver to perform view resolution, and resolves it into a real view (jsp) according to the logical view name;

Step 9: The view resolver returns View to the front controller;

Step 10: The front controller performs view rendering. View rendering fills the model data (in the ModelAndView object) into the request field;

Step 11: The front controller responds to the user with the result.

9, web.xml configuration

Insert picture description here

10. Annotated processor mapper and adapter

Use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping annotation mapper after spring3.1.

Use org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter annotation adapter after spring3.1.

Use mvc:annotation-driven instead of the above annotation mapper and annotation adapter configuration.

11. Spring and mybatis integration process

Step 1: Integrate the dao layer

        mybatis和spring整合,通过spring管理mapper接口。

       使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

Step 2: Integrate the service layer

       通过spring管理 service接口。

       使用配置方式将service接口配置在spring配置文件中。

       实现事务控制。

Step 3: Integrate springmvc

       由于springmvc是spring的模块,不需要整合。

The main configurations are:

(1) Mybatis configuration file sqlMapConfig.xml configures alias automatic scanning (entity class)

(2) Mapper scanner (interface, database access interface)

(3) Database connection pool configuration

(4) Declarative transaction configuration

(5) Enable annotation scanning: <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 resolver: <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">

(8) Configuration control class: DispatcherServlet front controller

(9) Configure the spring configuration file loading class: ClassLoadListener

12. Front-end controller

The front controller loads the mapper, adapter, view parser and other components from the above file. If it is not configured in springmvc.xml, it uses the DispatcherSerlvet.properties loaded by default.

13. View resolver configuration prefix and suffix:

Insert picture description here

14. sqlMapConfig.xml, mybatis' own configuration file.

Insert picture description here

15. Configure the data source:

Insert picture description here

16. Transaction control

Transaction control (applicationContext-transaction.xml), using spring declarative transaction control method in applicationContext-transaction.xml.
Insert picture description here

17, load spring configuration

Insert picture description here

18. Access to static resources is not blocked:

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

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

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

19. The role of @RequestMapping

(1) url mapping

(2) Narrowing request mapping

(3) Limit http request method

20, the return value of the controller method

1. Return to ModelAndView

When the method is needed, define ModelAndView, and set the model and view separately.

2. Return string

If the controller method returns string:

(1) Represents the return of the logical view name. Real view (jsp path) = prefix + logical view name + suffix

(2) Redirect: The returned string format is: "redirect: queryItem.action"

(3) Forward page forwarding: The returned string format is: "forward:queryItem.action"

3. Return void

You can define request and response on the formal parameters of the controller method, and use request or response to specify the response result:

(1) Use request to turn to the page, as follows: request.getRequestDispatcher("page path").forward(request, response);

(2) You can also redirect through the response page: response.sendRedirect("url");

(3) You can also specify the response result through response, for example, the response json data is as follows:

response.setCharacterEncoding(“utf-8”);

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

response.getWriter().write(“json串”)。

21. Parameter binding:

1. Types supported by default

You can use these objects by directly defining objects of the following types on the formal parameters of the controller method. In the parameter binding process, if you encounter the following types, bind directly.

(1) HttpServletRequest: Get request information through the request object;

(2) HttpServletResponse: Process response information through response;

(3) HttpSession: Get the objects stored in the session through the session object;

(4) Model/ModelMap: model is an interface, modelMap is an interface implementation. Role: Fill the model data into the request field.

2. Simple type

Use @RequestParam to bind simple type parameters.

If @RequestParam is not used, the parameter name passed in the request is required to be consistent with the formal parameter name of the controller method in order to bind successfully.

If you use @RequestParam, you don't need to restrict the name of the parameter passed in the request to be consistent with the parameter name of the controller method.

Specify whether parameters must be passed in through the required attribute. If set to true, if no parameters are passed in, an error will be reported.

3.pojo binding

The name entered in the page is the same as the attribute name in the pojo parameter of the controller, which binds the data in the page to the pojo. (usename, age; user.username, user.age is not required).

4. Custom parameter binding to achieve date type binding

For the pojo object in the controller parameter, if there is a date type in the attribute, you need to customize the parameter binding. Convert the requested date data string into a date type, and the date type to be converted is consistent with the type of the date attribute in the pojo.

22, Spring MVC and Struts2 comparison

(1) Struts2 is a class-level interception, a class corresponds to a request context, SpringMVC is a method-level interception, a method corresponds to a request context, and a method corresponds to a URL at the same time, so SpringMVC is easy to implement from the architecture itself restful url.

(2) Due to the above reasons, SpringMVC's methods are basically independent, and request response data is exclusively shared. Request data is obtained through parameters, and the processing results are returned to the framework through ModelMap. Variables are not shared between methods, while Struts2 does it. It's messy. Although the methods are independent, all the Action variables are shared. This will not affect the running of the program, but it will cause us trouble when coding and reading the program. Every time a request comes, an Action, an Action object is created. Corresponds to a request context.

(3) Since Struts2 needs to encapsulate each request, encapsulate the variables of the servlet life cycle such as request and session into a Map for use by each Action to ensure thread safety, so in principle, it is more memory-consuming.

(4) SpringMVC integrates Ajax, which is very convenient to use. It can be realized by only an annotation @ResponseBody, and then the response text can be directly returned. However, the Struts2 interceptor integrates Ajax. Generally, you must install a plug-in or write your own when processing in Action The code is integrated, and it is relatively inconvenient to use.

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

(6) Springmvc can be developed in a single case, while struts2 can only be developed in multiple cases.

23, garbled processing

(1) Post garbled

Add post garbled filter in web.xml: CharacterEncodingFilter

(2) There are two solutions to the garbled characters in the Chinese parameter of the get request:

  1. Modify the tomcat configuration file and add the code to be consistent with the project code, as follows:

     <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    
  2. Recode the parameters:

     String userName = new  String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
    
     ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码
    

24, collection type binding

(1) Array binding:

        controller方法参数使用:(Integer[] itemId)

        页面统一使用:itemId 作为name

(2) List binding:

         pojo属性名为:itemsList

         页面:itemsList[index].属性名

(3) Map binding:

         pojo属性名为:Map<String, Object> itemInfo = new HashMap<String, Object>(); 

         页面: 姓名:"text"name="itemInfo['name']"/>

25, spring verification

(1) In projects, front-end verification is usually used, such as js verification in the page. For higher security requirements, it is recommended to perform verification on the server.

(2) Springmvc uses hibernate's verification framework for validation (it has nothing to do with hibernate).

Validation idea: The page submits the request parameters, the request is sent to the controller method, and the validation is used for verification. If there is a check error, the error message will be displayed on the page.

26, data echo

(1) @ModelAttribute can also pass the return value of the method to the page: annotate @ModelAttribute on the method;

(2) Use the easiest way to use model, without @ModelAttribute: model.addAttribute("id", id);

(3) springmvc echoes the pojo data by default. After the pojo data is passed to the controller method, springmvc automatically puts the pojo data in the request field, and the key is equal to the pojo type (the first letter is lowercase);

(4) public String testParam(PrintWriter out, @RequestParam(“username”) String username) { //out直接输出 。

27, exception handling

springmvc provides a global exception handler (a system has only one exception handler) for unified exception handling.

When the system encounters an exception, it is manually thrown in the program, dao throws to the service, service to the controller, and the controller throws to the front controller, and the front controller calls the global exception handler.
Insert picture description here

28, upload pictures

(1) When submitting enctype="multipart/form-data" data in the page form, springmvc is required to parse the multipart type data.

(2) Configure the multipart type parser in springmvc.xml.
Insert picture description here
(3) Method used: MultipartFile attach (single file upload) or MultipartFile[] attachs (multiple file upload)

29, Json processing

(1) Load the jar package 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. Add messageConverters to the annotation adapter RequestMappingHandlerAdapter.

If you use <mvc:annotation-driven />, it will be automatically added.

(3) Ajax.
Insert picture description here
(4) Controller (ResponseBody, RequestBody)
Insert picture description here
(5) Note that if the contentType in ajax is not set to json type, the passed parameter is key/value type. After the above settings, the json type is passed.

30. Interceptor:

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

  1. preHandle: Executed before entering the Handler method, used for identity authentication and identity authorization, such as identity authentication. If the authentication is passed, it means that the current user is not logged in, and this method needs to be intercepted and no longer executed.
  2. postHandle: After entering the Handler method, it is executed before returning to modelAndView. The application scenario starts from modelAndView: transfer common model data (such as menu navigation) to the view here, or you can specify the view here.
  3. afterCompletion: Execute Handler to complete the execution of this method, application scenarios: unified exception handling, unified log handling.

(2) Interceptor configuration:

  1. Configuration for HandlerMapping (not recommended): Springmvc interceptor sets interception for HandlerMapping. If interception is configured in a HandlerMapping, the handler that successfully maps through the HandlerMapping will eventually use the interceptor. (Generally not recommended)
  2. Similar to the global interceptor: springmvc configuration is similar to the global interceptor, and the springmvc framework injects the configured global interceptor into each HandlerMapping
    Insert picture description here

Java knowledge is much more than that. This is just a little bit of sorting out. Because of space problems, it is not easy to place all the content, but I have sorted out a large amount of Java learning materials, and I also have the latest Java interview this year. information, there is a need can click to enter, signal: cszq , may also be concerned about + private letter I!

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/m0_45270667/article/details/108695640