Java Interview Question Update Post (Updated on April 19, 2020)

1. Spring

1. Talk about IOC container and DI dependency injection in Spring

Answer: The IOC container in Spring, that is, inverse of control inversion, for example, before using Spring, when we use the dao layer object in the service layer, we are used to using a new dao layer object. This is a This kind of strong dependence does not conform to the principle of low coupling and high cohesion in Java . To understand coupling , we introduced the factory pattern. Originally, the way we obtained the objects was new, and now the objects created by the factory provide us What turned out to be our initiative is now passive. This is called control inversion. This factory is actually a Map, which we call a container.

SpringIOC容器使用过程
//1.使用 ApplicationContext 接口,就是在获取 spring 容器
ApplicationContext ac = new ClassPathXmlApplicationContext("bean.xml");
//2.根据 bean 的 id 获取对象
IAccountService aService = (IAccountService) ac.getBean("accountService");
System.out.println(aService);
IAccountDao aDao = (IAccountDao) ac.getBean("accountDao");
System.out.println(aDao);

The difference between BeanFactory and ApplicationContext?

BeanFactory is the top-level interface in the Spring container.
ApplicationContext is its sub-interface.
The time at which the object is created is different.
ApplicationContext: As soon as the configuration file is read, the object is created by default.
BeanFactory: What to use when to create objects.

Bean tag in IOC?

Used to configure objects to be created by spring.
By default, it calls the parameterless constructor in the class. If there is no parameterless constructor, it cannot be created successfully.

id: Provide a unique identifier for the object in the container. Used to get objects.
class: The fully qualified class name of the specified class. Use for reflection to create objects. The parameterless constructor is called by default.
scope: Specify the scope of the object.
* singleton: default value, singleton.
* prototype: multiple cases.
* request: In the WEB project, Spring creates a Bean object and stores the object in the request field.
* session: WEB project, Spring creates a Bean object, store the object in the session domain.
* Global session: WEB project, applied in the portlet environment. If there is no portlet environment, then
globalSession is equivalent to session.
Init-method: Specify the initialization method name in the class.
destroy-method: Specifies the name of the destroy method in the class.

The scope and life cycle of the bean?

Singleton object: scope = "singleton"
An application has only one instance of the object. Its scope is the entire reference.
Life cycle:
Object born: When the application loads and the container is created, the object is created.
Subject is alive: As long as the container is present, the subject is alive.
Object death: When the application is uninstalled and the container is destroyed, the object is destroyed.
Multiple instances of objects: scope = "prototype"
Each time an object is accessed, an object instance is recreated.
Life Cycle:
Object Birth: When using objects, create new object instances.
The object is alive: as long as the object is in use, it will remain alive.
Object death: When the object is not used for a long time, it is collected by java's garbage collector.

Dependency injection DI in Spring

DI , dependency injection。

Constructor injection

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
    <constructor-arg name="name" value=" 张三 "></constructor-arg>
    <constructor-arg name="age" value="18"></constructor-arg>
    <constructor-arg name="birthday" ref="now"></constructor-arg>
</bean>

Set method injection, the most commonly used

<bean id="accountService" class="com.itheima.service.impl.AccountServiceImpl">
    <property name="name" value="test"></property>
    <property name="age" value="21"></property>
    <property name="birthday" ref="now"></property>
</bean>
<bean id="now" class="java.util.Date"></bean>

p namespace injection, actually call the set method injection

2. Annotations in Spring

@Component: equivalent to <bean id = "" class = "">; There is only one attribute value in the annotation, which is used to specify the id value of the bean; three annotations are derived for different layers of the three-tier architecture, @Controller , @Service, @Repository.

@Autowired: Automatic injection according to type. When using annotations to inject properties, the set method can be omitted. It can only inject other bean types. When there are multiple types matching, use the name of the object variable to be injected as the id of the bean, and find it in the spring container. If it is found, it can also be injected successfully. Report an error if you can't find it.

@Qualifier: On the basis of automatic injection according to type, and then according to the id of Bean injection. It cannot be used independently when injecting fields, and must be used together with @Autowire; but it can be used independently when injecting method parameters. The annotation has an attribute value: specifies the id of the bean.

@Resource: Inject directly according to the id of the bean. It can only be injected into other bean types. The annotation has only one attribute name: specifies the id of the bean.

@Value: Inject basic data type and String type data, the annotation has an attribute value: used to specify the value.

@Scope: Equivalent to: <bean id = "" class = "" scope = "">, specify the scope of the bean. The annotation has only one attribute value: the value of the specified range. Value: singleton prototype request session globalsession.

@Configuration: Used to specify that the current class is a spring configuration class, and annotations will be loaded from this class when the container is created. You need to use AnnotationApplicationContext (class with @Configuration annotation.class) to get the container. This annotation has an attribute value: used to specify the bytecode of the configuration class.

@ComponentScan: Used to specify the package to be scanned by spring when initializing the container. The function is the same as in the spring xml configuration file:
<context: component-scan base-package = "com.itheima" /> Write in the line below @Configuration, @ComponentScan ("com.itheima")

@Bean: This annotation can only be written on the method, indicating that this method is used to create an object and put it into the spring container. name: Assign a name (ie bean id) to the object created by the current @Bean annotation method.

3. Talk about your understanding of AOP in Spring

AOP: The full name is Aspect Oriented Programming, namely: aspect-oriented programming. Simply put, it is to extract the repeated code of our program. When it needs to be executed, use the dynamic proxy technology to enhance our existing methods without modifying the source code.

Connection point (JointPoint) : refers to all methods in the project, we can add the code to write logs for each method, so each candidate is a connection point

Pointcut : Then we must not add a log for every method. Those connection points that need to be processed are called pointcuts.

Notification (Advice) : The code for writing logs is called notification, which means the part of the code that is specifically enhanced

Aspect : Entry point + notification = aspect

<bean id="log" class="com.wanglei.utils.Logger"></bean>
<!--配置AOP-->
<aop:config>
        <!--配置切入点-->
        <aop:pointcut id="accountServicePoint" expression="execution(* com.wanglei.service.impl.*.*(..))"></aop:pointcut>
        <!--配置切面=通知+切入点-->
        <aop:aspect id="logAdvice" ref="log">
            <!--前置通知-->
            <aop:before method="printLog1" pointcut-ref="accountServicePoint"></aop:before>
            <!--后置通知-->
            <aop:after-returning method="printLog2" pointcut-ref="accountServicePoint"></aop:after-returning>
            <!--异常通知-->
            <aop:after-throwing method="printLog3" pointcut-ref="accountServicePoint"></aop:after-throwing>
            <!--最终通知-->
            <aop:after method="printLog4" pointcut-ref="accountServicePoint"></aop:after>

        </aop:aspect>
</aop:config>

二、SpringMVC

1. SpringMVC processing flow

(1) The client sends a request to the front-end controller DispatcherServlet;
(2) After receiving the request, DispatcherServlet calls the HandlerMapping processor mapper to request a
handle ; (3) The processor mapper finds a specific processor according to the request url and generates The processor object and processor interceptor (generated if any) are returned to DispatcherServlet;
(4) DispatcherServlet calls the HandlerAdapter processor adapter ;
(5) HandlerAdapter calls the specific processor (Handler, also called the back-end controller after adaptation) );
(6) Handler execution returns to ModelAndView;
(7) HandlerAdapter returns Handler execution ModelAndView to DispatcherServlet;
(8) DispatcherServlet passes ModelAndView to ViewResolver view resolver for analysis;
(9) ViewResolver returns to specific View after analysis;
( 10) DispatcherServlet renders the view to the View (that is, fills the model data into the view)
(11) DispatcherServlet responds to the user.

 

2. Binding of request parameters

Basic data type and String, require key = value format in the request path

    <a href="param?info=wanglei">向后台传递wanglei</a>

    @RequestMapping(path = "/param")
    public String paramMethod(String info){
        System.out.println(info);
        return "success";
    }

POJO object, the name attribute in the form and the attribute in the user entity class must be the same before it can be injected through the set method

    <form action="beanparam" method="post">
        用户名:<input name="username" type="text"><br>
        年&nbsp龄:<input name="userage" type="text"><br>
        账户名:<input name="account.accountname" type="text"><br>
        账户密码:<input name="account.accountpass" type="text"><br>
        <input type="submit" name="提交">
    </form>

    @RequestMapping(path = "/beanparam")
    public String parambeanMethod(User user){
        System.out.println(user);
        return "success";
    }

Request path placeholder binding parameters: The request path must be in /delProducts.do/3 format

    //使用占位符,保证占位符和@PathVariable("ids")一样
    @RequestMapping("/delProducts.do/{ids}")
    @ResponseBody
    public String delProducts(@PathVariable("ids") String ids){
        if (ids.contains(",")){
            String[] split = ids.split(",");
            Integer id = Integer.valueOf(split[0]);
            productService.delProducts(id);
            System.out.println("================id"+id);
        }else {

        }

        return "删除ok";
    }

3. The request parameters are garbled in Chinese

<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>

4.Cookie和Session

Both Cookie and Session belong to the session technology in javaweb. Session: A session is similar to a conversation in life. The role of session technology is to share data in a session. It is divided into client-side session technology (cookie) and server-side session technology. (Session).

The HTTP protocol is a stateless protocol. Once the data exchange is completed, the connection between the client and the server will be closed, and a new connection needs to be established to exchange data again. This means that the server cannot track the session from the connection.

Difference: Cookies are saved in the client browser, while Session is saved on the server. Cookie mechanism is to determine the customer's identity by checking the "passport" on the customer, then the Session mechanism is to confirm the customer's identity by checking the "customer list" on the server. Session is equivalent to a client file created by the program on the server. When a client visits, he only needs to query the client file table.
 

5. Forwarding and redirection

Forwarding: It is the transfer of control within the server, which is requested by the server area. The client does not know how to transfer, so the address of the client browser will not display the redirected address. The address bar will not change.
Redirection: It is the server that tells the client which address to redirect to. The client then requests the redirected address by itself, so the redirected address is displayed, and it can be understood that the browser has made at least two access requests. The address bar will change.

 

 

Published 111 original articles · Like 60 · 70,000 + views

Guess you like

Origin blog.csdn.net/Haidaiya/article/details/105611801