序文
「作者のホームページ」:Sprite Youbai Bubbles
「個人サイト」:スプライトの個人サイト
「おすすめコラム」:
★ Java ワンストップ サービス ★
★ 入門から習熟まで対応★
★クールなフロントエンド コード共有 ★
★ 0 からヒーロー、Vue が神になるまでの道★
★ uniapp-構築からプロモーションまで★
★ 0 からヒーロー、 Vueが神になる道★
★ アルゴリズムは1カラムで解ける★
★ 0からアーキテクチャを語ろう★
★データの循環の絶妙なやり方★
★先進的なバックエンドへの道★
記事ディレクトリ
例外処理
例外処理は、あらゆるアプリケーションにとって不可欠なコンポーネントです。Spring MVC は、例外をキャッチして処理し、分かりやすいエラー メッセージを返す便利なメカニズムを提供します。
例外処理は、あらゆるアプリケーションにとって不可欠なコンポーネントです。Web アプリケーションで例外が発生すると、通常、HTTP エラー コードと対応するエラー メッセージが返されますが、これはエンド ユーザーにとって使いやすいものではありません。Spring MVC は、例外をキャッチして処理し、分かりやすいエラー メッセージを返す便利なメカニズムを提供します。
以下では、Spring MVC 例外処理の中心となる概念と、対応する Java コード例を詳しく説明します。
1. 例外処理:
Spring MVC フレームワークでは、 @ControllerAdvice アノテーションを使用してグローバル例外処理クラスを定義できます。このクラスは複数のメソッドを定義でき、それぞれが特定の種類の例外を処理し、分かりやすいエラー メッセージを返します。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(SQLException.class)
public ModelAndView handleSQLException(HttpServletRequest request, SQLException ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", ex.getMessage());
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
@ExceptionHandler(Exception.class)
public ModelAndView handleException(HttpServletRequest request, Exception ex) {
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("exception", ex.getMessage());
modelAndView.addObject("url", request.getRequestURL());
modelAndView.setViewName("error");
return modelAndView;
}
}
上の例では、GlobalExceptionHandler というグローバル例外処理クラスを定義し、その中に handleSQLException() と handleException() という 2 つのメソッドを定義しました。これら 2 つのメソッドは、それぞれ SQLException および Exception タイプの例外を処理します。処理中に、ModelAndView オブジェクトを使用してエラー メッセージを設定し、「エラー」ビューを返します。
2. 例外ハンドラーを構成します (例外ハンドラー構成)。
Spring MVC フレームワークでは、SimpleMappingExceptionResolver クラスを使用して例外ハンドラーを構成できます。
@Bean
public SimpleMappingExceptionResolver exceptionResolver() {
SimpleMappingExceptionResolver resolver = new SimpleMappingExceptionResolver();
Properties mappings = new Properties();
mappings.put("org.springframework.dao.DataAccessException", "dataAccessFailure");
mappings.put("org.springframework.security.access.AccessDeniedException", "accessDenied");
mappings.put("java.lang.Exception", "error");
resolver.setExceptionMappings(mappings);
return resolver;
}
上記の例では、ExceptionResolver Bean を定義し、Properties オブジェクトを通じて 3 つの例外タイプと対応するビュー名を設定しました。たとえば、DataAccessException タイプの例外が発生した場合、「dataAccessFailure」ビューが返されます。
3. HTTP エラー コードの処理 (HTTP ステータス コードの処理):
Spring MVC フレームワークでは、@ExceptionHandler アノテーションと ResponseEntity クラスを使用して HTTP エラー コードを処理できます。
@ControllerAdvice
public class GlobalExceptionHandler {
@ExceptionHandler(ResourceNotFoundException.class)
public ResponseEntity<Object> handleResourceNotFoundException(ResourceNotFoundException ex) {
ApiError apiError = new ApiError(HttpStatus.NOT_FOUND, ex.getMessage(), ex);
return new ResponseEntity<>(apiError, HttpStatus.NOT_FOUND);
}
@ExceptionHandler(Exception.class)
public ResponseEntity<Object> handleException(Exception ex) {
ApiError apiError = new ApiError(HttpStatus.INTERNAL_SERVER_ERROR, ex.getMessage(), ex);
return new ResponseEntity<>(apiError, HttpStatus.INTERNAL_SERVER_ERROR);
}
}
上の例では、GlobalExceptionHandler というグローバル例外処理クラスを定義し、その中に handleResourceNotFoundException() と handleException() という 2 つのメソッドを定義しました。これら 2 つのメソッドは、それぞれ ResourceNotFoundException タイプと Exception タイプの例外を処理します。処理中に、ApiError オブジェクトを作成し、それを ResponseEntity の戻り値として使用します。これにより、HTTP エラー コードと対応するエラー メッセージが返されます。
上記の紹介から、例外処理は Spring MVC フレームワークの非常に重要なメカニズムであることがわかります。これにより、開発者は例外をキャプチャして処理し、分かりやすいエラー メッセージを返すことができます。例外処理の概念を深く理解し、対応する Java コード スキルを習得することによってのみ、実際の開発で Spring MVC フレームワークを柔軟に使用して、効率的で信頼性が高く、保守が容易な Web アプリケーションを構築できます。
ファイルのアップロード
Spring MVC は、ファイルのアップロードを処理するためのシンプルなメカニズムを提供します。MultipartResolver インターフェイスを使用すると、複数のファイルのアップロードを同時に簡単に処理できます。
ファイルのアップロードは Web アプリケーションでは非常に一般的な機能であり、Spring MVC はファイルのアップロードを処理する簡単なメカニズムを提供します。MultipartResolver インターフェイスを使用すると、複数のファイルのアップロードを同時に簡単に処理できます。
以下では、Spring MVC ファイルのアップロードの中心となる概念と、対応する Java コードの例を詳しく説明します。
1. ファイルのアップロードを構成します。
Spring MVC フレームワークでは、ファイルのアップロード要求を処理するために MultipartResolver Bean を構成する必要があります。
@Bean
public MultipartResolver multipartResolver() {
CommonsMultipartResolver resolver = new CommonsMultipartResolver();
resolver.setMaxUploadSizePerFile(1024 * 1024); // 1MB
return resolver;
}
上記の例では、multipartResolver Bean を定義し、最大ファイル アップロード サイズを 1MB に設定しました。
2. ファイルのアップロードを処理します。
Spring MVC フレームワークでは、 @RequestParam アノテーションを使用して、アップロードされたファイルを Java オブジェクトにバインドできます。
@Controller
@RequestMapping("/file")
public class FileController {
@PostMapping("/upload")
public String upload(@RequestParam("file") MultipartFile file, RedirectAttributes redirectAttributes) {
if (file.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/file";
}
try {
byte[] bytes = file.getBytes();
Path path = Paths.get("uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
redirectAttributes.addFlashAttribute("message", "File uploaded successfully");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/file";
}
}
上記の例では、FileController というコントローラー クラスを定義し、その中に Upload() メソッドを定義しました。このメソッドは、@RequestParam アノテーションを使用してアップロードされたファイルを MultipartFile オブジェクトにバインドし、RedirectAttributes オブジェクトを通じてメッセージをビューに渡します。処理中に、Files.write() メソッドを使用して、アップロードされたファイルをサーバーのローカル ディスクに書き込みます。
3. 複数のファイルのアップロードを処理します。
Spring MVC フレームワークでは、 @RequestParam アノテーションと List タイプを使用して、アップロードされた複数のファイルを Java オブジェクトにバインドできます。
@Controller
@RequestMapping("/file")
public class FileController {
@PostMapping("/multi-upload")
public String multiUpload(@RequestParam("files") List<MultipartFile> files, RedirectAttributes redirectAttributes) {
if (files.isEmpty()) {
redirectAttributes.addFlashAttribute("message", "Please select a file to upload");
return "redirect:/file";
}
try {
for (MultipartFile file : files) {
byte[] bytes = file.getBytes();
Path path = Paths.get("uploads/" + file.getOriginalFilename());
Files.write(path, bytes);
}
redirectAttributes.addFlashAttribute("message", "Files uploaded successfully");
} catch (IOException e) {
e.printStackTrace();
}
return "redirect:/file";
}
}
上の例では、FileController というコントローラー クラスを定義し、その中に multiUpload() メソッドを定義しました。このメソッドは、 @RequestParam アノテーションを使用して、アップロードされた複数のファイルを List オブジェクトにバインドし、RedirectAttributes オブジェクトを通じてメッセージをビューに渡します。処理中、for ループを使用して、アップロードされたすべてのファイルを反復処理し、サーバーのローカル ディスクに書き込みます。
上記の紹介から、ファイルのアップロードは Spring MVC フレームワークの非常に重要なメカニズムであり、開発者が複数のファイルのアップロードを同時に簡単に処理できることがわかります。ファイルアップロードの概念を深く理解し、対応する Java コードスキルを習得することによってのみ、実際の開発で Spring MVC フレームワークを柔軟に使用して、効率的で信頼性が高く、保守が容易な Web アプリケーションを構築できます。
安心のサポート
Spring MVC は、Restful スタイルの Web サービスを適切にサポートします。RESTful Web サービスは、@RestController アノテーションを使用して簡単に作成できます。
RESTful アーキテクチャ スタイルは Web サービスの設計スタイルであり、HTTP プロトコルの GET、POST、PUT、DELETE などのメソッドを使用して、リソースの作成、読み取り、更新、削除の操作を実装します。Spring MVC は、Restful スタイルの Web サービスを適切にサポートします。RESTful Web サービスは、@RestController アノテーションを使用して簡単に作成できます。
以下では、Spring MVC Restful の中心となる概念と、対応する Java コード例を詳しく説明します。
1. Restful コントローラーを作成します (Restful コントローラーの作成):
Spring MVC フレームワークでは、@RestController アノテーションを使用して Restful コントローラー クラスを定義できます。このクラスのすべてのメソッドは、JSON データまたは XML データを返します。
@RestController
@RequestMapping("/api")
public class UserController {
@Autowired
private UserService userService;
@GetMapping("/users")
public List<User> getAllUsers() {
return userService.getAllUsers();
}
@PostMapping("/users")
public User createUser(@RequestBody User user) {
return userService.saveUser(user);
}
@GetMapping("/users/{id}")
public User getUserById(@PathVariable Long id) {
return userService.getUserById(id);
}
@PutMapping("/users/{id}")
public User updateUser(@PathVariable Long id, @RequestBody User user) {
User oldUser = userService.getUserById(id);
oldUser.setName(user.getName());
oldUser.setEmail(user.getEmail());
oldUser.setPassword(user.getPassword());
return userService.saveUser(oldUser);
}
@DeleteMapping("/users/{id}")
public void deleteUserById(@PathVariable Long id) {
userService.deleteUserById(id);
}
}
上の例では、UserController という Restful コントローラー クラスを定義し、その中に getAllUsers()、createUser()、getUserById()、updateUser()、および deleteUserById() の 5 つのメソッドを定義しました。これらのメソッドは、HTTP GET、POST、PUT、および DELETE リクエストをそれぞれ処理し、JSON または XML 形式でデータを返します。
2.Restful メッセージコンバーターの構成
Spring MVC フレームワークでは、Restful Web サービスのリクエストとレスポンスを処理するために HttpMessageConverters Bean を構成する必要があります。
@Bean
public HttpMessageConverters converters() {
MappingJackson2HttpMessageConverter jsonConverter = new MappingJackson2HttpMessageConverter();
List<MediaType> supportedMediaTypes = new ArrayList<>();
supportedMediaTypes.add(MediaType.APPLICATION_JSON);
supportedMediaTypes.add(MediaType.APPLICATION_XML);
jsonConverter.setSupportedMediaTypes(supportedMediaTypes);
return new HttpMessageConverters(jsonConverter);
}
上記の例では、コンバータ Bean を定義し、それに MappingJackson2HttpMessageConverter オブジェクトを追加しました。このオブジェクトは、JSON および XML 形式でのデータの処理をサポートします。
上記の紹介を通じて、Restful スタイル Web サービスは Spring MVC フレームワークの非常に重要なメカニズムであることがわかります。これにより、開発者は HTTP プロトコルで GET、POST、PUT、DELETE などのメソッドを使用して、リソース、読み取り、更新および削除操作。Restful の概念を深く理解し、対応する Java コード スキルを習得することによってのみ、実際の開発で Spring MVC フレームワークを柔軟に使用して、効率的で信頼性が高く、保守が容易な Web アプリケーションを構築することができます。