Struts2 ist eines der bekannten Frameworks zur Entwicklung von Webanwendungen in Java. Vor kurzem habe ich viele Struts2-Tutorials geschrieben, und in diesem Beitrag liste ich einige wichtige Struts2-Interviewfragen mit Antworten auf, um Ihnen bei Ihrem Interview zu helfen.
Struts2-Interviewfragen
- Was ist Struts2?
- Was sind die Unterschiede zwischen Struts1 und Struts2 oder wie ist Struts2 besser als Struts1?
- Was sind die Kernkomponenten von Struts2?
- Was ist ein Interceptor in Struts2?
- Welches Entwurfsmuster wird von Struts2-Interceptors implementiert?
- Auf welche verschiedenen Arten können Action-Klassen in Struts2 erstellt werden?
- Sind Struts2-Aktionen und Interceptors thread-sicher?
- Welche Klasse ist der Front-Controller in Struts2?
- Was sind die Vorteile von Interceptors in Struts2?
- Was ist ValueStack und OGNL?
- Nennen Sie einige nützliche Annotationen, die in Struts2 eingeführt wurden?
- Nennen Sie einige wichtige Struts2-Konstanten, die Sie verwendet haben?
- Was ist die Verwendung von Namespace in der Aktionszuordnung in Struts2?
- Welcher Interceptor ist für das Zuordnen von Anforderungsparametern zu den Eigenschaften der Aktionsklassen-Java-Beans verantwortlich?
- Welcher Interceptor ist für die i18n-Unterstützung verantwortlich?
- Was ist der Unterschied zwischen der Verwendung des Action-Interfaces und der ActionSupport-Klasse für unsere Aktionsklassen, welche würden Sie bevorzugen?
- Wie können wir Servlet-API-Anforderung, Antwort, HttpSession usw. Objekte in Aktionsklassen erhalten?
- Was ist die Verwendung des execAndWait-Interceptors?
- Was ist die Verwendung des Token-Interceptors in Struts2?
- Wie können wir log4j in einer Struts2-Anwendung integrieren?
- Welche verschiedenen Struts2-Tags gibt es? Wie können wir sie verwenden?
- Was ist ein benutzerdefinierter Typkonverter in Struts2?
- Wie können wir unseren eigenen Interceptor schreiben und für eine Aktion zuordnen?
- Was ist der Lebenszyklus eines Interceptors?
- Was ist ein Interceptor-Stack?
- Was ist das struts-default Paket und welche Vorteile hat es?
- Was ist das Standard-Suffix für Struts2 Aktions-URIs und wie können wir es ändern?
- Was ist der Standardort für Ergebnisseiten und wie können wir ihn ändern?
- Wie können wir Dateien in einer Struts2-Anwendung hochladen?
- Welche bewährten Methoden sollten beim Entwickeln einer Struts2-Anwendung befolgt werden?
- Wie können wir Ausnahmen behandeln, die von Anwendungen in Struts2 ausgelöst werden?
Struts2 Interviewfragen und Antworten
-
Was ist Struts2?
Apache Struts2 ist ein Open-Source-Framework zum Erstellen von Webanwendungen in Java. Struts2 basiert auf dem OpenSymphony WebWork-Framework. Es wurde stark verbessert im Vergleich zu Struts1, was es flexibler, einfacher zu verwenden und zu erweitern macht. Die Kernkomponenten von Struts2 sind Action, Interceptors und Ergebnisseiten. Struts2 bietet viele Möglichkeiten, Action-Klassen zu erstellen und sie über struts.xml oder über Annotationen zu konfigurieren. Wir können eigene Interceptors für gemeinsame Aufgaben erstellen. Struts2 wird mit vielen Tags geliefert und verwendet die OGNL-Ausdruckssprache. Wir können eigene Typkonverter erstellen, um Ergebnisseiten zu rendern. Ergebnisseiten können JSPs und FreeMarker-Vorlagen sein.
-
Was sind die Unterschiede zwischen Struts1 und Struts2 oder warum ist Struts2 besser als Struts1?
Struts2 ist darauf ausgelegt, die Schwächen von Struts1 zu überwinden und es flexibler und erweiterbarer zu machen. Einige der bemerkenswerten Unterschiede sind:
Komponenten Struts1 Struts2 Action-Klassen Struts1-Aktionsklassen müssen eine abstrakte Klasse erweitern, was sie nicht erweiterbar macht. Struts2-Aktionsklassen sind flexibel, wir können sie implementieren, indem wir das Action-Interface verwenden, die ActionSupport-Klasse erweitern oder einfach die execute()-Methode haben. Thread-Sicherheit Struts1-Aktionsklassen sind Singleton und nicht thread-sicher, was vom Entwickler zusätzliche Vorsicht erfordert, um etwaige Nebenwirkungen aufgrund von Multithreading zu vermeiden. Struts2-Aktionsklassen werden pro Anfrage instanziiert, es gibt also kein Multithreading und sie sind thread-sicher. Servlet-API-Kopplung Struts1-APIs sind eng mit der Servlet-API gekoppelt, und Request- und Response-Objekte werden an die execute()-Methode der Aktionsklassen übergeben. Struts2-API ist locker mit der Servlet-API gekoppelt und ordnet die Formularbean-Daten automatisch den Eigenschaften der Aktionsklasse zu, die wir meistens verwenden. Wenn wir jedoch Referenzen auf Servlet-API-Klassen benötigen, gibt es *Aware-Schnittstellen dafür. Tests Struts1-Aktionsklassen sind aufgrund der Servlet-API-Kopplung schwer zu testen. Struts2-Aktionsklassen sind wie normale Java-Klassen und können leicht getestet werden, indem sie instanziiert und ihre Eigenschaften festgelegt werden. Mapping von Anforderungsparametern Struts1 erfordert, dass wir ActionForm-Klassen erstellen, um Anforderungsparameter zu halten, und wir müssen sie in der Struts-Konfigurationsdatei konfigurieren. Struts2-Anforderungsparameter werden dynamisch zugeordnet, und alles, was wir brauchen, sind Java-Bean-Eigenschaften in Aktionsklassen oder die Implementierung des ModelDriven-Interfaces, um den Java-Bean-Klassennamen für die Zuordnung bereitzustellen. Tag-Unterstützung Struts1 verwendet JSTL-Tags und ist daher begrenzt. Struts2 verwendet OGNL und bietet verschiedene Arten von UI-, Steuerungs- und Daten-Tags. Es ist vielseitiger und einfacher zu verwenden. Validierung Struts1 unterstützt Validierung durch manuelle validate()-Methode. Struts2 unterstützt sowohl manuelle Validierung als auch die Integration des Validierungsframeworks. Ansichtsrendering Struts1 verwendet die standardmäßige JSP-Technologie, um Bean-Werte an JSP-Seiten für Ansichten bereitzustellen. Struts2 verwendet den ValueStack, um Anforderungsparameter und Attribute zu speichern, und wir können OGNL und Struts2-Tags verwenden, um darauf zuzugreifen. Modulunterstützung Struts1-Module sind schwer zu gestalten und sehen aus wie separate Projekte. Struts2 bietet eine „Namespace“-Konfiguration für Pakete, um einfach Module zu erstellen. -
Was sind die Kernkomponenten von Struts2?
Die Kernkomponenten von Struts2 sind:
- Action-Klassen
- Interzeptoren
- Ergebnisseiten, JSP von FreeMarker-Vorlagen
- ValueStack, OGNL und Tag-Bibliotheken

-
Was ist ein Interceptor in Struts2?
Interceptors sind das Rückgrat des Struts2-Frameworks. Struts2-Interceptors sind für die meisten Verarbeitungsvorgänge des Frameworks verantwortlich, wie z.B. das Weiterleiten von Anforderungsparametern an Aktionsklassen, das Bereitstellen von Servlet-API-Anforderung, Antwort, Sitzung für Aktionsklassen, Validierung, i18n-Unterstützung usw. ActionInvocation ist dafür verantwortlich, Aktionsklassen und Interceptors zu verkapseln und sie in der Reihenfolge auszulösen. Die wichtigste Methode für die Verwendung in ActionInvocation ist die invoke()-Methode, die die Interceptor-Kette verfolgt und den nächsten Interceptor oder die nächste Aktion aufruft. Dies ist eines der besten Beispiele für das Muster der Verantwortungskette in Java-EE-Frameworks.
-
Welches Entwurfsmuster wird von Struts2-Interceptors implementiert?
Struts2 interceptors are based on intercepting filters design pattern. The invocation of interceptors in interceptor stack closely resembles Chain of Responsibility design pattern.
Struts2 provide different ways to create action classes.
1. By implementing Action interface
2. Using Struts2 @Action annotation
3. By extending ActionSupport class
4. Any normal java class with execute() method returning String can be configured as Action class.
Struts2 Action classes are thread safe because an object is instantiated for every request to handle it. Struts2 interceptors are singleton classes and a new thread is created to handle the request, so it's not thread safe and we need to implement them carefully to avoid any issues with shared data.
`org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter` is the Front Controller class in Struts2 and every request processing starts from this class. Earlier versions of Struts2 uses `org.apache.struts2.dispatcher.FilterDispatcher` as Front Controller class.
Some of the benefits of interceptors are:
- Interceptor plays a crucial role in achieving high level of separation of concerns.
- Struts2 interceptors are configurable, we can configure it for any action we want.
- We can create our own custom interceptors to perform some common tasks such as request params logging, authentication etc. This helps us in taking care of common tasks at a single location, achieving low maintenance cost.
- We can create interceptors stack to use with different actions.
ValueStack is the storage area where the application data is stored by Struts2 for processing the client requests. The data is stored in `ActionContext` objects that use ThreadLocal to have values specific to the particular request thread. Object-Graph Navigation Language (OGNL) is a powerful Expression Language that is used to manipulate data stored on the ValueStack. As you can see in architecture diagram, both interceptors and result pages can access data stored on ValueStack using OGNL.
Some of the important annotations introduced in Struts2 are:
1. @Action to create action class
2. @Actions to configure single class for multiple actions
3. @Namespace and @Namespaces for creating different modules
4. @Result for result pages
5. @ResultPath for configuring result pages location
Some of the Struts2 constants that I have used are:
1. **struts.devMode** to run our application in development mode. This mode does reload properties files and provides extra logging and debugging feature. It's very useful while developing our application but we should turn it off while moving our code to production.
2. **struts.convention.result.path** to configure the location of result pages. By default Struts2 look for result pages at {WEBAPP-ROOT}/{Namespace}/ and we can change the location with this constant.
3. **struts.custom.i18n.resources** to define global resource bundle for i18n support.
4. **struts.action.extension** to configure the URL suffix to for Struts2 application. Default suffix is .action but sometimes we might want to change it to .do or something else.
We can configure above constants in the struts.xml file like below.
```
<constant name="struts.devMode" value="true"></constant>
<constant name="struts.action.extension" value="action,do"></constant>
<constant name="struts.custom.i18n.resources" value="global"></constant>
<constant name="struts.convention.result.path" value="/"></constant>
```
Struts2 namespace configuration allows us to create modules easily. We can use namespace to separate our action classes based on their functionality, for example admin, user, customer etc.
`com.opensymphony.xwork2.interceptor.ParametersInterceptor` interceptor is responsible for mapping request parameters to the Action class java bean properties. This interceptor is configured in struts-default package with name "params". This interceptor is part of basicStack and defaultStack interceptors stack.
`com.opensymphony.xwork2.interceptor.I18nInterceptor` interceptor is responsible for i18n support in Struts2 applications. This interceptor is configured in struts-default package with name "i18n" and it's part of i18nStack and defaultStack.
We can implement Action interface to create our action classes. This interface has a single method execute() that we need to implement. The only benefit of using this interface is that it contains some constants that we can use for result pages, these constants are SUCCESS, ERROR, NONE, INPUT and LOGIN. ActionSupport class is the default implementation of Action interface and it also implements interfaces related to Validation and i18n support. ActionSupport class implements Action, Validateable, ValidationAware, TextProvider and LocaleProvider interfaces. We can override the validate() method of ActionSupport class to include field level validation login in our action classes. Depending on the requirements, we can use any of the approaches to creating Struts 2 action classes, my favorite is ActionSupport class because it helps in writing validation and i18n logic easily in action classes.
Struts2 action classes don't provide direct access to Servlet API components such as Request, Response, and Session. However, sometimes we need these access in action classes such as checking HTTP method or setting cookies in response. That's why Struts2 API provides a bunch of \*Aware interfaces that we can implement to access these objects. Struts2 API uses dependency injection to inject Servlet API components in action classes. Some of the important Aware interfaces are SessionAware, ApplicationAware, ServletRequestAware, and ServletResponseAware. You can read more about them in How to get [Servlet API Session in Struts2 Action Classes](/community/tutorials/get-servlet-session-request-response-context-attributes-struts-2-action) tutorial.
Struts2 provides execAndWait interceptor for long running action classes. We can use this interceptor to return an intermediate response page to the client and once the processing is finished, final response is returned to the client. This interceptor is defined in the struts-default package and implementation is present in `ExecuteAndWaitInterceptor` class. Check out [Struts2 execAndWait interceptor example](/community/tutorials/struts2-execandwait-interceptor-example-for-long-running-actions) to learn more about this interceptor and how to use it.
One of the major problems with web applications is the double form submission. If not taken care, double form submission could result in charging double amount to customer or updating database values twice. We can use a token interceptor to solve the double form submission problem. This interceptor is defined in the struts-default package but it's not part of any interceptor stack, so we need to include it manually in our action classes. Read more at [Struts2 token interceptor](/community/tutorials/struts2-token-interceptor-example) example.
Struts2 provides easy integration of log4j API for logging purpose, all we need to have is log4j configuration file in the WEB-INF/classes directory. You can check out the sample project at [Struts2 Log4j integration](/community/tutorials/struts2-and-log4j-integration-example-project).
Struts2 provides a lot of custom tags that we can use in result pages to create views for client request. These tags are broadly divided into three categories- Data tags, Control tags and UI tags. We can use these tags by adding these in JSP pages using taglib directive.
```
<%@ taglib uri="/struts-tags" prefix="s" %>
```
Some of the important Data tags are property, set, push, bean, action, include, i18n and text tag. Read more at [Struts2 Data Tags](/community/tutorials/struts-2-data-tags-example-tutorial). Control tags are used for manipulation and navigation of data from a collection. Some of the important Control tags are if-elseif-else, iterator, append, merge, sort, subset and generator tag. Read more at [Struts2 Control Tags](/community/tutorials/struts-2-control-tags-example-tutorial). Struts2 UI tags are used to generate HTML markup language, binding HTML form data to action classes properties, type conversion, validation, and i18n support. Some of the important UI tags are form, textfield, password, textarea, checkbox, select, radio and submit tag. Read more about them at [Struts2 UI Tags](/community/tutorials/struts-2-ui-tags-form-checkbox-radio-select-submit).
Struts2 support OGNL expression language and it performs two important tasks in Struts 2 – data transfer and type conversion. OGNL is flexible and we can easily extend it to create our own custom converter class. Creating and configuring custom type converter class is very easy. The first step is to fix the input format for the custom class. The second step is to implement the converter class. Type converter classes should implement `com.opensymphony.xwork2.conversion.TypeConverter` interface. Since in web application, we always get the request in form of String and send the response in the form of String, Struts 2 API provides a default implementation of TypeConverter interface, StrutsTypeConverter. StrutsTypeConverter contains two abstract methods – convertFromString to convert String to Object and convertToString to convert Object to String. For implementation details, read [Struts2 OGNL Example Tutorial](/community/tutorials/struts2-ognl).
We can implement `com.opensymphony.xwork2.interceptor.Interceptor` interface to create our own interceptor. Once the interceptor class is ready, we need to define that in struts.xml package where we want to use it. We can also create interceptor stack with our custom interceptor and defaultStack interceptors. After that we can configure it for action classes where we want to use our interceptor. One of the best example of using custom interceptor is to validate session, read more about it at [Struts2 Interceptor Tutorial](/community/tutorials/struts-2-interceptor-example).
Interceptor interface defines three methods - init(), destroy() and intercept(). init and destroy are the life cycle methods of an interceptor. Interceptors are Singleton classes and Struts2 initialize a new thread to handle each request. init() method is called when interceptor instance is created and we can initialize any resources in this method. destroy() method is called when application is shutting down and we can release any resources in this method. intercept() is the method called every time client request comes through the interceptor.
An interceptor stack helps us to group together multiple interceptors in a package for further use. struts-default package creates some of the mostly used interceptor stack - basicStack and defaultStack. We can create our own interceptor stack at the start of the package and then configure our action classes to use it.
struts-default is an abstract package that defines all the Struts2 interceptors and commonly used interceptor stack. It is advisable to extend this package while configuring our application package to avoid configuring interceptors again. This is provided to help developers by eliminating the trivial task of configuring interceptor and result pages in our application.
The default URI suffix for Struts2 action is .action, in Struts1 default suffix was .do. We can change this suffix by defining struts.action.extension constant value in our Struts2 configuration file as:
```
<constant name="struts.action.extension" value="action,do"></constant>
```
By default Struts2 looks for result pages in {WEBAPP-ROOT}/{Namespace}/ directory but sometimes we want to keep result pages in another location, we can provide struts.convention.result.path constant value in Struts2 configuration file to change the result pages location. Another way is to use @ResultPath annotation in action classes to provide the result pages location.
File Upload is one of the common tasks in a web application. That's why Struts2 provides built-in support for file upload through FileUploadInterceptor. This interceptor is configured in the struts-default package and provide options to set the maximum size of a file and file types that can be uploaded to the server. Read more about FileUpload interceptor at [Struts2 File Upload Example](/community/tutorials/struts-2-file-upload-example).
Some of the best practices while developing Struts2 application are:
1. Always try to extend struts-default package while creating your package to avoid code redundancy in configuring interceptors.
2. For common tasks across the application, such as logging request params, try to use interceptors.
3. Always keep action classes java bean properties in a separate bean for code reuse and implement ModelDriven interface.
4. If you have custom interceptor that you will use in multiple actions, create interceptor stack for that and then use it.
5. Try to divide your application in different modules with namespace configuration based on functional areas.
6. Try to use Struts2 tags in result pages for code clarify, if needed create your own type converters.
7. Use development mode for faster development, however make sure production code doesn't run in dev mode.
8. Use Struts2 i18n support for resource bundles and to support localization.
9. Struts2 provides a lot of places where you can have resource bundles but try to keep one global resource bundle and one for action class to avoid confusion.
10. struts-default package configures all the interceptors and creates different interceptor stacks. Try to use only what is needed, for example if you don't have localization requirement, you can avoid i18n interceptor.
Struts2 provides a very robust framework for exception handling. We can specify global results in packages and then map specific exceptions to these result pages. The exception mapping can be done at the global package level as well as the action level. It's a good idea to have exception result pages to provide some information to the user when some unexpected exception occurs that is not processed by the application. The sample configuration in the struts.xml file looks like below.
```
<package name="user" namespace="/" extends="struts-default">
<global-results>
<result name="exception">/exception.jsp</result>
<result name="runtime_exception">/runtime_exception.jsp</result>
<result name="error">/error.jsp</result>
</global-results>
<global-exception-mappings>
<exception-mapping exception="java.lang.Exception" result="exception"></exception-mapping>
<exception-mapping exception="java.lang.Error" result="error"></exception-mapping>
<exception-mapping exception="java.lang.RuntimeException" result="runtime_exception"></exception-mapping>
</global-exception-mappings>
<action name="myaction" class="com.journaldev.struts2.exception.MyAction">
</action>
<action name="myspecialaction" class="com.journaldev.struts2.exception.MySpecialAction">
<exception-mapping exception="java.io.IOException" result="login"></exception-mapping>
<result name="login">/error.jsp</result>
</action>
</package>
```
Read more at [Struts2 Exception Handling Example](/community/tutorials/struts2-exception-handling-example-tutorial).
Das ist alles für die Struts2-Interviewfrage und -antworten. Wenn Sie auf eine wichtige Frage stoßen, die ich übersehen habe, lassen Sie es mich bitte über Kommentare wissen.
Source:
https://www.digitalocean.com/community/tutorials/struts2-interview-questions-and-answers