1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【勝手に】Spring Security公式のチュートリアルで紹介されたページをWebMvcConfigurerなしで作る【補足してみた】

Last updated at Posted at 2023-08-19

概要

Spring Securityの公式サイトに掲載されている、下記のソースが一般に知られているものではないと思ったので、勝手に補足してみました。

一応、初心者向けの説明のつもりです。

src/main/java/com/example/securingweb/MvcConfig.java
package com.example.securingweb;

import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ViewControllerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

@Configuration
public class MvcConfig implements WebMvcConfigurer {

	public void addViewControllers(ViewControllerRegistry registry) {
		registry.addViewController("/home").setViewName("home");
		registry.addViewController("/").setViewName("home");
		registry.addViewController("/hello").setViewName("hello");
		registry.addViewController("/login").setViewName("login");
	}

}

要はこういうこと

先に書いておきますが、上記のコードは下記のコードと同じものと思っていただいて結構です。(実際はチョット違う)

src/main/java/com/example/securingweb/Controllers.java
package com.example.securingweb;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Controllers {

    @RequestMapping({"/home","/"})
    public String requestHome(){
        return "home";
    }

    @RequestMapping("/hello")
    public String requestHello(){
        return "hello";
    }

    @RequestMapping("/login")
    public String requestLogin(){
        return "login";
    }

}

公式サイトのコードにWebMvcConfigurerとかaddViewControllerとかsetViewNameとか、色々知らないメソッドやインターフェースがあります。気にしなくて良いです。実際の開発で、エンドポイントがテンプレートを返すだけということは、あり得ないからです。

@Configurationアノテーションが公式サイトのソースについているので、Springを起動した際にMvcConfigは実行されます。
一方で、@Controllerアノテーションをつける一般的なやり方では、クライアントからリクエストが飛んできた際に実行されます。ここが違いの1つ。

@Configurationアノテーションを使うコードと、@Controllerアノテーションを使うコード両方を組み込むと、@Controllerアノテーションの方が優先されます。
これは単純に先ほど説明した通り、Springを起動した際にMvcConfigは実行され、クライアントからリクエストが飛んできた際に実行されるからです。
つまり両方書いても、ちゃんと動きます。コード的には無駄がありますが。

参考情報

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?