웹사이트 검색

Struts2 인터뷰 질문 및 답변


Struts2는 Java에서 웹 애플리케이션을 개발하기 위한 유명한 프레임워크 중 하나입니다. 최근에 저는 많은 Struts2 Tutorials를 작성했으며 이 게시물에서는 인터뷰에 도움이 되는 답변과 함께 중요한 Struts2 인터뷰 질문 중 일부를 나열하고 있습니다.

Struts2 인터뷰 질문

  1. Struts2란 무엇입니까?
  2. Struts1과 Struts2의 차이점 또는 Struts2가 Struts1보다 나은 점은 무엇입니까?
  3. Struts2 핵심 구성 요소는 무엇입니까?
  4. Struts2에서 인터셉터란 무엇입니까?
  5. Struts2 인터셉터에 의해 구현되는 디자인 패턴은 무엇입니까?
  6. Struts2에서 Action 클래스를 생성하는 다른 방법은 무엇입니까?
  7. Struts2 액션과 인터셉터는 스레드로부터 안전합니까?
  8. Struts2의 Front Controller는 어떤 클래스입니까?
  9. Struts2에서 인터셉터의 이점은 무엇입니까?
  10. ValueStack 및 OGNL이란 무엇입니까?
  11. Struts2에 도입된 유용한 주석의 이름을 말하시겠습니까?
  12. 사용한 중요한 Struts2 상수를 제공하시겠습니까?
  13. Struts2의 액션 매핑에서 네임스페이스의 용도는 무엇입니까?
  14. 어떤 인터셉터가 요청 매개변수를 액션 클래스 Java Bean 속성에 매핑하는 역할을 합니까?
  15. i18n 지원을 담당하는 인터셉터는 무엇입니까?
  16. 액션 클래스에 대해 Action 인터페이스와 ActionSupport 클래스를 사용할 때의 차이점은 무엇입니까? 어떤 것을 선호하십니까?
  17. 액션 클래스에서 Servlet API 요청, 응답, HttpSession 등의 개체를 어떻게 얻을 수 있습니까?
  18. execAndWait 인터셉터의 용도는 무엇입니까?
  19. Struts2에서 토큰 인터셉터의 용도는 무엇입니까?
  20. Struts2 애플리케이션에 log4j를 어떻게 통합할 수 있습니까?
  21. 다른 Struts2 태그는 무엇입니까? 어떻게 사용할 수 있나요?
  22. Struts2의 사용자 정의 유형 변환기는 무엇입니까?
  23. 우리만의 인터셉터를 어떻게 작성하고 행동을 위해 매핑할 수 있습니까?
  24. 인터셉터의 수명 주기는 무엇입니까?
  25. 인터셉터 스택이란 무엇입니까?
  26. struts-default 패키지는 무엇이며 이점은 무엇입니까?
  27. Struts2 작업 URI의 기본 접미사는 무엇이며 어떻게 변경할 수 있습니까?
  28. 결과 페이지의 기본 위치는 무엇이며 어떻게 변경할 수 있습니까?
  29. Struts2 애플리케이션에서 어떻게 파일을 업로드할 수 있습니까?
  30. Struts2 애플리케이션을 개발하는 동안 따라야 할 모범 사례는 무엇입니까?
  31. Struts2에서 애플리케이션이 발생시킨 예외를 어떻게 처리할 수 있습니까?

Struts2 인터뷰 질문 및 답변

  1. What is Struts2?

    Apache Struts2 is an open source framework to build web applications in Java. Struts2 is based on OpenSymphony WebWork framework. It’s highly improved from Struts1 and that makes it more flexible, easy to use and extend. The core components of Struts2 are Action, Interceptors and Result pages. Struts2 provides many ways to create Action classes and configure them via struts.xml or through annotations. We can create our own interceptors for common tasks. Struts2 comes with a lot of tags and uses OGNL expression language. We can create our own type converters to render result pages. Result pages can be JSPs and FreeMarker templates.

  2. What are the differences between Struts1 and Struts2 or how Struts2 is better than Struts1?

    Struts2 is designed to overcome the shortcomings of Struts1 and to make it more flexible, extendable. Some of the noticeable differences are:

    Components Struts1 Struts2
    Action Classes Struts1 action classes are forced to extend an Abstract Class that makes it not extendable. Struts2 action classes flexible and we can create them by implementing Action interface, extending ActionSupport class or just by having execute() method.
    Thread Safety Struts1 Action Classes are Singleton and not thread safe, that makes extra care on developer side to avoid any side effects because of multithreading. Struts2 action classes gets instantiated per request, so there is no multithreading and makes them thread safe.
    Servlet API coupling Struts1 APIs are tightly coupled with Servlet API and Request and Response objects are passed to action classes execute() method. Struts2 API is loosely coupled with Servlet API and automatically maps the form bean data to action class java bean properties that we mostly use. If however we need reference to Servlet API classes, there are *Aware interfaces for that.
    Testing Struts1 action classes are hard to test because of Servlet API coupling. Struts2 Action classes are like normal java classes and we can test them easily by instantiating them and setting their properties.
    Request Parameters mapping Struts1 requires us to create ActionForm classes to hold request params and we need to configure it in the struts configuration file. Struts2 request params mapping is done on the fly and all we need is to have java bean properties in action classes or implement ModelDriven interface to provide the java bean class name to be used for mapping.
    Tag Support Struts1 uses JSTL Tags and hence are limited. Struts2 uses OGNL and provide different kinds of UI, Control and Data Tags. It’s more versatile and easy to use.
    Validation Struts1 supports validation through manual validate() method Struts2 support both manual validation as well as Validation framework integration.
    Views Rendering Struts1 uses standard JSP technology for providing bean values to JSP pages for views. Struts2 uses ValueStack to store request params and attributes and we can use OGNL and Struts2 tags to access them.
    Modules support Struts1 modules are complex to design and looks like separate projects Struts2 provides “namespace” configuration for packages to easily create modules.
  3. What are Struts2 core components?

    Struts2 core components are:

    1. Action Classes
    2. Interceptors
    3. Result Pages, JSP of FreeMarker templates
    4. ValueStack, OGNL and Tag Libraries

    Struts2에서 인터셉터란? 인터셉터는 Struts2 Framework의 백본입니다. Struts2 인터셉터는 액션 클래스에 요청 매개변수 전달, Servlet API 요청, 응답, 액션 클래스에 사용 가능한 세션, 유효성 검사, i18n 지원 등과 같이 프레임워크에서 수행되는 대부분의 처리를 담당합니다. ActionInvocation은 액션 클래스를 캡슐화하는 책임이 있습니다. 인터셉터와 순서대로 발사합니다. ActionInvocation에서 사용하는 가장 중요한 메소드는 인터셉터 체인을 추적하고 다음 인터셉터 또는 액션을 호출하는 invoke() 메소드입니다. 이것은 Java EE 프레임워크에서 책임 사슬 패턴의 가장 좋은 예 중 하나입니다.\n\n\nStruts2 인터셉터는 어떤 디자인 패턴을 구현합니까?

    Struts2 interceptors are based on intercepting filters design pattern. The invocation of interceptors in interceptor stack closely resembles Chain of Responsibility design pattern.
    

    Struts2에서 Action 클래스를 생성하는 다른 방법은 무엇입니까?

    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 액션과 인터셉터는 스레드로부터 안전합니까?

    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.
    

    Struts2에서 Front Controller는 어떤 클래스인가요?

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

    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.
    

    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.
    

    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
    

    사용했던 몇 가지 중요한 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>
    ```
    

    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.
    

    요청 매개변수를 조치 클래스 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.
    

    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.
    

    액션 클래스에 대해 Action 인터페이스와 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.
    

    액션 클래스에서 Servlet API 요청, 응답, HttpSession 등 객체를 어떻게 얻을 수 있습니까?

    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.
    

    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.
    

    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.
    

    Struts2 애플리케이션에서 log4j를 어떻게 통합할 수 있습니까?

    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 태그는 무엇입니까? 어떻게 사용할 수 있습니까?

    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의 Custom Type Converter는 무엇입니까?

    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 패키지는 무엇이며 이점은 무엇입니까?

    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.
    

    Struts2 액션 URI의 기본 접미사는 무엇이며 어떻게 변경할 수 있습니까?

    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.
    

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

    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.
    

    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 인터뷰 질문과 답변은 여기까지 입니다. 제가 놓친 중요한 질문이 있으면 댓글로 알려주세요.