Java interview questions (86-115)

Source: Internet
Author: User
Tags i18n

Java programmer interview questions (86-115)

86. In Struts 2, how does Action obtain the data that the user inputs from the page, and how does it transmit its own data to the view?

A: There are three ways for Action to retrieve data from the page:

1) accept parameters through the Action attribute

2) obtain parameters through the domain model

3) ModelDriven )

Action saves data to the Value Stack. Views can obtain data from the Value Stack through Expression Language (EL.

87. Briefly describe how Struts 2 implements the MVC Architecture Model.

A: The MVC Architecture requires the separation of input, processing, and output of applications. The system is divided into three parts: Model, View, and Controller, using controllers to decouple models and views makes development and maintenance of applications easy, as shown in. Among them, the model represents the data of the application and the rules for processing the data. At the same time, it can also query and save the relevant status for the view, which is usually implemented by JavaBean, the model code can be reused by multiple views once written. A view is used to organize the model content. It obtains data from the model and presents the data to the user, in Struts 2, JSP pages and Freemarker templates are usually implemented. The controller accepts requests from the client and converts them to a certain behavior. After the behavior is complete, it selects a view to present it to the user, the controller does not need to output any content. It only receives the request and decides which model component to call to process the request. The StrutsPrepareAndExecuteFilter is the core of Struts 2, it and a series of actions constitute the Controller in Struts 2.


Figure-1 MVC Architecture Pattern

88. describes how Struts 2 Implements user input verification. The verification method is used in your project. Why is this method used?

A: Struts 2 supports manual verification and automatic verification framework for user input verification. The Automatic Verification Framework places the verification rules for input in the XML file. This method is flexible and allows you to modify the verification rules without modifying the code.

89. How to compile the Action in Struts 2? Does Action use Singleton?

A: There are three ways to write Struts2 actions:

1) POJO

2) Implement the Action interface to override the execute () method

3) inherit the ActionSupport class

Action does not work in the same way as Servlet with multiple threads on a single instance. Obviously, each Action must receive request parameters of different users, which means that Action is stateful, therefore, the processing method of each request corresponding to an Action is used in design.

90. The Action in Struts 2 does not directly receive the user's request. Why does it process the user's request? Why does it know which Action a request is sent?

A: After receiving user requests, the core filter of Struts2 performs simple preprocessing (for example, parsing and encapsulating parameters) on user requests, and then creates an Action instance through reflection, and call the method specified in Action to process user requests.

There are two ways to determine which Action the request is sent to: 1. Use the configuration file: You can configure the corresponding Action class and the method to be called through tag configuration in the configuration file; 2. Usage conventions: convention plug-ins can be used in Struts2. For example, conventions xxx always correspond to XxxAction, which is a practice that convention is better than configuration concepts.

91. Which Struts 2 constant configurations do you often use?

A:

1) struts. i18n. encoding-specify the default encoding

2) struts. objectFactory/struts. objectFactory. spring. autoWire-automatic assembly method of the object Factory/Spring (name and type)

3) struts. devMode-whether to use the Development Mode

4) struts. locale-specify the default region. The default value is en_US.

5) struts. i18n. resources-resource files used internationally

6) struts. enable. DynamicMethodInvocation-whether to allow dynamic method calls

92. Briefly describe Struts2's exception handling mechanism.

A: Struts 2 provides a declarative Exception Handling Mechanism. You can add the following code to the configuration file:

93. Let's talk about your understanding of the Agreement over the configuration (CoC.

A: convention over configuration, also known as contract-based programming, is a software design paradigm designed to reduce the number of decisions that software developers need to make. Essentially, developers only need to specify parts that do not conform to the conventions in the application. For example, if there is a class named Sale in the model, the corresponding table in the database will be named sales by default. The configuration of this name must be written only when the table is named products_sold. If the conventions of the tools you use are consistent with your expectations, you can save the configuration. On the contrary, you can configure the tools to meet your expectations. Although some flexibility is lost in the conventions, the directory structure cannot be arranged at will, and the function name cannot be performed at will, but the configuration can be reduced. More importantly, compliance with conventions can help developers comply with building standards, including naming rules.

94. How to Implement I18N in Struts2?

A: First, write different resource files for different languages and then configure Struts in the struts 2 configuration file. i18n. custom. resources constant; in the Action, you can call the getText () method to read the resource file to obtain international resources.

95. Briefly describe how the interceptor works and the custom interceptor you have used in the project.

A: Struts 2 defines the Interceptor interface and default implementation, implementing the Interceptor interface or inheriting the AbstractInterceptor class can be used as the Interceptor. The init () method in the interface is called immediately after the interceptor is created. It is called only once in the lifecycle of the Interceptor. You can initialize the relevant resources in this method. Each time a request is intercepted, the intercept () method is called once. The destory () method will be called before the interceptor is destroyed. It is also called only once in the lifecycle of the interceptor.

Permission interceptor, execution time interceptor, and Token Interceptor Used in the project.

96. How to Use Ajax in Struts2?

A: The following is an optional method to implement Ajax in Struts 2:

1) JSON plugin + jQuery

2) DOJO plugin

3) DWR (DirectWeb Remoting)

97. Let's talk about the differences between interceptor and filter.

A: The interceptor and filter can be used to implement the cross-cutting attention function. The main difference is:

1) the interceptor is based on the Java reflection mechanism, and the filter is based on interface callback.

2) The filter depends on the Servlet container, and the interceptor does not rely on the Servlet container.

3) the interceptor can only act on Action requests, while the filter can act on all requests.

4) the interceptor can access the objects in the Action context and value stack, but the filter cannot.

98. Let's talk about the differences between Struts 1 and Struts2.

Differences

Struts 1

Struts 2

Action class

The Action class must inherit an abstract base class. A common problem with Struts1 is the use of abstract class programming rather than interfaces.

The Action class can implement an Action interface or other interfaces to make optional and customized services possible. Struts 2 provides an ActionSupport class as the Action parent class, but it is not necessary. Any POJO object with the execute method can be used as the Action object of Struts 2.

Thread mode

Action is a singleton mode and must be thread-safe, because only one instance of Action is used to process all requests. The Singleton policy limits what Struts1 actions can do and requires caution during development. Action resources must be thread-safe or synchronized.

The Action object generates an instance for each request, so there is no thread security problem. (In fact, the Servlet container generates many discarded objects for each request without causing performance and garbage collection problems)

Servlet dependency

Action depends on the Servlet API, because when an Action is called, HttpServletRequest and HttpServletResponse are passed to the execute method.

The Action does not depend on the container and allows the Action to be tested independently from the container. If necessary, Struts2 Action can still access the initial request and response. However, other elements reduce or eliminate the need to directly access HttpServetRequest and HttpServletResponse.

Testability

One major problem with Action is that the execute method exposes the servlet API (which makes the test dependent on the container ).

Actions can be tested by initializing, setting properties, and calling methods. "dependency injection" also makes testing easier.

Capture Input

Capture input using the ActionForm object. All actionforms must inherit a base class. Because other JavaBean cannot be used as an ActionForm, developers often create redundant class capture inputs.

Struts2 can capture input through the Action attribute, domain model, or model driver, and also comes with the default type conversion mechanism.

Expression Language

JSTL is integrated, so jstl el is used. This kind of EL has basic object graph traversal, but its support for set and index attributes is weak.

JSTL can be used, but it also supports a stronger and more flexible Expression Language-OGNL (Frankly speaking, this is a very junk and inefficient expression language, because the Struts 2 high-risk vulnerability recently exposed is caused by OGNL)

Type conversion

The ActionForm attribute is generally of the String type. Struts1 uses Commons-Beanutils for type conversion. One converter for each class is not configurable for each instance.

Use OGNL for type conversion. Provides Converters for basic and common objects.

99. Reasons for choosing Struts 2 for your project

Answer: 1Action is a POJO with no dependencies on Servlet APIs and is highly testable. 2. Powerful interceptor simplifies development. 3. Support multiple presentation layer technologies: JSP and Freemarker; 4 flexible verification methods; 5 International (I18N) support; 6 declarative Exception management; 7 simplified Ajax through the JSON plug-in; 8 integrated with Spring through the Spring plug-in.

Supplement: Some people have proposed 20 standards for the selection and evaluation of the Web framework, including: developers' efficiency (Can I build a CRUD page in 1-5 days) what do developers think (is it interesting to use), learning curve (Can I work after a week or a month), and project Health (is the project in desperate condition), developer adequacy (Can you find experienced developers), Employment Trends (Can you recruit people in the future), templated (follow the DRY principle) components (controls such as built-in date selector), Ajax (whether asynchronous call and partial refresh are supported), plug-ins, or additional items (can I add functions such as Facebook integration) scalability (can the number of concurrent users be controlled by default reach 500 +?), test support (can I do test-driven development?), I18N, and L10N (can I support multiple languages and regions), validation (Can you easily verify user input and rapid feedback), multi-Programming Language Support (Can you use multiple languages for development at the same time), document quality (common use cases and problems are reflected in the document), published books (has any industry experts used it and shared their usage experience), and REST support Holding (can I use this protocol according to the HTTP protocol design purpose) and mobile support (is it easy to support Android, iOS and other mobile smart terminals) and the degree of risk (whether large projects can be implemented ). Obviously, Java is not an optimal Web development language, but it satisfies many of the 20, especially the two points of ample developers and mature solutions.

100. How to access three domain objects in Struts 2: HttpServletRequest, HttpSession, and ServletContext

A: There are two methods:

1) obtained through the ServletActionContext method;

2) inject data through the ServletRequestAware, SessionAware, and ServletContextAware interfaces.

101. What is the role of the default Struts-default package in struts 2?

A: it defines many interceptor and Result types in Struts 2. Many core functions of Struts 2 are implemented through these built-in interceptors, such: the request parameters encapsulated in the request to action, file upload, data verification, and so on are all implemented through the interceptor. In the Struts 2 configuration file, the custom package inherits the struts-default package and you can use these functions provided by Struts 2 for us.

102 briefly describe the principle and life cycle of Value Stack

A: Value-Stack runs through the lifecycle of the entire Action and is stored in the request scope. Therefore, it has the same lifecycle as the request. When Struts 2 accepts a request, it creates ActionContext, Value-Stack, and Action object, and stores the Action in Value-Stack. Therefore, the instance variables of the Action can be accessed through OGNL. Because Action is multi-instance, different from the Servlet used in the single instance, each Action has a corresponding Value-Stack, and the Value-Stack stores the Data Type of this Action instance, and instance variables in the Action, the Action object is saved on the top of the stack by default.

103. Is SessionFactory thread-safe? Is the Session thread safe? Can two threads share the same Session?

A: SessionFactory corresponds to a data storage concept of Hibernate. It is thread-safe and can be accessed concurrently by multiple threads. SessionFactory is generally built only at startup. For applications, it is best to encapsulate SessionFactory in singleton mode for convenient access. Session is a lightweight, non-thread-safe object (the session cannot be shared between threads). It represents a unit of work that interacts with the database. The Session is created by SessionFactory and closed after the task is completed. Session is the main interface provided by the persistent layer service. Session will delay obtaining database connections (that is, it will be obtained only when necessary ). To avoid creating too many sessions, you can use ThreadLocal to obtain the current session. No matter how many times you call the getCurrentSession () method, the same session is returned.

104. What is the difference between Session load and get methods?

A: There are three main differences:

1) if no matching record is found, the get method returns null, and the load method throws an exception.

2) The get method returns the object class object directly, and the load method returns the proxy of the Object Class Object.

3) The get method only searches for data in the first-level cache (internal cache). If no corresponding data is found, it goes beyond the second-level cache and directly sends an SQL statement to read the data; the load method can take full advantage of the existing data in the second-level cache.

To put it simply, for the load () method Hibernate thinks that the data must exist in the database, you can safely use the agent to implement delayed loading. If there is no data, an exception is thrown, and get () the data retrieved by the method does not exist.

105 what are the differences between the save (), update (), merge (), lock (), saveOrUpdate (), and persist () Methods of sessions?

A: There are three types of Hibernate objects: transient, persistent, and free. Instances in the free status can be persisted by calling the save (), persist (), or saveOrUpdate () methods. instances in the out-of-the-box status can be updated (), 0 saveOrUpdate (), lock () or replicate () for persistence. Save () and persist () will trigger SQL INSERT statements, while update () or merge () will trigger UPDATE statements. The difference between save () and update () is that one is to change the transient object to the permanent state, and the other is to change the Free State object to the permanent state. The merge method can complete the functions of the save () and update () methods. It aims to combine the new state to an existing persistent object or create a new Persistent Object. According to the instructions in the official documentation: (1) the persist () method persists a transient instance, but "not guaranteed" the identifier is immediately entered into the persistent instance, enter the identifier may be postponed to the flush time; (2) persist "guarantee", when it is called outside a transaction, it does not trigger an Insert statement, when a long session flow needs to be encapsulated, a function such as persist is required. (3) save "does not guarantee" 2nd. It must return the identifier, so it will immediately execute the Insert statement, whether inside or outside the transaction. The update () method is to change an object that has been changed to the persistent state. The lock () method is to change an object that has not been changed to the permanent state.

106 describe the process of loading object by Session.

A: The steps to load an object in a Session are as follows:

1) before the Session calls the database query function, it first queries in the cache. In the first-level cache, it searches through the entity type and primary key, if the first-level cache query hits and the data status is valid, the system returns

2) If the first-level cache does not hit, the Session will be searched in the current NonExists record (equivalent to a query blacklist. If duplicate invalid queries exist, the query can be quickly determined to improve performance, if NonExists has the same query condition, null is returned.

3) for the load method, if the first-level cache query fails, the second-level cache will be queried. If the second-level cache hits, the second-level cache will be returned directly.

4) If none of the previous queries hit, an SQL statement is issued. If no corresponding record is found in the query, the query is added to the NonExists of the Session to record the query and null is returned.

5) obtain the ResultSet Based on the ing configuration and SQL statement, and create the corresponding object.

6) include objects in Session (level-1 cache) Management

7) execute the onLoad method of the Interceptor (if there is a corresponding interceptor)

8) include data objects in the second-level cache

9) return data object

107 what is the difference between the list method and the iterate method of the Query interface?

A:

1) The list method cannot use the cache. It only writes but does not read the cache. The iterate method can make full use of the cache. If the target data is read-only or frequently, iterate can reduce the performance overhead.

2) The list method does not cause N + 1 queries, while the iterate method causes N + 1 queries.

108. How does Hibernate implement paging query?

A: Using Hibernate for paging query, developers only need to provide HQL statements, the start row (setFirstresult () method), and the maximum number of rows (setMaxResult () method ), and call the list () method of the Query interface. Hibernate will automatically generate the SQL statement for paging Query.

109. What is the use of the lock mechanism? Briefly describe the pessimistic lock and optimistic lock mechanism of Hibernate.

A: Some business logic often needs to ensure data access exclusive during execution. Therefore, some mechanisms are required to ensure that data is locked during this process and will not be modified by the outside world, this is the so-called lock mechanism.

Hibernate supports two lock mechanisms: Pessimistic lock and optimistic lock. Pessimistic lock, as its name implies, is pessimistic that there must be a concurrent transaction for modifying data during data processing (including other transactions of the system or transactions from external systems ), therefore, the processed data is set to locked. Pessimistic locks must rely on the lock mechanism of the database to truly guarantee the exclusive access to data. Optimistic lock, as its name implies, is optimistic about concurrent transactions (it is considered that concurrent operations on data rarely occur ), the loose lock mechanism is used to solve the serious impact of pessimistic lock exclusive data access on system performance. The most common optimistic lock is implemented by the data version identifier. the version number of the data is obtained when the data is read, and 1 is added when the data is updated, then compare it with the current version number of the corresponding record of the database table. If the submitted data version number is greater than the current version number of the record in the database, the data is updated; otherwise, the data is considered to have expired.

110 describe the three states of object and the conversion relationship.

A: Objects in Hibernate have three statuses: transient, persistent, and detached, as shown in.


Figure Hibernate object state transition

Ü temporary state: after a new object is created, the object is in the temporary state, that is, the object is only a memory area for saving temporary data. If no variable references this object, it will be reclaimed by the JVM garbage collection mechanism. The data stored in this object has nothing to do with the database, unless the temporary object is associated with the database through Session save or saveOrUpdate, and the data is inserted or updated to the database, this object is converted to a persistent object.

Ü persistent State: instances of persistent objects have corresponding records in the database and have a persistent ID. After the delete operation is performed on the Persistent object, the corresponding records in the database will be deleted, so the persistence object and the database record will no longer have a corresponding relationship, and the persistence object will become a temporary state. After the persistence object is modified and changed, it will not be synchronized to the database immediately until the database transaction is committed.

Ü free state: after the Session is closed, clear, or evict, although the persistence object has a persistence identifier and a value consistent with the corresponding record of the database, the Session has disappeared, objects are not in the persistent management, so they are in the Free State (also called the out-of-tube State ). The object in the Free State is very similar to the object in the temporary state, but it also contains a persistent identifier.

111. How to understand the delayed Loading Mechanism of Hibernate. In practical applications, how does one deal with the conflict between delayed loading and session shutdown?

A: delayed loading is not to load data when reading, but to load data when used. Hibernate uses a virtual proxy mechanism to implement delayed loading. What is returned to the user is not the entity itself, but the proxy of the object. The proxy object loads data from the database when the user calls the getter method. However, the database connection is required to load data. When we close the session, the database connection is closed at the same time.

The conflict between delayed loading and session shutdown is generally handled as follows:

1) disable the delayed loading feature. This method is relatively simple, because the delayed loading feature of hibernate can be configured through the ing file or annotation, but this solution has obvious defects. First, when no session or session wasclosed occurs, it proves that there is a primary/foreign key Association in the system. If delayed loading is removed, the overhead of each query will increase greatly.

2) obtain the data to be queried before closing the session (Hibernate. initialize () method ).

3) Use Interceptor or Filter to control the Session.

112. Give an example of multi-to-Multi-join and explain how to implement multi-to-Multi-join ing.

A: For example, goods and orders, students and courses are typically many-to-many relationships. You can configure multiple-to-multiple associations or use And Tags are configured with many-to-many associations. However, you can usually convert multiple-to-many associations into two many-to-one associations to implement multi-to-many Association ing.

113. Let's talk about your understanding of inheritance ing.

A: There are three mappings for the inheritance relationship:

1) Each inheritance structure is a table (table per class hierarchy)

2) one table for each subclass (table per subclass)

3) one table for each specific class (table per concrete class)

The first method is a single-table policy. It has the advantage that table join is not required when querying subclass objects, which is fast in query and suitable for multi-state queries. The disadvantage is that the table may be large. The latter two methods belong to the multi-table policy. The advantage is that the data storage is compact, and the disadvantage is that connection query is required, which is not suitable for multi-state query.

114 briefly describe the common optimization strategies of Hibernate.

A:

1) formulate reasonable cache policies

2) adopt a reasonable Session management mechanism

3) try to use the delayed loading feature

4) set reasonable Batch Processing Parameters

5) If possible, use UUID as the primary key generator.

6) If possible, use the version-based Optimistic lock to replace the pessimistic lock.

7) during development, enable the hibernate. show_ SQL option to view the generated SQL to understand the underlying State. disable this option after development.

8) the optimization of the database itself (reasonable indexes, caches, and Data Partition policies) will also significantly improve the performance of the persistent layer. These require the support of professional DBAs.

115 talk about Hibernate's Level 1 cache, level 2 cache, and query cache.

A: The Hibernate Session provides a level-1 cache function, which is always valid by default. When an application saves persistent entities and modifies persistent entities, the Session does not submit the changes to the database immediately, instead, it is cached in the current Session unless the flush () method of the Session is called or the Session is closed through the close () method. Through level-1 caching, the interaction between programs and databases can be reduced to improve database access performance.

The SessionFactory level second-level cache is global, and all sessions can share this second-level cache. However, the second-level cache is disabled by default. You need to enable it and specify the second-level cache implementation class to be used (you can use the implementation provided by a third party ). Once the second-level cache is enabled and the entity class that requires second-level cache is set, SessionFactory caches each object of the accessed object class, unless the cached data exceeds the specified cache space.

Both level-1 cache and level-2 Cache cache the entire object and do not cache common attributes. If you want to cache common attributes, you can use query cache. The query cache caches HQL or SQL statements and their query results as key-value pairs. For the same query, you can directly obtain data from the cache. The query cache is disabled by default and must be enabled.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.