java interview basic questions finishing (three)

java interview basic questions

table of Contents

Article Directory

struts2 framework

Briefly describe the mvc programming mode in struts?

The full name of MVC is Model View Controller, which is an abbreviation of model-view-controller. Struts is the role of C in MVC, because it is mainly responsible for Action processing various requests.

Talk about the working principle of Struts2

  1. The user issues an HttpServletRequest request
  2. This request is transmitted through a series of filters Filter
  3. Call the controller FilterDispatcher
  4. The controller obtains Action information through ActionMapper
  5. Controller calls ActionProxy
  6. ActionProxy reads the struts.xml file to obtain information about action and interceptorStack
  7. ActionProxy passes the request request to ActionInvocation
  8. ActionInvocation calls action and interceptor in turn
  9. Generate result according to the configuration information of action
  10. Result information is returned to ActionInvocation
  11. Generate an HttpServletResponse response
  12. The generated response behavior is sent to the customer service terminal.

tocken prevents duplicate submissions

The principle of token implementation is to store a key in the form (this key is also obtained by the server). When the form is submitted, the key is taken with it. After arriving at the server, the key is first judged whether it is valid. If it is valid, the user's request is processed. After the processing is completed, the key is set as invalid. If the key is invalid, the user is prompted that the form has been submitted once.

hibernate framework

Talk about Hiberante's cache

There are three types of caches in Hibernae, namely, the first level cache, the second level cache, and the query cache. The results will be put into the cache during the first query, and the second query will be directly obtained from the cache, so Hibernate cache Can improve query efficiency

  • Level 1 cache (session)
    • Valid for the current session, the cache is emptied when the session is closed, the corresponding methods are get or load
  • Secondary cache (sessionFactory)
    • The data in the secondary cache can be used in all sessions of the current application. Hibernate only provides an interface for the secondary cache. The specific implementation is done by a third party. Commonly used ones are EHCache, OSCache, SwarmCache and JBossCache. When accessing the object with the specified id, first look it up in the first-level cache, and use it directly if found, then go to the second-level cache to find if it is not found (the second-level cache must be configured and enabled), if found in the second-level cache, Use it directly, otherwise the database will be queried, and the query results will be placed in the cache according to the object id
  • Query cache
    • For frequently used query statements, if the query cache is enabled, Hibernate will store the query results in the second cache when the query statement is executed for the first time. When the query statement is executed again in the future, only the query results need to be obtained from the cache, thereby improving query performance

Talk about how Hibernate solves the problem of lazy loading

  • The lazy loading problem can be solved by setting the lazy attribute to false. This is the simplest but not practical. Because no matter whether the object is used or not, Hiberate will be queried for other attributes or related objects, which will lead to waste of resources
  • It can also be solved by OpenSessionInViewFilter. This method is to hand over the session to the servletFilter to manage. When a request comes, a session will be opened, and the session will be closed only when the response is over.

spring framework

When are our configuration beans instantiated in Spring? And the shape of the bean in the container

  • The default container initializes beans when loading, but you can also delay loading by setting the lazy-init property
  • First instantiate the bean
  • Assemble the bean according to the Spring configuration information, which is the IOC
  • If the bean is configured with the init-method attribute in the Spring configuration file, this method will be automatically called for initialization.
  • This is a Bean and it can be used
  • If the Bean is not in use, the Bean will be cleaned up. If the destroy-method attribute is configured, its configured destruction method will be automatically called

Describe the working principle of spring

  • The two core ideas in Spring IOC and AOP, IOC inversion of control give the right to create objects to the Spring container, which can be automatically produced. The principle of reflection is used to dynamically create and call objects. Spring is to dynamically create and maintain the relationship between objects according to the configuration file when running, and realize the idea of ​​loose coupling.
  • AOP is aspect-oriented programming, that is, it can well separate business logic and system services (transactions, logs, etc.). Business logic only cares about business processing and no longer handles other things. These are all achieved through configuration.

Talk about IOC and DI, AOP and list the application scenarios in project development

  • The concepts of IOC and AOP have been mentioned in the interview questions above, and the following mainly talk about DI and usage scenarios
  • Dependency Injection This is DI. The Spring container injects the object into the place where it is used. The injected object only provides the corresponding method to accept it. The container determines the dependencies between the objects.
  • scenes to be used
    • IOC: Beans in the project can be handed over to the Spring container to maintain, so that the creation and destruction of Beans and their life cycles do not require us to deal with them. Spring is managed.
    • DI: For example, the service layer needs to call the Dao layer to access the database. At this time, the Bean of the service layer and the Bean of the Dao layer can be managed by Spring. We only need to define the corresponding method in the service to receive the Dao layer injected by the Spring container. Bean
    • AOP: transactions, logs, permissions, etc.

Talk about how Spring configures declarative transaction control

There are also two common ways of declarative transaction management, one is based on the xml configuration file of the tx and aop namespaces, and the other is based on the @Transactional annotation

  • Configuration file
    -configure the transaction manager
    -transaction strategy (here you can configure the transaction isolation level, propagation attributes, readability, etc.)
    -configure the entry point of the transaction, inject transaction attributes
  • Annotation
    -Configure transaction manager
    -Enable annotation support for transaction control-
    Add @Transactiona to the class or method, and the attributes of the transaction are set on the attributes of the annotation

What are the scope of Spring?

  • Singleton (default) Each Spring container has only one instance object
  • The prototype (prototype) creates a new instance every time it is called
  • Request (request) Each HTTP request has its own Bean instance. Only available in web-based Spring ApplicationContext
  • Session (session) In an HttpSession, the container will return the same instance of the Bean. For different Session requests, a new instance will be created. The bean instance is only valid in the current Session. This scope is valid only when Spring is used in a web application.
  • globalSession In a global HttpSession, the container will return the same instance of the Bean, which is only valid when portletContext is used

What is the underlying principle of spring aop? What are the advantages of interceptors?

  • The bottom layer of Spring AOP is implemented through proxy
    • One is a dynamic proxy based on JDK
    • One is a dynamic proxy based on CgLIB
  • The interceptor is implemented based on the Java reflection mechanism, using proxy mode
    • The interceptor does not depend on the servlet container
    • The interceptor can only work on action requests
    • The interceptor can access the action context
    • The interceptor can obtain each bean in the IOC container
    • In the action life cycle, the interceptor can be called multiple times

The characteristics of spring? How to implement spring principle by hand?

  • Spring has a large amount of core ideas AOP and IOC (specifically above)
  • Spring is a huge factory, this factory is specially used to generate Beans, so if you want to write by hand, you must use the factory design pattern
  • Write a factory class to provide a static method externally. This method accepts an id of the object that the user wants to create. The object and id can be written into the configuration file. The factory provides an init method to read the configuration file. What the user calls is that the incoming id finds the object to be created in the configuration file according to the id, and finally creates the object through reflection and returns it to the user

springMVC framework

Which annotation does the Controller use to receive JSON data?

方法的形参上用@RequestBody修饰
@RequestMapping(value = "/addJSON")
public String addJSON(@RequestBody User user) {
	System.out.println("UserController.add() "+user);
		return "ok";
}
发送时要写上 contentType:'application/json'
$.ajax({
	url :"addJSON",
	type :"POST", 
	dataType:"json",
	contentType:'application/json;charset=UTF-8',
	data:JSONstr,
    success : function(data) {
		console.info(data);   
	} 
});

Talk about the working principle of SpringMVC

  1. The user sends a request to the server, and the request is first captured by the SpringMVC front-end control DispatcherServlet;
  2. DispatcherServlet parses the request URL to obtain the requested resource identifier (URI). Then according to the URI, call HandlerMapping to obtain all related objects of the Handler configuration, and finally return in the form of a HandlerExecutionChain object
  3. DispatcherServlet selects an appropriate HandlerAdapter based on the Handler obtained.
  4. Extract the model data in the Request, fill in the Handler input parameters, and start executing the Controller
  5. After the Controller is executed, it returns a ModelAndView object to DispatcherServlet;
  6. According to the returned ModelAndView, select a suitable ViewResolver and return it to DispatcherServlet;
  7. ViewResolver combines Model and View to render the view
  8. Return the rendering result to the client.

Talk about your understanding of SSM (SpringMVC Spring Mybatis), how do they collaborate to complete the function development? Can describe their respective functions by completing a certain function

  • SSM is a standard MVC design pattern that divides the entire system into four layers: display layer, control layer, business layer, and data layer.
  • SpringMVC is responsible for request forwarding and view management
  • MyBatis is responsible for database query database
  • Spring is responsible for coordination and realizing business object management, which is the most different level of convergence

Common annotations in springMVC

  • @RequestMapping-request and method mapping
  • @RequsetBody-Receive JOSN data from the client
  • @ResponceBody-return client JOSN data
  • @Controller-represents the control layer
  • @Service-represents the business layer
  • @Repository-represents the data layer
  • @Component-add the bean to the Spring container
  • @Autowired-automatic injection, according to type injection
  • @Resource-custom injection, you can inject by type or by name
  • @PathVariable-used in restFul style
  • @Param-used when form parameters and method parameters are different

mybatis framework

The difference between mybatis and hibernate

  • MyBatis

    • advantage
      • Developers can flexibly control SQL statements and reduce query fields
      • All SQL statements are placed in a unified configuration file to facilitate maintenance and management, reducing the coupling between SQL and programs
      • MyBatis is a semi-automated ORM framework, object data and object actual relationships still need to be implemented and managed by handwriting SQL
      • Support dynamic writing of SQL
    • Disadvantage
      • Database portability is very weak, different databases need to write different SQL statements
      • The DAO layer method does not support method overloading
      • Does not support cascading updates and deletions
  • Hibernate

    • advantage
      • Dialects in Hibernate can facilitate database transplantation
      • Hibernate provides first-level cache, second-level cache, and query cache to improve query efficiency. The cache in MyBatis is not good
      • Hibernate is a fully automated technology, the Dao layer development is relatively simple, just call the save method directly
    • Disadvantage
      • It is more complicated when multiple tables are associated, and the use cost is not low
      • SQL statements are automatically generated, and it is difficult to modify SQL to optimize
  • Summary
    -The two frameworks have their own merits. If there are few multi-table related queries in the project (such as more than 10 tables), you can choose to use Hiberate. Otherwise, choose MyBatis. The specific framework to choose depends on the project.

    Finally, here is a small summary
    mybatis: small, convenient, efficient, simple, direct, semi-automatic
    hibernate: powerful, convenient, efficient, complex, flexible, fully automatic

The difference between $ and # in mybatis

  • #: is parsed as a precompiled statement of jdbc, for example: #{name} is finally dynamically parsed as a?, followed by a precompiled object of jdbc? Assignment, this way will not cause SQL injection problems.
  • $: Write the incoming content directly into the sql statement, such as: select * from ${tableName}, the passed parameter is "t_user", and it is finally parsed as select * from t_user. This method will cause SQL injection problems, which are generally used to transfer dynamic tables or use dynamic field sorting.

mybatis realization principle

  • The bottom layer of MyBatis still uses JDBC to operate the database, and the execution process is encapsulated by several processors such as SqlSession, Executor, StatementHandler, ParameterHandler, ResultHandler and TypeHandler.
  • SqlSession: The top-level interface of MyBatis operation, as a session access, completes the function of deleting, modifying, and checking
  • Executor: MyBatis executor, this is the core interface of MyBatis, responsible for dynamic SQL generation and query caching
  • StatementHandler: Responsible for interacting with the JDBC Statement and setting the parameters of the Statement, and converting the returned resultSet of JDBC into a list
  • ParameterHandler: responsible for setting parameters to the Statement object according to the passed parameters
  • ResultHandler: Responsible for converting the ResultSet result set into a list
  • TypeHandler: otherwise the conversion of JavaType and JdbcType, set parameters for the Statement object

How to realize batch insertion in mybatis?

可以通过foreach标签实现批量插入
 <insert id="addUsers">  
    INSERT INTO t_user(name,password)  VALUES   
	<foreach collection="users" item="user" separator=",">  
		  (#{user.name},#{user.password})  
	</foreach>  
</insert>

Can tags in XML files in Mybatis write and delete sql?

can

The fetch-size tag in Mybatis

Set how many records are fetched from the database each time, call the setfetchsize of the underlying preparedstatement

other

Activiti workflow task processing

  • Task service needs to be used for task processing. It is necessary to consider whether to agree or reject. This information can be obtained from the form, and then the method to complete the task is called, passing in agreement or rejection as a process variable.
  • It may be necessary to set the next handler to complete the task, which can be achieved through TaskListener

Talk about FreeMarker? Will you use tags? How to traverse and determine whether it is empty

  • FreeMarker is a template engine written in Java language, which generates text output based on templates. Its advantages are as follows
    • Can not write java code, can achieve strict mvc separation
    • Performance is very good
    • Good support for jsp tags
    • Set a large number of commonly used functions, very convenient to use
    • Macro definition (similar to jsp tags) is very convenient
    • Use expression language
  • Commonly used tags are
    • <#if obj??> …<#else>…</#if> – Determine whether the object exists
    • <#if obj?exists && obj.id == 1>…<#else>…</#if> – 比较
    • <#list listObj as obj> – Collection traversal
    • ${list?size}-Get the collection length

Could you please talk about your knowledge of Maven?

  • Maven is an open source project management tool written in pure Java. Maven uses a concept called project object model (POM) to manage projects. All project configuration information is defined in a file called POM.xml. Through this file, Maven can manage the entire lifecycle of the project. , Including compiling, building, testing, publishing, reporting, etc. At present, most of the projects under Apache have been managed by Maven. And Maven itself also supports a variety of plug-ins, which can facilitate more flexible control of the project

Could you please talk about the precautions when using SVN? How to resolve when a conflict occurs?

  • When using SVN in a project, update it as often as possible and submit it early.
  • When submitting, write a clear message, so that you can find the reason for the user update in the future
  • Develop good usage habits. When using SVN, update it first and submit it later. After opening every morning, first get the latest version from the repository. All edited documents must be submitted to the repository before leaving get off work every day
  • Two ways to resolve conflicts
    • Give up your own updates and use others' updates. Overwrite the target file with the latest version
    • Manual resolution: When a conflict occurs, after communicating with other users, manually update the target file. Then execute resolved filename to resolve the conflict, and finally submit

Talk about how your authority management is implemented? What are the tables involved? What is the relationship between the tables? How to control the menus that users can access?

  • The design of permissions is inseparable from roles, users and permissions. These three dimensions are the most basic in the design of permissions management. When assigning, you can assign permissions to roles first, and then assign roles to people. In this way, different people have different roles and thus different permissions.
  • The realization of permissions should use the idea of ​​AOP. When the user accesses a method, first determine whether the user has the permission to access the method, if so, execute it, if not, jump to a page without permission and prevent him from accessing it. You can achieve controller control
  • We can make dynamic menus and go to the database to check them. The menus that the current user has permission to see are not found every time. If you don’t have permission, you won’t be able to see it. Another is that it’s not dynamic. Make a judgment on the page, and display it if there is permission for this menu, and not display it if there is no permission.
  • Permission frameworks that have been implemented are Shiro and Spring Security.

Understanding of webservice

  • WebService is a cross-programming language and cross-operating system platform remote calling technology.
  • The so-called cross-language means that the server can be written in Java by the user, and the client can be written in other languages
  • The so-called cross-platform means that the server and the client can be on different operating systems
  • The classic is the weather. Now every mobile phone can check today’s weather. Our mobile phone is actually a client. The client accesses the server through the network. The server is on the server of a certain company. Today's weather conditions are obtained through various hardware and technologies, and all this information is converted into data and stored on the server. We can query today's weather conditions directly through mobile phones.

The interview questions were sorted out manually, and analyzed and answered them according to my own understanding. It is inevitable that there are deficiencies. I hope you can correct me and hope to help you!


The only reliable standard of truth is that it always conforms to itself. —— Irving

Guess you like

Origin blog.csdn.net/weixin_44511845/article/details/102528667