質問するログイン新規登録

Q&A

解決済

1回答

322閲覧

java spring 共通エラー画面(error.html))が出ない【Security】

ikigamikita

総合スコア20

0グッド

1クリップ

投稿2024/08/19 05:34

編集2024/08/19 06:24

0

1

実現したいこと

http://localhost:8080/user/list
にアクセスしたら出るはずの共通エラー画面error.htmlを出すようにしたい

前提

「SpringBoot解体新書」という本を参考にアプリを作っています。Securityの章に入り勉強していましたが、本のコードが古いらしく、
Spring Security 6.0 にバージョンアップしたためAIでSecurityFilterChainのコードを書きました
しかし、共通エラー画面が出ずに下記のようなエラー画面が出てしまいます。
(web Securityの設定をするまでは普通にerror.htmlは表示されていました。)
イメージ説明
何が原因でしょうか?お手数ですが、何卒よろしくお願いします、

発生している問題・エラーメッセージ

なし

該当のソースコード

java

1package com.example.config; 2 3import org.springframework.context.annotation.Bean; 4import org.springframework.context.annotation.Configuration; 5import org.springframework.security.config.annotation.web.builders.HttpSecurity; 6import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity; 7import org.springframework.security.web.SecurityFilterChain; 8 9@EnableWebSecurity 10@Configuration 11public class SecurityConfig { 12 13 @Bean 14 public SecurityFilterChain securityFilterChain(HttpSecurity http) throws Exception { 15 http 16 .authorizeHttpRequests((requests) -> requests 17 .requestMatchers("/webjars/**", "/css/**", "/js/**", "/h2-console/**").permitAll() // 誰でもアクセス可能 18 .requestMatchers("/login").permitAll() // /loginへのアクセスは許可 19 .requestMatchers("/user/signup").permitAll() // /user/signupへのアクセスは許可 20 .anyRequest().authenticated() // その他のリクエストは認証が必要 21 ) 22 .csrf(csrf -> csrf.ignoringRequestMatchers("/h2-console/**")) // h2-console/**以下はCSRF保護を無視 23 .headers(headers -> headers.frameOptions().disable()); // X-Frame-Options ヘッダーを無効化 24 25 return http.build(); 26 } 27} 28

java

1package com.example.aspect; 2 3import org.springframework.dao.DataAccessException; 4import org.springframework.http.HttpStatus; 5import org.springframework.ui.Model; 6import org.springframework.web.bind.annotation.ControllerAdvice; 7import org.springframework.web.bind.annotation.ExceptionHandler; 8 9@ControllerAdvice 10public class GlobalControllAdvice { 11 12// データベース関連の例外処理 13 @ExceptionHandler(DataAccessException.class) 14 public String dataAccessxExceptionHandler(DataAccessException e,Model model) { 15 16// 空文字をセット 17 model.addAttribute("error",""); 18// メッセージをModelに登録 19 model.addAttribute("message","SignupControllerで例外が発生しました"); 20 21// HTTPのエラーコード(500)をModelに登録 22 model.addAttribute("status",HttpStatus.INTERNAL_SERVER_ERROR); 23 24 return "error"; 25 26 } 27 28 @ExceptionHandler(Exception.class) 29 public String exceptionHandler(Exception e,Model model) { 30 31// 空文字をセット 32 model.addAttribute("error",""); 33// メッセージをModelに登録 34 model.addAttribute("message","SignupControllerで例外が発生しました"); 35 36// HTTPのエラーコード(500)をModelに登録 37 model.addAttribute("status",HttpStatus.INTERNAL_SERVER_ERROR); 38 39 return "error"; 40 41 } 42 43 44 45} 46

java

1package com.example.controller; 2 3import java.util.Locale; 4import java.util.Map; 5 6import org.modelmapper.ModelMapper; 7import org.springframework.beans.factory.annotation.Autowired; 8import org.springframework.dao.DataAccessException; 9import org.springframework.http.HttpStatus; 10import org.springframework.stereotype.Controller; 11import org.springframework.ui.Model; 12import org.springframework.validation.BindingResult; 13import org.springframework.validation.annotation.Validated; 14import org.springframework.web.bind.annotation.ExceptionHandler; 15import org.springframework.web.bind.annotation.GetMapping; 16import org.springframework.web.bind.annotation.ModelAttribute; 17import org.springframework.web.bind.annotation.PostMapping; 18import org.springframework.web.bind.annotation.RequestMapping; 19 20import com.example.application.service.UserApplicationService; 21import com.example.domain.user.model.MUser; 22import com.example.domain.user.service.UserService; 23import com.example.form.GroupOrder; 24//import com.example.form.GroupOrder; 25import com.example.form.SignupForm; 26 27import lombok.extern.slf4j.Slf4j; 28 29@Controller 30@RequestMapping("/user") 31//Slf4jはLombokのアノテーションです。これをクラスに付けるとSlf4jを使って、簡単にログ出力できます 32@Slf4j 33public class SignupController { 34 35 @Autowired 36 private UserApplicationService userApplicationService; 37 38 @Autowired 39 private UserService userService; 40 41 @Autowired 42 private ModelMapper modelMapper; 43 44 45// ユーザー登録画面を表示 46 @GetMapping("/signup") 47 public String getSignup(Model model,Locale locale, 48 @ModelAttribute SignupForm form) { 49 50// 性別を取得 51 Map<String,Integer> genderMap=userApplicationService.getGenderMap(locale); 52 model.addAttribute("genderMap",genderMap); 53 54// ユーザー登録画面に遷移 55 return "user/signup"; 56// 57 } 58 59// ユーザー登録処理 60 @PostMapping("/signup") 61 public String postSignup(Model model,Locale locale, 62 @ModelAttribute @Validated(GroupOrder.class) SignupForm form, 63 BindingResult bindingResult) { 64 65// 入力チェック結果 66 if(bindingResult.hasErrors()) { 67 68// ユーザー画面に戻る 69 return getSignup(model,locale,form); 70 71 } 72 73 log.info(form.toString()); 74 75 //formをMUserクラスに変換 76 MUser user=modelMapper.map(form,MUser.class); 77 78 //ユーザー登録 79 userService.signup(user); 80 81// ログイン画面にリダイレクト 82 return "redirect:/login"; 83 } 84 85 86// データベース関連の例外処理 87 @ExceptionHandler(DataAccessException.class) 88 public String dataAccessExceptionHandler(DataAccessException e,Model model) { 89 90// 空文字をセット 91 model.addAttribute("error",""); 92// メッセージをModelに登録 93 model.addAttribute("message","SignupControllerで例外が発生しました"); 94 95// HTTPのエラーコード(500)をModelに登録 96 model.addAttribute("status",HttpStatus.INTERNAL_SERVER_ERROR); 97 98 return "error"; 99 100 } 101 102// その他の例外処理 103 @ExceptionHandler(Exception.class) 104 public String exceptionHandler(Exception e,Model model) { 105 106// 空文字をセット 107 model.addAttribute("error",""); 108// メッセージをModelに登録 109 model.addAttribute("message","SignupControllerで例外が発生しました"); 110 111// HTTPのエラーコード(500)をModelに登録 112 model.addAttribute("status",HttpStatus.INTERNAL_SERVER_ERROR); 113 114 return "error"; 115 116 } 117 118 119 120 121} 122 123```java 124package com.example.controller; 125import java.util.List; 126 127import org.modelmapper.ModelMapper; 128import org.springframework.beans.factory.annotation.Autowired; 129import org.springframework.stereotype.Controller; 130import org.springframework.ui.Model; 131import org.springframework.web.bind.annotation.GetMapping; 132import org.springframework.web.bind.annotation.ModelAttribute; 133import org.springframework.web.bind.annotation.PostMapping; 134import org.springframework.web.bind.annotation.RequestMapping; 135 136import com.example.domain.user.model.MUser; 137import com.example.domain.user.service.UserService; 138import com.example.form.UserListForm; 139 140 141@Controller 142@RequestMapping("/user") 143public class UserListController { 144 145 @Autowired 146 private UserService userService; 147 148 @Autowired 149 private ModelMapper modelMapper; 150 151// ユーザー一覧画面を表示 152 153 @GetMapping("/list") 154 public String getUserList(@ModelAttribute UserListForm form,Model model) { 155 156// formをMUserクラスに変換 157 MUser user=modelMapper.map(form,MUser.class); 158 159// ユーザー一覧取得 160 List<MUser> userList=userService.getUsers(user); 161 162// Modelに登録 163 model.addAttribute("userList",userList); 164 165 166 167//// ユーザー一覧画面を表示 168 return "user/list"; 169 170 171 } 172 173// ユーザー検索処理 174 @PostMapping("/list") 175 public String postUserList(@ModelAttribute UserListForm form,Model model){ 176 177// formをMUserクラスに変換 178 MUser user=modelMapper.map(form, MUser.class); 179 180// ユーザー検索 181 List<MUser> userList=userService.getUsers(user); 182 183// Modelに登録 184 model.addAttribute("userList",userList); 185 186// ユーザー一覧画面を表示 187 return "user/list"; 188 189 190 } 191} 192

試したこと

プロジェクトのクリーンを行いました

補足情報(FW/ツールのバージョンなど)

java17
.springframework3.0.0

気になる質問をクリップする

クリップした質問は、後からいつでもMYページで確認できます。

またクリップした質問に回答があった際、通知やメールを受け取ることができます。

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

jimbe

2024/08/19 08:00

書籍を元に勉強されるのなら、バージョンダウンしてでも環境を合わせたほうが良いと思います。 新しい環境を勉強したいのなら、そのような環境を対象とする書籍を購入されたほうが良いでしょう。
ikigamikita

2024/08/27 04:38

返信遅れて申し訳ありません。たしかに、そうですよね。勉強し直すことも視野に入れます。
guest

回答1

0

ベストアンサー

エラーページへのpermissionがないからだと思います。

エラーページに遷移させても、その遷移先がアクセス権限がなくて403エラーになっていると推測できます。

authorizeHttpRequests()内でerrorページのパーミッションを追加してあげてください。以下のように。

Java

1// /errorがエラーページの場合 2.requestMatchers("/error").permitAll()

※エラーページが別のパスの場合は環境に合わせて変更してください

投稿2024/08/20 12:35

kiino

総合スコア559

バッドをするには、ログインかつ

こちらの条件を満たす必要があります。

ikigamikita

2024/08/27 04:39

ありがとうございます。試してみます。
guest

あなたの回答

tips

太字

斜体

打ち消し線

見出し

引用テキストの挿入

コードの挿入

リンクの挿入

リストの挿入

番号リストの挿入

表の挿入

水平線の挿入

プレビュー

15分調べてもわからないことは
teratailで質問しよう!

ただいまの回答率
85.30%

質問をまとめることで
思考を整理して素早く解決

テンプレート機能で
簡単に質問をまとめる

質問する

関連した質問