Java Interview--struts2 face test

Source: Internet
Author: User
Tags garbage collection i18n
1, struts2 work flow

The Struts 2 framework itself can be roughly divided into 3 parts:

Core Controller Filterdispatcher, business controller action, and user-implemented enterprise business logic components.

The core controller Filterdispatcher is the foundation of the Struts 2 framework,

Contains the control processes and processing mechanisms within the framework.

The Business controller action and business logic components are required to be implemented by the user themselves.

While developing action and business logic components, users also need to write related configuration files.

For use by the core controller filterdispatcher.

The Struts 2 workflow is simple compared to struts 1, essentially the same as the WebWork framework,

So struts 2 is an upgraded version of WebWork. The basic summary process is as follows:

1, the client initializes a request to the servlet container;

2. This request passes through a series of filters (filter)

(These filters have an optional filter called Actioncontextcleanup,

This filter is useful for integrating STRUTS2 with other frameworks, such as: Sitemesh Plugin)

3, then Filterdispatcher is called,

     Filterdispatcher ask Actionmapper to decide if you need to call an action

4. If Actionmapper decides to call an action,

     Filterdispatcher the processing of the request to Actionproxy

5, Actionproxy through the configuration Manager to ask the framework of the configuration file,

     Find the action class that needs to be invoked

6, Actionproxy to create a actioninvocation instance.

7, the Actioninvocation instance uses the naming pattern to invoke,

     The call to the associated Interceptor (Intercepter) is involved before and after the action is invoked.

8. Once the action is completed, Actioninvocation is responsible for finding the corresponding return result according to the configuration in Struts.xml. The return result is usually (but not always, or perhaps another action chain) a JSP or freemarker template that needs to be represented. You can use the label inherited in the Struts2 frame during the presentation. In this process needs to involve actionmapper

9, the response is returned through the filter we configured in the Web.xml
10, if the Actioncontextcleanup is currently in use, then Filterdispatecher will not clean up sreadlocal actioncontext, if the actioncontextcleanup is not used, will be to clean up the sreadlocals. 2. The design model of struts

MVC pattern: When a Web application starts, it loads and initializes the Actionservler. When a user submits a form, a configured Actionform object is created and filled in with the corresponding data in the form. Actionservler determines whether form validation is required based on the configured settings of the Struts-config.xml file and, if necessary, selects the action to which the request will be sent if the validate () is invoked actionform, if the action does not exist, Actionserv Let will create this object first and then invoke the Execute () method of the action. Execute () obtains the data from the Actionform object, completes the business logic, returns a Actionforward object, and actionservlet the client request to the JSP component specified by the Actionforward object. Actionforward the JSP specified by the object
into a Dynamic Web page, returned to the customer. 3. The difference between interceptor and filter

1, the Interceptor is based on the Java reflection mechanism, and the filter is based on function callback.
2, the filter relies on the servlet container, and the interceptor does not depend on the servlet container.
3. The interceptor can only function on the action request, and the filter works on almost any request.
4, the interceptor can access the action context, value stack objects, and filters can not.
5. In the life cycle of the action, the interceptor can be invoked multiple times, and the filter can only be invoked once when the container is initialized. 4. Comparison of Struts1 in Struts2

1, Action class:
STRUTS1 requires the action class to inherit an abstract base class. A common problem with Struts1 is programming with abstract classes rather than interfaces.
The Struts 2 action class can implement an action interface or implement other interfaces to make optional and customized services possible. STRUTS2 provides a actionsupport base class to implement commonly used interfaces. The action interface is not required, and any object with an Execute identity can be used as a Struts2 action object.

2, Threading mode:
The Struts1 action is a singleton pattern and must be thread-safe because only one instance of the action handles all requests. A single example strategy limits what Struts1 action can do, and is particularly cautious when developing. The action resource must be thread safe or synchronized.
The Struts2 action object produces an instance of each request, so there is no thread-safe issue. (In fact, the servlet container produces many disposable objects for each request, and does not cause performance and garbage collection issues)
3. Servlet dependencies:
The Struts1 action relies on the servlet API because when an Action is invoked HttpServletRequest and HttpServletResponse are passed to the Execute method.
The Struts 2 action does not depend on the container, allowing the action detach container to be tested alone. If necessary, the STRUTS2 action can still access the initial request and response. However, other elements reduce or eliminate the need for direct access to Httpservetrequest and HttpServletResponse.

4. Testability:
A major problem with testing the STRUTS1 action is that the Execute method exposes the servlet API (which makes the test dependent on the container). A third-party extension--struts testcase--provides a set of Struts1 mock objects (for testing).
The Struts 2 action can be tested by initializing, setting properties, calling methods, and "Dependency injection" support also makes testing easier.

5. Capture Input:
Struts1 uses the Actionform object to capture the input. All Actionform must inherit a base class. Because other JavaBean cannot be used as actionform, developers often create redundant class capture inputs. Dynamic Beans (Dynabeans) can be used as a choice to create a traditional actionform, but a developer may be recreating (creating) an already existing javabean (still causing a redundant javabean).
Struts 2 eliminates the need for a second input object by using the action attribute directly as an input property. The input property may be a rich object type with its own (child) attribute. The action attribute can be accessed through taglibs on a Web page. STRUTS2 also supports Actionform mode. Rich object types, including business objects, that can be used as input/output objects. This modeldriven feature simplifies taglib references to pojo input objects.

6. Expression Language:
Struts1 integrates Jstl, so use Jstl EL. This El has a basic object graph traversal, but the support for collections and indexed properties is weak.
Struts2 can use Jstl, but it also supports a more powerful and flexible expression language-"Object Graph notation Language" (OGNL).

7, bound values to the page (view):
Struts 1 uses the standard JSP mechanism to bind objects to the page to access them.
Struts 2 uses "Valuestack" technology to enable taglib to access values without having to bind your page (view) to the object. The Valuestack policy allows pages (view) to be reused through a series of properties with the same name but different types.

8. Type conversion:
The Struts 1 Actionform properties are usually string types. Struts1 uses commons-beanutils for type conversions. Each class has a converter that is not configurable for each instance.
STRUTS2 uses OGNL for type conversions. A converter that provides basic and commonly used objects.

9. Check:
Struts 1 supports manual checksums in the Actionform validate method, or by Commons Validator extensions. The same class can have different checksum content, but cannot validate child objects.
STRUTS2 supports validation through the Validate method and the Xwork checksum framework. The Xwork validation Framework supports chain checksum properties using the checksum content checksum defined for the attribute class type

10, action execution of control:
STRUTS1 supports each module with a separate request processors (lifecycle), but all the action in the module must share the same life cycle.
STRUTS2 supports creating different lifecycles for each action through the Interceptor Stack (Interceptor Stacks). The stack can be used in conjunction with different action as needed. 5, why to use Struts2 Struts2 is based on the MVC architecture, the framework structure is clear, the development process is at a glance, the developer can control the development process well. Use OGNL for parameter passing. Powerful interceptors to test easily extensible plug-in mechanisms modular management of global results and declarative exception 6, STRUTS2 has the advantages.

1 The application of Struts2 in software design can be independent of the Servlet API and the Struts API. This design of STRUTS2 is a non-invasive design;

2 Interceptor, to achieve such functions as parameter interception injection;

3 The type converter can convert the special request parameter to the required type;

4 A variety of performance layer technology, such as: JSP, freemarker, velocity and so on;

5 The STRUTS2 input checksum can be used to verify the specified method;

6 provides the global scope, package scope and action scope of the internationalization of resource file management implementation 7, Struts2 is how to start.

The STRUTS2 framework is initiated through filter, that is, Strutsprepareandexecutefilter, which is the core filter for STRUTS2, and 8, the core controller of the STRUTS2 framework. It has any effect.

1) The core controller of the STRUTS2 framework is strutsprepareandexecutefilter.

2) Function:
is responsible for intercepting all user requests specified by/*, which filter the user's request when the user requests to arrive. By default, if the user requests a path

Without a suffix or suffix to the. Action end, the request is transferred to the STRUTS2 framework, or the STRUTS2 framework skips the processing of the request.

You can modify the suffix of an action by using the constant "struts.action.extension", such as:

If a user needs to specify more than one request suffix, multiple suffixes are separated by commas (,).

9, the struts2 configuration file loading sequence.

Struts.xml--> struts.properties

Constants can be configured in Struts.xml or struts.properties, and if the same constant is configured in multiple files, the constant value that is configured in the latter file overrides the constant value that was configured in the previous file.

The role of the Struts.xml file: Notifies the STRUTS2 frame to load the corresponding action resource 10, STRUTS2 constant modification.

Constants can be configured in Struts.xml or Struts.properties, and the two configurations are as follows:

1 Configure constants in Struts.xml files

2 to configure constants in Struts.properties (struts.properties files are placed under SRC):

Struts.action.extension=do 11, struts2 How to access HttpServletRequest, HttpSession, servletcontext three domain objects.

Programme I:

HttpServletRequest request =servletactioncontext.getrequest ();

HttpServletResponse response =servletactioncontext.getresponse ();

HttpSession session= request.getsession ();

ServletContext Servletcontext=servletactioncontext.getservletcontext ();

Programme II:

class implements Servletrequestaware,servletresponseaware,sessionaware,servletcontextaware

Note: The framework automatically passes in the corresponding domain object 12, how Struts2 manages the action. What is the benefit of this management style.

The STRUTS2 framework uses packages to manage actions, and the package is very similar to the class packages in Java.

Mainly used to manage a set of business functions related to the action. In practical applications, we should put a set of business functions related to the action under the same package. 13, Struts2 in the default package Struts-default what role.

1 Struts-default package is built by struts, it defines many interceptors and result types within the struts2, and Struts2 many core functions are implemented through these built-in interceptors, such as: from the request

The request parameters are encapsulated into action, file uploads, data validation, and so on, and are implemented through interceptors. When the package inherits the Struts-default package, you can use STRUTS2 to provide us with these features.

2 Struts-default package is defined in Struts-default.xml, Struts-default.xml is also Struts2 default profile. Struts2 automatically loads struts-default.xml files each time.

3 usually each package should inherit the Struts-default package. 14, Struts2 How to verify the method specified.

1) The Validate () method verifies all methods in the action that are identical to the Execute method signature;

2 to verify that the specified method is implemented by overriding the ValidateXxx () method, ValidateXxx () only validates the method named XXX in the action. Where the first letter of XXX should be capitalized;

3 When a data checksum fails, the Addfielderror () method is invoked to add validation failure information to the fielderrors of the system (in order to use the Addfielderror () method, the action can inherit actionsupport) if the system Fielderrors contains the failure information, STRUTS2 forwards the request to result named input;

4 in the input view, you can display the failure information.

5 The first execution validatexxxx ()->validate ()-> If there is an error, the specified page will be forwarded, and if not, the Action::execute () method 15, Struts2 default to solve the Get and post submission method of garbled problem.

No. The Struts.i18n.encoding=utf-8 attribute value can only parse the garbled problem under post submission. 16, please write the struts2 of at least 5 of the default interceptor.

FileUpload provides file upload function

i18n records User-selected locale

Cookies are used as name,value to refer to cookies.

The checkbox adds the CheckBox automatic Processing code, sets the contents of the unchecked checkbox to False, and the HTML does not commit the unchecked checkbox by default.

Chain lets the properties of the previous action be accessed by the next action, now in combination with the chain type of result ().

The alias converts request parameters between different requests in different names, the request content unchanged 17, the principle and life cycle of the value stack valuestack.

1 valuestack throughout the life cycle of the Action, saved in the request domain, so the valuestack is the same as the life cycle of the request. When Struts2 accepts a request, it quickly creates a actioncontext,

Valuestack,action. The action is then stored in the Valuestack, so the instance variable of the action can be accessed by OGNL. When the request comes, the action, the Valuestack Life begins, the request ends, the action, the Valuestack life ends;

2 action is a number of cases, and the servlet is not the same, Servelt is a single case;

3 each action has a corresponding value stack, the value stack holds the data type is an instance of the action, as well as the action of the instance variables, the action object is saved by default on the stack top;

4) Valuestack is essentially a ArrayList;

5 The following mappings will be pressed into the Contextmap for contextmap,struts:

Parameters: This Map contains request parameters for the current request

Request: This map contains all the properties in the current request object session: This map contains all the properties in the current session object

Application: This Map contains all the properties in the current Application object

attr: The Map retrieves an attribute in the following order: request, Session, application

6 Use OGNL Access value stack content, do not need #, and access to request, session, application, attr, need to add #;

7 Note: In Struts2, ognl expressions need to be used with struts tags. Such as:

8 refer to the OGNL expression in the Struts2 configuration file, referencing the value of the value stack, using the "$" instead of # or%; 18, Actioncontext, ServletContext, PageContext difference.

1 Actioncontext is the context of the current action, through Actioncontext can get to the request, session, ServletContext and other action-related objects of reference;

2 ServletContext is a domain object, there is only one servletcontext in a Web application, the lifecycle accompanies the whole Web application;

3 PageContext is the most important JSP in a built-in object, you can get the application of other domain objects through the PageContext, while it is a domain object, the scope of action only for the current page, at the end of the current page, PageContext destroy,

The lifecycle is the smallest of the JSP four domain objects. 19. What kinds of results are in the type attribute of result.

Altogether 10 kinds:

Dispatcher

Struts default result type, the control is forwarded to a resource in the application can not forward control to an external resource, if you need to direct control weights to an external resource, you should use

REDIRECT Result type

Redirect redirect the response to another resource (including an external resource)

Redirectaction redirect the response to another Action

Freemarker, Velocity, chain, Httpheader, XSLT, plaintext, stream 20, Interceptor lifecycle and work process.

1 Each interceptor is a Java class that implements the Interceptor interface;

2 init (): The method is called immediately after the Interceptor is created, and it is invoked only once in the life cycle of the interceptor. The necessary initialization of related resources can be done in the method;

3) Intercept (actioninvocation invocation): Each intercept an action request, this method will be called once;

4) Destroy: The method will be invoked before the interceptor is destroyed, and it is only invoked once in the life cycle of the interceptor;

5 There are 18 interceptors built into the struts2. 21, Struts2 How to complete the file upload.

1, JSP page:

1 JSP page upload file components: If you need to upload multiple files at a time, you must use multiple file tags, but their names must be the same, namely:

The value of name= "XXX" must be the same;

2 must set the Enctype property of the form to: Multipart/form-data;

3 The method of the form must be post, because the data submitted by post is in the body of the message without the size limit.

2, the corresponding action:

1 Add 3 new and file upload related attributes in Action;

2 If you are uploading a single file, the type of the Uploadimage attribute is Java.io.File, which represents the uploaded file, and the second and third attribute types are String, which represent the upload text, respectively.

The file name and file type of the item are defined in the following ways:

The name of the JSP page file component +contenttype, the name of the JSP page file component +filename

3 If you upload multiple files, you can use the array or List 22, struts works

1, initialization, read struts-config.xml, web.xml configuration files (all configuration file initialization)
2, send HTTP request, the client sends the request with. Do End
3, fill Formbean (Instantiate, reset, fill data, verify, Save)
4. Forward the request to action (the Execute () method that invokes the action)
5, processing business (you can call the background class, return Actionforward object)
6. Return target Response object (return from action to Actionservlet)
7. Convert HTTP request to target Response object (lookup response, based on returned forward keyword)
8, HTTP response, return to the JSP page 23, in their own words to briefly explain the struts2 of the implementation process.

1, the client browser issued an HTTP request.

2, according to the Web.xml configuration, the request is filterdispatcher receive.

3. According to the Struts.xml configuration, find the action class and method that needs to be invoked, and inject the value into Aciton through the IOC way.

4. The action calls the business logic component to handle the business logic, which includes form validation.

5, action execution completed, according to the configuration in Struts.xml find the corresponding return results result, and jump to the appropriate page.

6, return HTTP response to the client browser.

Related Article

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.