שאלות ותשובות לראיון ב-Struts2

Struts2 הוא אחד מהפריימוורקים המפורסמים לפיתוח אפליקציות ווב ב-Java. לאחרונה כתבתי הרבה מדריכי Struts2 ובפוסט הזה, אני מפרט מספר שאלות ראיון Struts2 חשובות עם תשובות כדי לעזור לך בראיון.

שאלות ראיון Struts2

  1. מהו Struts2?
  2. מהם ההבדלים בין Struts1 לבין Struts2 או כיצד Struts2 טוב יותר מ-Struts1?
  3. מהם הרכיבים העיקריים של Struts2?
  4. מהו מפריצה (interceptor) ב-Struts2?
  5. איזה תבנית עיצוב מיושמת על ידי מפריצות (interceptors) ב-Struts2?
  6. מהם הדרכים השונות ליצור Action classes ב-Struts2?
  7. האם פעולת Struts2 ומפריצים הם thread safe?
  8. איזה מחלקת הפרונט קונטרולר ב-Struts2?
  9. מהם היתרונות של מפריצים ב-Struts2?
  10. מהו ValueStack ו-OGNL?
  11. ציין כמה הערות שימושיות שהוזכרו ב- Struts2?
  12. ספק קבועים חשובים ב- Struts2 שהשתמשת בהם?
  13. מהו שימוש ה־ namespace במיפוי פעולה ב- Struts2?
  14. איזה interceptor אחראי למיפוי של פרמטרי בקשה למאפייני Java Bean של מחלקת פעולה?
  15. איזה interceptor אחראי לתמיכה ב- i18n?
  16. מה ההבדל בשימוש בממשק הפעולה ובמחלקת ActionSupport עבור מחלקות הפעולה שלנו, איזה אחת אתה מעדיף?
  17. איך ניתן לקבל אובייקטי Servlet API Request, Response, HttpSession וכו' במחלקות פעולה?
  18. מהו השימוש של interceptor execAndWait?
  19. מהו השימוש של interceptor token ב- Struts2?
  20. איך ניתן לשלב log4j ביישום Struts2?
  21. מהם תגי Struts2 השונים? איך ניתן להשתמש בהם?
  22. מהו ממיר טיפוס מותאם אישית ב- Struts2?
  23. כיצד ניתן לכתוב אינטרספטור מותאם אישית ולמפתו עבור פעולה?
  24. מהו מחזור חיי interceptor?
  25. מהו מחסנית interceptor?
  26. מהו חבילת ה- struts-default ומהם היתרונות שלה?
  27. מהו הסיומת ברירת המחדל עבור URI הפעולה של Struts2 וכיצד ניתן לשנות אותה?
  28. מהו מיקום ברירת המחדל של עמודי התוצאה וכיצד ניתן לשנות אותו?
  29. כיצד ניתן להעלות קבצים באפליקציה של Struts2?
  30. מהם הפרקטיקות הטובות לעקוב אחריהן בפיתוח אפליקציות של Struts2?
  31. כיצד ניתן לטפל בחריגות שמושלכות על ידי האפליקציה ב- Struts2?

שאלות ותשובות לראיון על Struts2

  1. מה זה Struts2?

    Apache Struts2 הוא מסגרת קוד פתוח לבניית אפליקציות אינטרנט בשפת Java. Struts2 מבוסס על מסגרת OpenSymphony WebWork. המסגרת של Struts2 שופרה מאוד מ Struts1 וזה גורם לה להיות יותר גמישה, קלה לשימוש ולהרחבה. הרכיבים העיקריים של Struts2 הם פעולה (Action), אינטרספטורים ועמודי תוצאה (Result pages). Struts2 מספקת דרכים רבות ליצירת כיתות פעולה ולתצורתן דרך struts.xml או באמצעות הערות. אנו יכולים ליצור אינטרספטורים משלנו למשימות נפוצות. Struts2 מגיעה עם הרבה תגיות ומשתמשת בשפת הביטוי OGNL. אנו יכולים ליצור ממירי סוג משלנו כדי להציג עמודי תוצאה. עמודי התוצאה יכולים להיות JSPs ותבניות FreeMarker.

  2. מהם ההבדלים בין Struts1 ל-Struts2 או איך Struts2 טובה יותר מ-Struts1?

    Struts2 מתוכננת לשפר את החסרונות של Struts1 ולהפוך אותה למודולארית ומתפתחת יותר. כמה מההבדלים המפורטים הם:

    רכיבים Struts1 Struts2
    מחלקות פעולה מחלקות פעולה של Struts1 חייבות להרחיב מחלקה אבסטרקטית שזה מקשה על ההרחבה. מחלקות פעולה של Struts2 גמישות ואפשר ליצור אותן על ידי הממשק האקשיון Action, הרחבה של מחלקת ActionSupport או פשוט על ידי ביצוע של שיטת execute().
    בטיחות התהליך מחלקות הפעולה של Struts1 הן סינגלטון ולא בטוחות לשימוש ברצף, מה שדורש תשומת לב נוספת מצד המפתח כדי למנוע תופעות צד. מחלקות פעולה של Struts2 מתווצרות לפי בקשה, כך שאין רצפים מרובים ומבטיחות בטיחות התהליך.
    התממשקות עם API של Servlet API של Struts1 קשורות עם סרבלט API ואובייקטי דרישה ותגובה מועברים לשיטת הביצוע של מחלקות הפעולה. API של Struts2 נקשרות באופן פחות צמוד ל-Servlet API וממפה אוטומטית את נתוני גולמי הטופס למאפייני מחלקת הפעולה ב-Java שבדרך כלל אנו משתמשים בהם. אם נדרש לנו עדיין הפניה למחלקות API של Servlet, ישנם ממשקים "מודעים" עבור זה.
    בדיקות מחלקות הפעולה של Struts1 קשות לבדיקה בשל קישור חזק עם סרבלט API. מחלקות פעולה של Struts2 כמו מחלקות Java רגילות וניתן לבדוק אותם בקלות על ידי הפעלה והגדרת מאפייניהם.
    מיפוי פרמטרים של הבקשה Struts1 מחייבת אותנו ליצור מחלקות ActionForm כדי להחזיק את הפרמטרים של הבקשה ואנו צריכים להגדיר אותן בקובץ התצורה של Struts. מיפוי הפרמטרים של Struts2 נעשה בזמן ריצה וכל שצריך הוא להגדיר מאפייני Java Bean במחלקות הפעולה או לממש את הממשק ModelDriven כדי לספק את שם מחלקת ה-Java Bean שישמש למיפוי.
    תמיכת תגיות Struts1 משתמשת בתגיות JSTL ולכן מוגבלת. Struts2 משתמשת ב-OGNL ומספקת סוגים שונים של תגי UI, שליטה ונתונים. זה יותר גמיש וקל לשימוש.
    אימות Struts1 תומך באימות דרך שיטת validate() ידנית. Struts2 תומך באימות ידני וגם באינטגרציה עם מערכת האימות.
    עיבוד תצוגות Struts1 משתמשת בטכנולוגיית JSP סטנדרטית לספק ערכי Bean לדפי JSP עבור הצגה. Struts2 משתמשת ב-ValueStack לאחסון פרמטרי בקשה ומאפיינים וניתן להשתמש ב-OGNL ובתגי Struts2 כדי לגשת אליהם.
    תמיכה במודולים מודולים של Struts1 מורכבים לעיצוב ונראים כמו פרויקטים נפרדים. Struts2 מספקת הגדרת "שם מרחב" לחבילות כדי ליצור מודולים בקלות.
  3. מהם רכיבי Struts2 המרכזיים?

    רכיבי Struts2 המרכזיים הם:

    1. כיתות פעולה
    2. מפרצים
    3. עמודי תוצאה, JSP של תבניות FreeMarker
    4. ValueStack, OGNL וספריות Tag
Struts 2 Architecture Diagram
  1. מהו המפריצים (interceptor) ב־Struts2?

    המפריצים (interceptors) הם עמוד התוֹמֵכִים של מסגרת Struts2. המפריצים של Struts2 אחראים לרוב העיבוד הנעשה על ידי המסגרת, כגון העברת פרמטרים של בקשה למחלקות פעולה, ביצוע בקשת API של Servlet, העברת הבקשה, התגובה, הסשן של ה־Servlet למחלקות פעולה, תמיכה באימות, בתמיכה ב־i18n, ועוד. ActionInvocation אחראית לאיטום של מחלקות פעולה ומפריצים ולהפעלתם בסדר. השיטה החשובה ביותר לשימוש ב־ActionInvocation היא השיטה invoke() ששומרת על שרשרת המפריצים ומפעילה את המפריץ או הפעולה הבאה. זהו אחד מהדוגמאות הטובות ביותר לתבנית Chain of Responsibility במסגרות Java EE.

  2. איזו תבנית עיצוב מיושמת על ידי אינטרספטורים של Struts2?

Struts2 interceptors are based on intercepting filters design pattern. The invocation of interceptors in interceptor stack closely resembles Chain of Responsibility design pattern.
  1. מהם הדרכים השונות ליצירת מחלקות פעולה ב־Struts2?

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.
  1. האם פעולת Struts2 ו־interceptors הם thread safe?

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.
  1. איזו מחלקה היא ה־Front Controller ב־Struts2?

`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.
  1. מהם היתרונות של אינטרספטורים ב־Struts2?

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.
  1. מהו ה־ValueStack וְ־OGNL?

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.
  1. ציין כמה הערות שימושיות שהוצגו ב-Struts2?

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
  1. ספק כמה קבועים חשובים ב-Struts2 שהשתמשת בהם?

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>
```
  1. מהו השימוש של מרחב שמות במיפוי פעולה ב־Struts2?

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.
  1. איזה אינטרספטור אחראי למיפוי של פרמטרי בקשה לתכונות כיתה של Java Bean במחלקת פעולה?

`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.
  1. איזה interceptor אחראי על תמיכה ב-i18n?

`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.
  1. מה ההבחנה בין שימוש בממשק הפעולה ובמחלקת ActionSupport למחלקות הפעולה שלנו, איזו מהן אתה מעדיף?

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.
  1. כיצד ניתן לקבל את אובייקטי הבקשה, התגובה, HttpSession וכו' של API של Servlet במחלקות הפעולה?

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.
  1. מהו השימוש של מתיחת ה-interceptor execAndWait?

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.
  1. מהו השימוש של אינטרספטור טוקן ב-Struts2?

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.
  1. איך ניתן לשלב את log4j באפליקציית Struts2?

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).
  1. מהם התגיות השונות של Struts2? כיצד אנו יכולים להשתמש בהן?

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).
  1. מהו ממיר סוג מותאם אישית ב Struts2?

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).
  1. איך נוכל לכתוב אינטרספטור משלנו ולמפות אותו עבור פעולה?

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).
  1. מהו מחזור החיים של אינטרספטור?

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.
  1. מהו מחסנית אינטרספטור?

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.
  1. מהו החבילה של struts-default ומהם היתרונות שלה?

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.
  1. מהו הסיומת ברירת המחדל ל-URI של פעולת Struts2 וכיצד אנו יכולים לשנות אותה?

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>
```
  1. מהו המיקום הברירת מחדל של עמודי התוצאה וכיצד ניתן לשנות אותו?

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.
  1. כיצד ניתן להעלות קבצים באפליקציה של Struts2?

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).
  1. מהן הפרקטיקות הטובות לעקוב אחריהן בעת פיתוח אפליקציות ב-Struts2?

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.
  1. כיצד ניתן לטפל בחריגות שנזרקות על ידי האפליקציה ב-Struts2?

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

זהו כל השאלות והתשובות לראיון בנוגע ל-Struts2, אם יש לך שאלה חשובה שלא כללתי, אשמח לדעת דרך התגובות.

Source:
https://www.digitalocean.com/community/tutorials/struts2-interview-questions-and-answers