1. Please talk about the implementation process of SpringMVC

Steps:

1. The user sends a request to the server, which is captured by springMVC front-end controller DispatchServlet; 2. Front-end Controller request processor mapper: Query Controller 3 that can handle the request. Return the found Controller path to the front Controller.

4. The front-end controller requests a processor adapter: Find a processor that can handle the request. The processor executes the request code. (Controller-service-DAO) 6. Encapsulate the processed result and response page into the ModelAndView object and return it to the processor adapter. Return the ModelAndView object to the front controller.

8. The front controller asks the View parser to parse the View object to determine which page it is. 9. View parser internal concatenation, the page name concatenation into the real page path, back to the front controller. View=hello –> (/ web-inf /hello.jsp) View rendering (populating the page with data (the request field)), and finally presenting the complete view to the user.

2. The main components of Spring MVC?

  • Front-end controller DispatcherServlet (no programmer development) function: receive requests, response results, equivalent to a forwarder, with DispatcherServlet to reduce the coupling degree between other components.

  • The HandlerMapping (no programmer development required) is used to find handlers based on the requested URL

  • Note: When writing a Handler, follow the rules required by the HandlerAdapter so that the HandlerAdapter can properly execute the Handler.

  • Handler (programmer development required)

  • View resolver (no programmer development required) : Parses views into real views according to the logical name of the view.

  • View View (Requires a programmer to develop JSPS) View is an interface whose implementation classes support different View types (JSP, Freemarker, PDF, etc.)

3. What are the differences between springMVC and Struts2?

  • For springmvc entry is a servlet that front controller (DispatchServlet), and struts 2 is a filter blocking entrance (StrutsPrepareAndExecuteFilter).

  • Springmvc is method-based development (one URL corresponds to one method). Request parameters are passed to method parameters, which can be designed as singletons or multiple instances (suggested singletons). Struts2 is class-based development, passing parameters through class attributes, which can only be designed as multiple instances.

  • Struts uses value stack to store the data of request and response, and accesses data through OGNL. Springmvc parses the request content through parameter parser, assigns values to method parameters, and encapsulates data and view into ModelAndView objects. Finally, the model data in the ModelAndView is transferred to the page via the RequES domain. The Jsp view parser uses JSTL by default.

4. How to solve the problem of Chinese garbled characters in POST requests and how to handle GET requests?

  • Configure a CharacterEncodingFilter in web. XML and set it to UTF-8.
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>
/*</url-pattern>
</filter-mapping>
Copy the code

  • There are two solutions to the problem:
  • ① Modify the Tomcat configuration file to add the code consistent with the project code as follows:
<ConnectorURIEncoding=" UTF-8 "connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>Copy the code

  • ② Another method to re-encode parameters:
String userName = new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
Copy the code

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

5. What are the annotations commonly used by SpringMVC?

  • RequestMapping: annotation used to handle requested URL mapping, which can be used on a class or method. For a class, that means that all methods in the class that respond to requests have that address as the parent path.
  • @RequestBody: Annotation implementation receives JSON data from HTTP requests and converts json to Java objects.
  • ResponseBody: The annotation implementation converts the object returned by the Conreoller method into a JSON object response to the client.

6. Is SpringMvc’s Controller singleton? If so, what is the problem and how to solve it?

A: It is singleton mode, so there are thread safety issues when multi-threaded access, which will affect performance. The solution is to try not to use class variables in controllers.

For many cases the common property will not be shared, for static properties it will be shared. In the singleton case, both ordinary and static properties are shared. (Controller defaults to singletons.) SpringMVC is developed based on methods. Parameters in methods are not shared, so it defaults to multiple instances. If SpringMVC is going to use class variables, it needs to be multi-example. Struts is developed based on the properties of the class. Singletons share the properties, so singletons are not safe, so they are multiple by default.

7. What is the MVC pattern?

  1. The full name of MVC is Model View Controller, which is the abbreviation of Model – View – Controller. It is a Model of software design. It uses a method of separating business logic, data and interface display to organize the code, and gathers a large number of business logic into one part. When the interface and user interaction need to be improved and customized, there is no need to rewrite the business logic, so as to reduce the coding time.
  2. V stands for View. A View is the interface that the user sees and interacts with. For example, a web page interface consisting of HTML elements, or a software client interface. One of the nice things about MVC is that it can handle many different views for your application. There’s no real processing going on in the view, it’s just a way to output data and allow the user to manipulate it.
  3. M stands for Model. Models represent business rules. Of the three parts of MVC, the model has the most processing tasks. The data returned by the model is neutral and the model is independent of the data format, so that a model can provide data for multiple views, reducing code duplication because code applied to the model can be written once and reused by multiple views.
  4. C stands for Controller. A controller is a controller that accepts input from the user and invokes models and views to fulfill the user’s requirements. The controller itself does not output anything or do any processing. It simply receives the request, decides which model artifact to call to process the request, and then determines which view to use to display the returned data.

8. What are the advantages of SpringMVC?

  1. SpringMVC itself is integrated with the Spring framework and has both the benefits of Spring (such as dependency injection DI and aspect programming AOP).
  2. SpringMVc provides powerful convention over configuration programming support by contract, providing a software design paradigm that reduces the number of decisions a software developer has to make to specify only the parts of an application that don’t conform to convention.
  3. Flexible URL-to-page controller mapping is supported.
  4. Easy integration with other view technologies (JSP, FreeMarker, and so on). Because SpringMVC’s model data tends to be placed in Map data structures, it can be easily referenced by other frameworks.
  5. Has a very concise exception handling mechanism.
  6. Data validation, formatting, and data binding mechanisms can be implemented flexibly, and data binding operations can be performed using any object.
  7. RestFul style is supported.

9. What happens when a method returns a special Object to AJAX, such as Object,List, etc.?

  1. Annotate the method with @responseBody to indicate that the return value of the method, regardless of type, will return JSON data.
  2. Replace the @Controller annotation on the Controller class with the @RestController annotation. @restController = @Controller + @responseBody indicates that all methods of the Controller class return data in JSON format (except those without @requestMapping annotations).
  3. The reason why we can return JSON data by adding an @responseBody annotation: The HttpMessageConverter provided by SpringMVC is automatically converted to JSON. If Jackson or Gson is used, no extra configuration is required to automatically return JSON because the framework provides the corresponding HttpMessageConverter. If you use Alibaba’s Fastjson, you’ll need to manually provide an instance of the corresponding HttpMessageConverter.

10. What object does SpringMVC use to pass data from the background to the front desk?

  • Use Map, Model, and ModelMap methods, which store data in the Request domain
@RequestMapping("/getUser") public String getUser(Map<String,Object> map,Model model,ModelMap modelMap){ //1. Map. put("name", "xq"); AddAttribute ("habbit", "Play"); //3. Put modelmap.adDattribute ("city", "gd") in modelMap; modelMap.put("gender", "male"); return "userDetail"; }Copy the code

  • Use request
@RequestMapping("/getUser")
public String getUser(Map<String,Object> map,Model model,ModelMap modelMap,HttpServletRequest request){
    //放在request里  
    request.setAttribute("user", userService.getUser());
    return "userDetail";
} 
Copy the code

  • Using a ModelAndView
@RequestMapping("/getUser")  
public ModelAndView getUser(ModelAndView modelAndView) {
    mav.addObject("user", userService.getUser());  
    mav.setViewName("userDetail");  
    return modelAndView;  
} 
Copy the code

11. How to put ModelMap data into session?

Add the @sessionAttributes annotation to the class to store the specified Model data into the session.

@SessionAttributes

  1. By default, Spring MVC stores the data in the model into the Request domain. When a request ends, the data is invalidated. If you want to use it across pages. So you need to use sessions. The @sessionAttributes annotation causes a copy of the data in the model to be stored in the session domain.
  2. SessionAttributes can only be defined in Class and interface enum. The @sessionAttributes function adds key/value pairs from the specified Model to a session for use within a session.

@ SessionAttributes parameters

  1. Names: This is an array of strings. It should contain the name of the data to be stored in the session.
  2. Types: Stores parameters of the corresponding type in the model into the session according to the specified parameter type.
  3. Value: The same as names above.
@SessionAttributes(value={"names"},types={Integer.class}) @Controller public class session{ @RequestMapping("/session") public String session(Model model){ model.addAttributes("names", Arrays.asList("caoyc","zhh","cjx")); model.addAttributes("age", 22); return "/session"; }}Copy the code

In the code above, add the @sessionAttributes annotation to the class and specify that Model data with names and type Integer be stored in the Session field.

12.SpringMMV has a class that combines views and data. What is it called?

It’s called ModelAndView.

  1. Use the ModelAndView class to store the resulting data after processing, as well as the view that displays the data. The name “Model” in ModelAndView represents the Model and “View” represents the View, which explains the purpose of this class. After the Controller processor calls the model layer to process the user request, it stores the result data in the model property of the class, stores the view information to be returned in the View property of the class, and then returns the ModelAndView to the front-end Controller. The front-end controller parses the object by calling the view parser defined in the configuration file, and finally displays the resulting data on the specified page.
  2. The ModelAndView constructor can specify the name of the page to return. You can also jump to the specified page using the setViewName() method.
  3. Returns the desired value using addObject() to set the value to return. AddObject () has methods with several different parameters that can default and specify the name of the returned object.

13. How are systems layered in Springmvc?

The system is divided into presentation layer (UI) : data display, operation page, request forwarding. Business layer (service layer) : encapsulates the business processing logic persistence layer (data access layer) : encapsulates the relationship between the data access logic layers: the presentation layer invokes the business layer through the interface, and the business layer invokes the persistence layer through the interface. In this way, the changes of the next layer do not affect the data of the previous layer. MVC is a presentation layer architecture

14. How are interceptors used in Springmvc

Defines an interceptor that implements the HandlerInterceptor interface. Three methods are provided in the interface.

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 is not logged in. After entering the Handler method and executing before returning to modelAndView, the application scenario starts from modelAndView: Upload common model data (such as menu navigation) to the view from here, or specify afterCompletion uniformly: Run the Handler command to execute this method. The application scenario is as follows: Unified exception processing and unified log processing

Interceptor configuration:

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) Global-like interceptors: SpringMVC configures global-like interceptors, and the SpringMVC framework injects configured global-like interceptors into each HandlerMapping

15. Introduce 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 also has its own transaction management mechanism, which is usually managed using TransactionMananger and can be done through Spring injection.

Sping transactions are managed in two ways:

Programming (granularity is down to code block level);

Programming mainly uses transactionTemplate; Manage transactions manually programmatically

Declarative (granularity is down to method level);

Implemented by AOP, its essence is to intercept before and after the method, and then create or join a transaction before the target method begins, and commit or roll back the transaction according to the execution of the target method after it is finished. The biggest advantage of declarative transactions is that they do not need to be managed programmatically. This means that you do not need to mix transaction management code with your business logic code. Instead, you can apply transaction rules to your business logic by declaring them in a configuration file (or by using the @Transactional annotation).

16. What are the functions of spring BeanFactory and ApplicationContext?

Spring describes beans and their dependencies through a configuration file, instantiates beans and establishes dependencies between beans using Java’s reflection capabilities. Sprig’s IoC container provides advanced services such as Bean instance caching, lifecycle management, Bean instance proxy, event publishing, and resource loading in addition to these low-level functions.

Spring provides two types of IOC container implementations.

BeanFactory: The basic implementation of the IOC container. ApplicationContext: Provides more advanced features. Is a subinterface of the BeanFactory. Bean plant (com) springframework. Beans. Factory. The BeanFactory) is the core of the interface in the Spring framework, it provides a senior IoC configuration mechanism. The BeanFactory makes it possible to manage Java objects of different types. while

Application context (com) springframework) context. ApplicationContext) based on the BeanFactory, provides more geared to the needs of the application of the function, it provides the international support and system framework events, easier to create practical application.

We call the BeanFactory the IoC container and the ApplicationContext the ApplicationContext or the Spring container.

17. What is your understanding of Spring framework? What modules does Spring framework have?

Spring is a lightweight IoC and AOP container framework that provides foundational services for Java applications. It is intended to simplify enterprise application development by allowing developers to focus only on business requirements.

Spring, an open source framework for simplifying enterprise application-level development. Simplified development: It encapsulates commonly used apis, such as JDBC, without having to worry about getting connections and closing when accessing a database using Spring JDBC. Decoupling: Spring helps us manage software dependencies so that objects are less coupled and thus more maintainable. Integration with other frameworks: easy to extend and optimize its functionality, such as integration with Mybatis, etc.

The Spring framework is carefully crafted to follow design patterns, which makes it easy to use the framework in a development environment, regardless of what goes on behind the scenes. The Spring container is a core module of the Spring framework that manages the creation, destruction, and initialization of objects, as well as the dependencies between objects.

It mainly includes the following seven modules:

Spring Context: provides frame-like Bean access and enterprise-level functionality (JNDI, scheduled tasks, etc.); Spring Core: a Core class library on which all functionality is dependent, providing IOC and DI services; Spring AOP: AOP services; Spring Web: Provides basic Web-oriented integration features, support for common frameworks such as Struts2, the ability to manage these frameworks, inject Spring resources into them, and insert interceptors around them; Spring MVC: Provides model-View-Controller (MVC) implementations for Web applications; Spring DAO: Abstract encapsulation of JDBC, simplifying the processing of data access exceptions, and unified management of JDBC transactions; Spring ORM: Support for existing ORM frameworks.

18. What is Inversion of Control (IOC) and what is dependency injection (DI)?

IOC: The dependencies between objects are created by the container. The relationships between objects are originally created and maintained by us developers. After we use the Spring framework, the relationships between objects are created and maintained by the container. The BeanFactory interface is the core interface of the Spring Ioc container. DI: When we use the Spring container, the container calls the set method or constructor to establish dependencies between objects. Inversion of control is the goal, and dependency injection is one of the ways we achieve inversion of control.

19. Spring Bean lifecycle?

As the most popular and powerful lightweight framework for Java today, Spring has been warmly welcomed by programmers. An accurate understanding of the life cycle of Spring beans is essential. We usually use ApplicationContext as the Spring container. Here, we are also talking about the life cycle of the Bean in the ApplicationContext. The BeanFactory is similar, but the handler needs to be manually registered.

In short, the Spring Bean life cycle consists of four stages: Instantiation > property assignment > Initialization > Destruction

But specifically, the life cycle of a Spring Bean includes the following flow:

(1) Instantiate the Bean

For the BeanFactory container, createBean is called when a customer requests an uninitialized bean from the container, or when another uninitialized dependency needs to be injected to initialize the bean.

For the ApplicationContext container, when the container is started, all beans are instantiated by getting information from the BeanDefinition object.

(2) Set object properties (dependency injection)

The instantiated object is wrapped in a BeanWrapper object, and Spring then sets the properties and dependency injection based on the information in BeanDefinition and the interface provided through BeanWrapper to set the properties.

(3) Processing Aware interface

Spring checks whether the object implements the xxxAware interface. Aware interfaces allow us to access some of the Spring container’s resources:

If the Bean implements the BeanNameAware interface, its setBeanName(String beanId) method is called, passing in the Bean name. ② If the Bean implements the BeanClassLoaderAware interface, call setBeanClassLoader() and pass in an instance of the ClassLoader object. ② If the Bean implements the BeanFactoryAware interface, its implementation of the setBeanFactory() method is called, passing in the Spring factory itself. (3) If the Bean implements the ApplicationContextAware interface, the setApplicationContext method is called, passing in the Spring context.

(4) BeanPostProcessor preprocessing

If you want to to some custom of pre-processing of Bean, then can let the Bean implements the BeanPostProcessor interface, it will call postProcessBeforeInitialization (Object obj, String s) method.

(5) InitializingBean

If the Bean implements the InitializingBean interface, execute the afeterPropertiesSet() method.

(6) init – method

If the Bean has the init-method property configured in the Spring configuration file, its configured initialization method is automatically called.

(7) BeanPostProcessor post-processing

If the Bean implements the BeanPostProcessor interface, will call postProcessAfterInitialization (Object obj, String s) method. Because this method is called at the end of Bean initialization, it can be applied to memory or cache techniques;

After the above steps are complete, the Bean has been correctly created and is ready to use.

DisposableBean (8)

When the Bean is no longer needed, it passes through the cleanup phase, and if the Bean implements the DisposableBean interface, its implementation destroy() method will be called.

(9) destroy – method

Finally, if the Bean has the destroy-method property configured in its Spring configuration, its configured destruction method is automatically called.

20. What design patterns are used in the Spring framework?

Singleton pattern: Beans in Spring are singleton by default. Factory pattern: Spring uses the factory pattern to create bean objects from the BeanFactory, ApplicationContext. Template method pattern: Spring’s jdbcTemplate, hibernateTemplate, and other classes that end in Template for database operations use the Template pattern. Proxy pattern: Implementation of Spring AOP functionality. Observer Pattern: The Spring event-driven model is a classic application of the Observer pattern. Adapter pattern: The adapter pattern is used in Spring AOP enhancements or Advice, and is used in Spring MVC to adapt controllers. Decorator pattern: Our project needs to connect to multiple databases, and different customers need to access different databases on each visit. This pattern allows us to dynamically switch between different data sources based on customer needs.

Spring AOP (aspect oriented) programming principle?

AOP is faceted programming, and it is an idea. It is for the business process of the section to extract, in order to achieve the purpose of optimizing the code, reduce the purpose of repeating the code. For example, when writing business logic code, we are used to writing: logging, transaction control, permission control, and so on, and each submodule has to write this code, the code is obvious duplication. At this time, we use the idea of section-oriented programming, the use of crosscutting technology, the repeated part of the code, does not affect the main business logic of the part extracted, put in a place for centralized management, call. Form log section, transaction control section, permission control section. In this way, we only need to deal with the business logic, that is, improve the efficiency of the work, and make the code become concise and elegant. This is the idea of section-oriented programming, which is an extension of object-oriented programming.

Use scenarios of AOP: caching, permission management, content delivery, error handling, lazy loading, record tracking, optimization, calibration, debugging, persistence, resource pooling, synchronization management, transaction control, etc. The concept of AOP: JoinPoint Advice Pointcut Proxy WeaVing Spring AOP programming principles? Proxy mechanism JDK dynamic proxy: Can only be used to generate proxies for classes that implement the interface. Cglib proxy: Generates proxies for classes that do not implement interfaces, using underlying bytecode enhancement techniques to generate subclass objects of the current class. (1) Join point: refers to the method executed during the operation of the program. In Spring AOP, a join point always represents the execution of a method.

(2) Aspect: a common module that is extracted and can be used to crosscut multiple objects. An Aspect can be thought of as a combination of Pointcut and Advice, and an Aspect can consist of multiple pointcuts and Advice.

In Spring AOP, aspects can be implemented on a class using the @AspectJ annotation.

(3) Pointcut: Pointcut points are used to define which Join points to intercept.

Tangent points are divided into execution mode and annotation mode. Execution allows path expressions to specify which methods to intercept, such as add* and search*. The annotation approach specifies which annotations decorate the code to intercept.

Advice: Actions to be performed at Join points, i.e., enhanced logic, such as permissions checksum, logging, etc. There are various types of notices, including Around, Before, After, After RETURNING, and After Throwing.

(5) Target: Objects containing join points, also known as Advice objects. Since Spring AOP is implemented through dynamic proxies, this object is always a proxy object.

(6) Weaving: the process of Advice enhancement in the method of Target (Join point) through dynamic proxy.

(7) Introduction: Add additional methods or fields to the notified class. Spring allows you to introduce new interfaces (and corresponding implementations) to any proxied object. For example, you can use an introduction to make the bean implement the IsModified interface to simplify the caching mechanism.

A diagram of several concepts can be seen below:

The key of AOP implementation lies in the proxy mode. AOP proxy is mainly divided into static proxy and dynamic proxy. Static proxies are represented by AspectJ; Dynamic proxies are represented by Spring AOP.

(1) AspectJ is static proxy, also known as compile-time enhancement. AOP frameworks generate AOP proxy classes at compile time and weave AspectJ(aspects) into Java bytecode, which run as enhanced AOP objects.

(2) Spring AOP use dynamic proxy, the so-called dynamic proxy is an AOP framework won’t go to modify the bytecode, but each time to run in memory temporarily for the method to generate a AOP object, the object of AOP method contains all of the target object, and in particular the tangent point of enhancement processing, and the correction method of the original object.

There are two main types of dynamic proxies in Spring AOP, JDK dynamic proxies and CGLIB dynamic proxies:

JDK dynamic proxy only provides the proxy of the interface, does not support the proxy of the class, requires the proxy class to implement the interface. At the core of JDK dynamic proxies are the InvocationHandler interface and Proxy class. When a Proxy object is acquired, the Proxy class is used to dynamically create the Proxy class of the target class (that is, the real Proxy class, which inherits from Proxy and implements the interface we defined). When the Proxy object calls the methods of the real object, The InvocationHandler uses the invoke() method reflection to call code in the target class, dynamically weaving crosscutting logic and business together;

Invoke (Object Proxy,Method Method,Object[] args) of InvocationHandler: Proxy is the final generated proxy Object; Method is a specific method of the proxied target instance; Args is a concrete entry to a method of the propped target instance that is used when the method reflection is invoked.

② If the proxied class does not implement an interface, Spring AOP will choose to dynamically proxied the target class using CGLIB. CGLIB (Code Generation Library) is a Code Generation Library that can dynamically generate a subclass object of a specified class at runtime, and override specific methods and add enhanced Code to implement AOP. CGLIB is dynamically proxied by inheritance, so if a class is marked final, it cannot be dynamically proxied using CGLIB.

(3) The difference between static proxy and dynamic proxy is that the generation of AOP proxy object is different, relatively speaking, AspectJ’s static proxy method has better performance, but AspectJ needs a specific compiler for processing, while Spring AOP does not need a specific compiler for processing.

IoC allows components that work together to remain loosely coupled, while AOP programming allows you to separate functionality across application layers into reusable functional components.

22. How does WebService interact with the client

① webServices receive parameters and transfer return values through SOAP protocol. The WSDL file is an XML document that describes a set of SOAP messages and how to exchange them. In most cases, it is automatically generated and used by software. XML is an extensible markup language. For short-term temporary data and universal networks. ⑤ UDDI is a project mainly aimed at Web service providers and users. Before users can call web services, they must determine what business methods the service contains, find the interface definition to be called, and compile software on the server side. UDDI is a mechanism to guide the system to find response services according to the description article. UDDI uses SOAP message mechanism to publish, compile, browse and find registration information. It uses XML format to encapsulate various types of data and sends it to the registry to return the required data.

23. The difference between interceptors and filters

① The interceptor inteceptor is implemented based on Java reflection mechanism; The Filter is based on the function callback implementation (doFilter method in Filter interface is implemented by callback function). Filters rely on servlets and cannot call back doFilter without servlets. Interceptors only work on action requests. The interceptor can access the action context, objects in the value stack; the interceptor can access the action context, objects in the value stack. The filter does not; (5) Interceptors can be called many times during the life cycle of an action; Filters can only be called once when the container is initialized; (6) Interceptors can fetch individual beans from the IOC container, but filters cannot;

24. Spring MVC exception handling

1. Use the @ExceptionHandler annotation.

public class AccountController {

      @ExceptionHandler

      public void handleException() {}

}
Copy the code

The @ExceptionHandler is Controller level and not globally valid for the entire application. Adding the corresponding @ExceptionHandler method to each controller would be tedious. All Controller classes can inherit the BaseController class and add the @ExceptionHandler modifier to the BaseController class for exception handling.

  1. HandlerExceptionResolver allows for a unified exception handling mechanism. Spring provides the following HandlerExceptionResolver to use:

The core components of ExceptionHandlerExceptionResolver is @ ExceptionHandler mechanisms work.

DefaultHandlerExceptionResolver will to a standard Spring resolved as the corresponding HTTP status code.

ResponseStatusExceptionResolver is mainly used for the modification of custom exception @ ResponseStatus annotations to map exceptions to the appropriate HTTP status code.

SimpleMappingExceptionResolver and AnnotationMethodHandlerExceptionResolver

A custom HandlerExceptionResolver returns a ModelAndView object that can be set to anything needed.

  1. The new @ControllerAdvice provides a global @ExceptionHandler exception handling mechanism.
@ControllerAdvice

public class ExceptionHandler {

                        @ExceptionHandler(Exception.class)

public Result handleException(Exception e)  {

    // todo

  }

}
Copy the code

@ControllerAdvice allows @ExceptionHandler, which is scattered across multiple Controllers, to be merged into a single global error handling component.

25. What are the ways that Spring MVC passes values?

(1) There are three ways to transfer the page value to the controller:

Use Request to transfer values: direct, but not automatic type conversion.

Characteristics of value passing through attributes: First, the name of the variable must be the same as the name value of the form component. Second, type conversion can be implemented. Third, exceptions may occur during type conversion

First, if the front end submits too much data, it is recommended to use this method. Second, encapsulate the name attribute value of the form component into the Bean class. Third, the parameters of the method can be passed to the encapsulated type of the object

(2) There are three ways for the controller to transmit values to the page:

Use Request and Session objects

Using ModelAndView to pass values features: first, you can set a Map object in the ModelAndView constructor. Second, after the Map object is processed by the framework, it sets the key-value to the Request object.

The characteristics of ModelMap value transfer: First, ModelMap is a set of maps provided by the framework; second, ModelMap is also set in the Request object by the framework.

26. How does Spring MVC handle garbled characters?

For POST garbled characters, add a POST garbled filter to the web. XML file — CharacterEncodingFilter. For GET request Chinese parameters garbled characters, the solution is as follows: (1) Modify the Tomcat configuration file to add the encoding consistent with the working encoding

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.

26. What are the execution times of the three methods of the Spring MVC interceptor?

When both interceptors implement the release operation, the sequence is preHanle1, preHandle2, postHandle2, postHandle1, afterCompletion2, afterCompletion1. When the first interceptor preHandle returns false, that is, intercepting it, the second interceptor does not execute at all, and the first interceptor only executes the preHandle part. When the first interceptor preHandle returns True, the second interceptor preHandle returns false, in the order preHandle1, preHandle2, and afterCompletion1

27. What is ContextLoaderListener and what does it do?

ContextLoaderListener is a listener that helps boot the Spring MVC. As the name implies, it loads and creates the ApplicationContext, so you don’t have to write explicit code to create it. The application context is where the Spring bean leaves off. For Web applications, there is a subclass called WebAppliationContext.

ContextLoaderListener also associates the lifecycle of the ApplicationContext with that of the ServletContext. This can be done by using the getServletContext () method to get the ServletContext from WebApplicationContext.

28. How are incoming requests mapped to controllers and methods?

The question is sometimes asked how does the DispatcherServlet know which Controller should handle the request?

Spring using the controller that is associated with the request handler mapping, two common handler mapping is BeanNameUrlHandlerMapping and SimpleUrlHandlerMapping.

In BeanNameUrlHandlerMapping, when the request url matching with the name of the bean, bean definition in the class is to handle the request of the controller.

In SimpleUrlHandlerMapping, on the other hand, the mapping is more explicit. The number of urls can be specified, and each URL can be explicitly associated with the controller.

By the way, if you use annotations to configure Spring MVC, you should use the @requestMapping annotation to map incoming requests to controller and handler methods.

You can also configure @requestMapping annotations with URI paths, query parameters, HTTP methods of the request, and HTTP headers present in the request.

29. What is @requestParam used for?

@RequestParam is a Spring MVC annotation that is used to extract request or query parameters from the controller’s handler method in the URL, as shown below:

Public String personDetail (@requestParam (" id ") long id) {.... Return "personDetails"; }Copy the code

The @requestParam annotation also supports data type conversion. For example, you can see that a String is automatically converted to long, but this can also cause an exception. You can also use requried = false to make the parameter optional if the query parameter does not exist or the type does not match. For example, @requestParam (value = “id”, required = false)

30. What is the difference between SpringBoot, SpringMVC and Spring?

Springboot is simplified configuration, mybatis configuration data source, master configuration file and other configurations, Spring, springMVC configuration file are configured with Springboot YML file, greatly simplified configuration, so that the project can be quickly started up.

SpringMVC is layered by (Model), V (View), C (Controller) structure, so as to achieve the effect of front and back end separation, and then through the front-end controller (DispatcherServlet), processor mapping (HandlerMapping), HandlerAdapter and ViewResolver organically organize each layer, so that everyone has different division of labor, thus speeding up the efficiency of development.

Spring is made up of Aop Aop Aop and IOC control rollover (also known as DI dependency injection). Aspect is the separation of the main method from other unrelated methods to achieve the effect of reducing coupling. Control rollover is the separation of objects originally created by New, with strong dependencies between each class. After transferring the right to create objects to ioc container, ioc container creates objects, which reduces the coupling degree and improves efficiency.

SpringMVC interface explanation

(1) DispatcherServlet interface: the front-end controller provided by Spring, through which all requests are uniformly distributed. Before DispatcherServlet can send requests to Spring Controllers, Spring provides HandlerMapping to locate specific controllers. (2) HandlerMapping interface: it can complete the mapping from customer request to Controller. (3) Controller interface: it is necessary to process the above requests for concurrent users, so the implementation of Controller interface must ensure thread safety and reusable. The Controller will handle the user request, which is consistent with the role played by the Struts Action. Once the Controller has finished processing the user request, it returns the ModelAndView object, which contains the Model and View, to the DispatcherServlet front Controller. From a macroscopic point of view, DispatcherServlet is the controller of the whole Web application. At a micro level, Controller is the Controller in the process of a single Http request, while ModelAndView is the Model and View returned in the process of an Http request. (4) ViewResolver interface: The ViewResolver provided by Spring looks up View objects in Web applications and renders corresponding results to customers.

Project recommendation:

Welcome to VX gongzhong – [more than programming]

More than 2000 GIGABytes of computer industry electronic resources sharing (constantly updated)

2020 micro channel small program full stack project miaomiaodating

Spring Boot development small and beautiful personal blog

Java Micro service combat 296 sets of large video – Grain mall

Java development micro service chang Buy mall actual combat [full 357 sets of large projects] – with code and courseware

The most complete and most detailed data structure and algorithm video