0
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?

【SpringBoot】CRUD

Posted at

CRUD

ツール:Eclipse

CRUDとは、データを操作するときに必要な最低限の機能である

・登録機能(「C」reate)
・参照機能(「R」ead)
・変更機能(「U」pdate)
・削除機能(「D」elete)

の4つを一緒くたにした表現

Spring BootのCRUD機能を実際に作ってみましょう。
前の章では登録機能を作成したので、そのほかの機能の作成しましょう。

1.Viewを作成します。

/demo/src/main/resources/templatesを右クリック > 新規 > その他 > WEB > HTMLファイル
image.png

/demo/src/main/java/com/example/demo/TodoController.java
	package com.example.demo;				
					
	import org.springframework.stereotype.Controller;				
	import org.springframework.web.bind.annotation.GetMapping;				
	import org.springframework.web.bind.annotation.PathVariable;				
	import org.springframework.web.bind.annotation.PostMapping;				
	import org.springframework.web.servlet.ModelAndView;				
					
	@Controller				
	public class TodoController {				
                    
				    
	    			

+	    @GetMapping("/{id}")				
+	    // パスパラメータを受け取るアノテーション				
+	    public ModelAndView edit (@PathVariable Long id) {				
+	        ModelAndView mav = new ModelAndView();				
+	        				
+	        mav.addObject("todo", repository.findById(id));				
+	        				
+	        mav.setViewName("edit");				
+	        				
+	        return mav;				
+	    }				
+	    				
+	    // わかりやすくstoreメソッドと分けていますが、一緒でも動作します。   				
+	    @PostMapping("/{id}")				
+	    public String update (Todo todo) {				
+	        repository.save(todo);				
+	        				
+	        return "redirect:/";				
+	    }				
+	    @PostMapping("/delete/{id}")				
+	    // パスパラメータを受け取るアノテーション				
+	    public String delete (@PathVariable Long id) {				
+	        repository.deleteById(id);				
+	        				
+	        return "redirect:/";				
+	    }				
+	    				
	}				
					
/demo/src/main/resources/templates/edit.html
	<!DOCTYPE html>
	<html>
	<head>
+	    <meta charset="UTF-8">
+	    <meta name="viewport" content="width=device-width, initial-scale=1.0">
+	    <title>編集画面</title>
+	    <link th:href="@{/css/style.css}" rel="stylesheet">
	</head>
	<body>
+	    <div class="container">
+	        <h2>編集画面</h2>
+	        <form method="post" th:action="@{/*{id}}" th:object="${todo}">
+	            <input type="text" placeholder="タイトルを入力..." th:field="*{title}">
+	            <br>
+	            <textarea rows="4" placeholder="メモを入力..." th:field="*{memo}"></textarea>
+	            <br>
+	            <button type="submit">編集</button>
+	        </form>
+	    </div>
	</body>
	</html>

アプリケーションを実行します。

次はValidationについてです。

0
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
0
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?