Spring MVCのインタビューの質問

Spring MVCインタビューの質問

1. 前書き

Spring MVCは、Servlet API上に構築されたSpringのオリジナルのWebフレームワークです。 柔軟なWebアプリケーションの開発に使用できるModel-View-Controllerアーキテクチャを提供します。

このチュートリアルでは、Springのデベロッパーの就職の面接で話題になることが多いため、それに関連する質問に焦点を当てます。

Spring Frameworkに関するその他の質問については、interview questions seriesanother Spring related articleを確認できます。

2. Spring MVCの基本的な質問

Q1. Spring MVCを使用する理由

Spring MVC implements a clear separation of concerns that allows us to develop and unit test our applications easily

次のような概念:

  • ディスパッチャサーブレット

  • コントローラー

  • リゾルバを表示

  • ビュー、モデル

  • ModelAndView

  • モデルとセッションの属性

互いに完全に独立しており、1つのことだけを担当します。

したがって、MVC gives us quite big flexibility。 これは(提供された実装クラスを備えた)インターフェースに基づいており、カスタムインターフェースを使用してフレームワークのすべての部分を構成できます。

Another important thing is that we aren’t tied to a specific view technology (for example, JSP), but we have the option to choose from the ones we like the most

また、we don’t use Spring MVC only in web applications development but in the creation of RESTful web services as well

Q2. @Autowiredアノテーションの役割は何ですか?

The @Autowired annotation can be used with fields or methods for injecting a bean by type。 このアノテーションにより、SpringはコラボレーションBeanを解決してBeanに注入できます。

詳細については、@Autowired in Springに関するチュートリアルを参照してください。

Q3. モデル属性の説明

@ModelAttributeアノテーションは、SpringMVCで最も重要なアノテーションの1つです。 It binds a method parameter or a method return value to a named model attribute and then exposes it to a web view

メソッドレベルで使用する場合、そのメソッドの目的が1つ以上のモデル属性を追加することであることを示しています。

一方、メソッドの引数として使用する場合、モデルから引数を取得する必要があることを示します。 存在しない場合は、最初にインスタンス化してからモデルに追加する必要があります。 モデルに表示されたら、名前が一致するすべてのリクエストパラメータから引数フィールドに入力する必要があります。

このアノテーションの詳細については、article related to the @ModelAttribute annotationをご覧ください。

Q4. @Controller@RestControllerの違いを説明してください。

@Controllerアノテーションと@RestControllerアノテーションの主な違いは、the @ResponseBody annotation is automatically included in the @RestControllerです。 これは、ハンドラーメソッドに@ResponseBodyで注釈を付ける必要がないことを意味します。 応答タイプをHTTP応答本文に直接書き込む場合は、@Controllerクラスでこれを行う必要があります。

Q5. PathVariableを説明する

We can use the @PathVariable annotation as a handler method parameter in order to extract the value of a URI template variable

たとえば、www.mysite.com/user/123からIDでユーザーをフェッチする場合は、コントローラーのメソッドを/user/{id}としてマップする必要があります。

@RequestMapping("/user/{id}")
public String handleRequest(@PathVariable("id") String userId, Model map) {}

The @PathVariable has only one element named value. It’s optional and we use it to define the URI template variable name。 value要素を省略する場合、URIテンプレート変数名はメソッドパラメーター名と一致する必要があります。

また、次々に宣言することにより、複数の@PathVariableアノテーションを付けることもできます。

@RequestMapping("/user/{userId}/name/{userName}")
public String handleRequest(@PathVariable String userId,
  @PathVariable String userName, Model map) {}

または、それらをすべてMap<String, String>またはMultiValueMap<String, String>に入れます。

@RequestMapping("/user/{userId}/name/{userName}")
public String handleRequest(@PathVariable Map varsMap, Model map) {}

Q6. Spring MVCを使用した検証

Spring MVC supports JSR-303 specifications by default. We need to add JSR-303 and its implementation dependencies to our Spring MVC application。 たとえば、Hibernate Validatorは自由に使用できるJSR-303実装の1つです。

JSR-303は、JavaEEおよびJavaSEの一部であるBean検証用のJava APIの仕様であり、@NotNull@Min、%((t1)sなどのアノテーションを使用してBeanのプロパティが特定の基準を満たすことを保証します。 t2)s。 検証の詳細については、Java Bean Validation Basicsの記事をご覧ください。

Spring offers the @Validator annotation and the BindingResult classValidatorの実装では、無効なデータがある場合、コントローラー要求ハンドラーメソッドでエラーが発生します。 次に、BindingResultクラスを使用してこれらのエラーを取得できます。

既存の実装を使用する以外に、独自の実装を作成できます。 そのためには、まずJSR-303仕様に準拠する注釈を作成します。 次に、Validatorクラスを実装します。 もう1つの方法は、SpringのValidatorインターフェースを実装し、Controllerクラスの@InitBinderアノテーションを介してバリデーターとして設定することです。

独自の検証を実装して使用する方法を確認するには、Custom Validation in Spring MVCに関するチュートリアルをご覧ください。

Q7. @RequestBody@ResponseBodyは何ですか?

The @RequestBody annotation, used as a handler method parameter, binds the HTTP Request body to a transfer or a domain object。 Springは、Httpメッセージコンバーターを使用して、Javaオブジェクトへの着信HTTP要求を自動的に逆シリアル化します。

When we use the @ResponseBody annotation on a handler method in the Spring MVC controller, it indicates that we’ll write the return type of the method directly to the HTTP response bodyModelには入れず、Springはビュー名として解釈しません。

これらのアノテーションの詳細については、@RequestBody and @ResponseBodyの記事をご覧ください。

Q8. ModelModelMapModelAndViewについて説明してください。

The Model interface defines a holder for model attributesThe ModelMap has a similar purpose, with the ability to pass a collection of values。 次に、それらの値をMap内にあるかのように扱います。 ModelModelMap)では、データしか保存できないことに注意してください。 データを入力し、ビュー名を返します。

一方、with the ModelAndView, we return the object itself。 返されるオブジェクトには、データやビュー名など、必要なすべての情報を設定します。

詳細については、Model, ModelMap, and ModelViewの記事をご覧ください。

Q9. SessionAttributesSessionAttributeについて説明する

The @SessionAttributes annotation is used for storing the model attribute in the user’s session.Session Attributes in Spring MVCに関する記事に示されているように、コントローラークラスレベルで使用します。

@Controller
@RequestMapping("/sessionattributes")
@SessionAttributes("todos")
public class TodoControllerWithSessionAttributes {

    @GetMapping("/form")
    public String showForm(Model model,
      @ModelAttribute("todos") TodoList todos) {
        // method body
        return "sessionattributesform";
    }

    // other methods
}

前の例では、@ModelAttribute@SessionAttributesの名前属性が同じである場合、モデル属性 ‘todos‘がセッションに追加されます。

If we want to retrieve the existing attribute from a session that is managed globally, we’ll use @SessionAttribute annotation as a method parameter

@GetMapping
public String getTodos(@SessionAttribute("todos") TodoList todos) {
    // method body
    return "todoView";
}

Q10. @EnableWebMVCの目的は何ですか?

The @EnableWebMvc annotation’s purpose is to enable Spring MVC via Java configuration。 XML構成の<mvc: annotation-driven>と同等です。 このアノテーションは、WebMvcConfigurationSupportからSpringMVC構成をインポートします。 これにより、@RequestMappingを使用して着信要求をハンドラーメソッドにマップする@Controllerアノテーション付きクラスのサポートが有効になります。

これと同様のアノテーションの詳細については、Guide to the Spring @Enable Annotationsをご覧ください。

Q11. 春のViewResolverとは何ですか?

The ViewResolver enables an application to render models in the browser –実装を特定のビューテクノロジに結び付けない–by mapping view names to actual views

ViewResolverの詳細については、Guide to the ViewResolver in Spring MVCをご覧ください。

Q12. BindingResultとは何ですか?

BindingResult is an interface from org.springframework.validation package that represents binding results. We can use it to detect and report errors in the submitted form。 呼び出すのは簡単です。検証するフォームオブジェクトの直後にパラメータとして配置する必要があります。 オプションのModelパラメータは、custom validator tutorialに見られるように、BindingResultの後に来る必要があります。

@PostMapping("/user")
public String submitForm(@Valid NewUserForm newUserForm,
  BindingResult result, Model model) {
    if (result.hasErrors()) {
        return "userHome";
    }
    model.addAttribute("message", "Valid form");
    return "userHome";
}

When Spring sees the @Valid annotation, it’ll first try to find the validator for the object being validated.次に、検証アノテーションを取得し、バリデーターを呼び出します。 最後に、見つかったエラーをBindingResultに配置し、後者をビューモデルに追加します。

Q13. フォームバッキングオブジェクトとは何ですか?

The form backing object or a Command Object is just a POJO that collects data from the form we’re submitting

ロジックは含まれておらず、データのみが含まれていることに注意してください。

Spring MVCのフォームでフォームバッキングオブジェクトを使用する方法については、Forms in Spring MVCに関する記事をご覧ください。

Q14. @Qualifierアノテーションの役割は何ですか?

It is used simultaneously with the @Autowired annotation to avoid confusion when multiple instances of a bean type are present

例を見てみましょう。 XML構成で2つの同様のBeanを宣言しました。


    


    

Beanをワイヤリングしようとすると、org.springframework.beans.factory.NoSuchBeanDefinitionException.が返されます。これを修正するには、@Qualifierを使用して、どのBeanをワイヤリングする必要があるかをSpringに通知する必要があります。

@Autowired
@Qualifier("person1")
private Person person;

Q15. @Requiredアノテーションの役割は何ですか?

@Requiredアノテーションはsetterメソッドで使用され、このアノテーションを持つBeanプロパティは構成時に入力する必要があることを示します。 それ以外の場合、SpringコンテナはBeanInitializationException例外をスローします。

また、@Required@Autowiredとは異なります。セッターに限定されているのに対し、@Autowiredはそうではありません。 @Autowiredは、コンストラクターとフィールドとの接続にも使用できますが、@Requiredは、プロパティが設定されているかどうかのみをチェックします。

例を見てみましょう:

public class Person {
    private String name;

    @Required
    public void setName(String name) {
        this.name = name;
    }
}

ここで、Person Beanのnameを次のようにXML構成で設定する必要があります。


    

@Required doesn’t work with Java based @Configuration classes by defaultに注意してください。 すべてのプロパティが設定されていることを確認する必要がある場合は、@Beanアノテーション付きメソッドでBeanを作成するときに行うことができます。

Q16. フロントコントローラーパターンの説明

In the Front Controller pattern, all requests will first go to the front controller instead of the servletIt’ll make sure that the responses are ready and will send them back to the browser. This way we have one place where we control everything that comes from the outside world.

フロントコントローラーは、最初にリクエストを処理するサーブレットを識別します。 次に、サーブレットからデータを取得すると、レンダリングするビューが決定され、最後に、レンダリングされたビューが応答として返送されます。

image

実装の詳細を確認するには、Guide to the Front Controller Pattern in Javaを確認してください。

Q17. モデル1およびモデル2のアーキテクチャとは何ですか?

モデル1とモデル2は、Java Webアプリケーションの設計に関して頻繁に使用される2つの設計モデルを表しています。

In Model 1, a request comes to a servlet or JSP where it gets handled。 サーブレットまたはJSPは、リクエストを処理し、ビジネスロジックを処理し、データを取得および検証し、レスポンスを生成します。

image

このアーキテクチャは実装が簡単なので、通常は小さくてシンプルなアプリケーションで使用します。

一方、大規模なWebアプリケーションには便利ではありません。 多くの場合、ビジネスロジックとプレゼンテーションロジックが結合されているJSPで機能が複製されます。

モデル2は、Model View Controllerデザインパターンに基づいており、コンテンツを操作するロジックからビューを分離します。

Furthermore, we can distinguish three modules in the MVC pattern: the model, the view, and the controller。 モデルは、アプリケーションの動的データ構造を表します。 データとビジネスロジックの操作を担当します。 ビューはデータの表示を担当し、コントローラーは前の2つの間のインターフェースとして機能します。

モデル2では、要求がコントローラーに渡され、コントローラーは、表示されるべき正しいコンテンツを取得するために必要なロジックを処理します。 次にコントローラーは、通常はJavaBeanまたはPOJOとしてコンテンツをリクエストに戻します。 また、どのビューでコンテンツをレンダリングするかを決定し、最終的にリクエストをコンテンツに渡します。 次に、ビューはデータをレンダリングします。

image

3. Spring MVCの高度な質問

Q18. Springの@Controller@Component@Repository,@Serviceアノテーションの違いは何ですか?

Springの公式ドキュメントによると、@ComponentはSpringが管理するコンポーネントの一般的なステレオタイプです。 @Repository@Service、および@Controllerは、それぞれ、永続性、サービス、およびプレゼンテーション層など、より具体的なユースケース向けの@Componentの特殊化です。

最後の3つの特定のユースケースを見てみましょう。

  • @Controller –クラスがコントローラーの役割を果たし、クラス内の@RequestMapping注釈を検出することを示します

  • @Service –クラスがビジネスロジックを保持し、リポジトリ層のメソッドを呼び出すことを示します

  • @Repository –クラスがデータリポジトリを定義することを示します。その仕事は、プラットフォーム固有の例外をキャッチし、Springの統合された未チェックの例外の1つとしてそれらを再スローすることです。

Q19. DispatcherServletおよびContextLoaderListenerとは何ですか?

簡単に言えば、フロントコントローラーのデザインパターンでは、単一のコントローラーが、着信HttpRequestsをアプリケーションの他のすべてのコントローラーとハンドラーに送信する役割を果たします。

SpringのDispatcherServletはこのパターンを実装しているため、HttpRequestsを適切なハンドラーに正しく調整する責任があります。

一方、ContextLoaderListenerは、SpringのルートWebApplicationContextを起動およびシャットダウンします。 これは、ApplicationContextのライフサイクルをServletContext.のライフサイクルに結び付けます。これを使用して、さまざまなSpringコンテキストで機能する共有Beanを定義できます。

DispatcherServletの詳細については、to this tutorialを参照してください。

Q20. MultipartResolverとは何ですか?いつ使用する必要がありますか?

The MultipartResolver interface is used for uploading files。 Springフレームワークは、Commons FileUploadで使用するための1つのMultipartResolver実装と、サーブレット3.0マルチパート要求の解析で使用するための別の実装を提供します。

これらを使用して、Webアプリケーションでのファイルのアップロードをサポートできます。

Q21. Spring MVCインターセプターとは何ですか?その使用方法は?

Spring MVCインターセプターを使用すると、クライアントリクエストをインターセプトし、リクエストの処理前、処理後、または完了後(ビューがレンダリングされるとき)に3つの場所で処理できます。

インターセプターは、横断的な関心事に使用でき、ロギング、Springモデルでグローバルに使用されるパラメーターの変更などの反復的なハンドラーコードを回避できます。

詳細とさまざまな実装については、Introduction to Spring MVC HandlerInterceptorの記事をご覧ください。

Q22. Init Binderとは何ですか?

A method annotated with @InitBinder is used to customize a request parameter, URI template, and backing/command objects。 コントローラで定義し、リクエストの制御に役立ちます。 In this method, we register and configure our custom PropertyEditors, a formatter, and validators

注釈には ‘value‘要素があります。 設定しない場合、@InitBinderアノテーション付きメソッドが各HTTPリクエストで呼び出されます。 値を設定すると、メソッドは、名前が ‘value‘要素に対応する特定のコマンド/フォーム属性および/またはリクエストパラメータにのみ適用されます。

It’s important to remember that one of the arguments must be WebDataBinder.他の引数は、コマンド/フォームオブジェクトと対応する検証結果オブジェクトを除いて、ハンドラーメソッドがサポートする任意のタイプにすることができます。

Q23. コントローラーのアドバイスを説明する

The @ControllerAdvice annotation allows us to write global code applicable to a wide range of controllers。 コントローラーの範囲を、選択したパッケージまたは特定の注釈に結び付けることができます。

デフォルトでは、@ControllerAdvice applies to the classes annotated with @Controller (or @RestController)です。 さらに具体的にしたい場合に使用するいくつかのプロパティもあります。

If we want to restrict applicable classes to a package, we should add the name of the package to the annotation

@ControllerAdvice("my.package")
@ControllerAdvice(value = "my.package")
@ControllerAdvice(basePackages = "my.package")

複数のパッケージを使用することもできますが、今回はStringの代わりに配列を使用する必要があります。

Besides restricting to the package by its name, we can do it by using one of the classes or interfaces from that package

@ControllerAdvice(basePackageClasses = MyClass.class)

assignableTypes‘要素は@ControllerAdviceを特定のクラスに適用し、 ‘annotations‘は特定の注釈に対して適用します。

It’s noteworthy to remember that we should use it along with @ExceptionHandler。 この組み合わせにより、すべてのコントローラークラスに対して毎回実装する必要なく、グローバルでより具体的なエラー処理メカニズムを構成できます。

Q24. @ExceptionHandlerアノテーションは何をしますか?

The @ExceptionHandler annotation allows us to define a method that will handle the exceptionsWe may use the annotation independently, but it’s a far better option to use it together with the @ControllerAdvice.したがって、グローバルエラー処理メカニズムを設定できます。 In this way, we don’t need to write the code for the exception handling within every controller

Error Handling for REST with Springに関する記事の例を見てみましょう。

@ControllerAdvice
public class RestResponseEntityExceptionHandler
  extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = { IllegalArgumentException.class,
      IllegalStateException.class })
    protected ResponseEntity handleConflict(RuntimeException ex,
      WebRequest request) {
        String bodyOfResponse = "This should be application specific";
        return handleExceptionInternal(ex, bodyOfResponse, new HttpHeaders(),
          HttpStatus.CONFLICT, request);
    }
}


これにより、IllegalArgumentExceptionまたはIllegalStateExceptionをスローするすべてのコントローラーに@ExceptionHandlerメソッドが提供されることにも注意してください。 @ExceptionHandlerで宣言された例外は、メソッドの引数として使用される例外と一致する必要があります。 そうしないと、例外解決メカニズムは実行時に失敗します。

ここで覚えておくべきことの1つは、同じ例外に対して複数の@ExceptionHandlerを定義できることです。 ただし、Springは例外をスローして起動に失敗すると文句を言うため、同じクラスでそれを行うことはできません。

一方、if we define those in two separate classes, the application will start, but it’ll use the first handler it finds, possibly the wrong one

Q25. Webアプリケーションでの例外処理

Spring MVCでの例外処理には、次の3つのオプションがあります。

  • 例外ごと

  • コントローラーごと

  • 世界的に

未処理の例外がWeb要求処理中にスローされた場合、サーバーはHTTP 500応答を返します。 これを防ぐには、we should annotate any of our custom exceptions with the @ResponseStatus annotationを使用します。 This kind of exceptions is resolved by HandlerExceptionResolver

これにより、コントローラーメソッドが例外をスローしたときに、サーバーは指定されたステータスコードで適切なHTTP応答を返します。 このアプローチが機能するためには、他の場所で例外を処理するべきではないことに注意してください。

Another way to handle the exceptions is by using the @ExceptionHandler annotation@ExceptionHandlerメソッドを任意のコントローラーに追加し、それらを使用して、そのコントローラー内からスローされた例外を処理します。 これらのメソッドは、@ResponseStatusアノテーションなしで例外を処理したり、ユーザーを専用のエラービューにリダイレクトしたり、完全にカスタムのエラー応答を作成したりできます。

サーブレット関連のオブジェクト(HttpServletRequestHttpServletResponseHttpSession、およびPrincipal)をハンドラーメソッドのパラメーターとして渡すこともできます。 ただし、Modelオブジェクトをパラメータとして直接配置することはできないことを覚えておく必要があります。

The third option for handling errors is by @ControllerAdvice classes。 これにより、特定のコントローラーだけでなく、今回はアプリケーションレベルでのみ、同じ手法を適用できるようになります。 これを有効にするには、@ControllerAdvice@ExceptionHandlerを一緒に使用する必要があります。 このように、例外ハンドラーは、コントローラーによってスローされた例外を処理します。

このトピックの詳細については、Error Handling for REST with Springの記事をご覧ください。

4. 結論

この記事では、Spring開発者向けの技術面接で出てくる可能性のあるSpringMVC関連の質問のいくつかを調査しました。 これは完全なリストではないため、これらの質問をさらなる研究の出発点として考慮に入れる必要があります。

今後のインタビューで幸運を祈ります!