기본값이 셋팅 돼 있기 때문에 h2데이터 베이스와 연결 했을 때 오류가 난다.
import static org.springframework.security.config.Customizer.withDefaults;
//Spring Security 구성에 대한 기본 설정을 적용하는 데 사용
//명시적으로 구성을 지정하지 않고도 일반적인 보안 구성을 간편하게 적용
@Bean
public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
//HttpServeltRequest에 매칭될 수 있는 필터 체인을 정의
// 웹요청이 들어오면 언제나 이 체인이 먼저 처리 한다
//ex ) 로그아웃 상태로 페이지를 요청하면 로그인 폼이 뜨는 것
http.authorizeHttpRequests(
auth -> auth.anyRequest().authenticated());
http.formLogin(withDefaults());
http.csrf().disable();
http.headers().frameOptions().disable();
return http.build();
//command + shift + t
//command + o
}
spring.datasource.url=jdbc:h2:mem:testdb
#소스 초기화 지연
spring.jpa.defer-datasource-initialization=true
3.Todo.java
@Entity
public class Todo {
public Todo() {
}
@Id
@GeneratedValue
private int id;
private String username;
@Size(min = 10, message="Enter at Enter at least 10 character")
private String description;
private LocalDate targetDate;
private boolean done;
package com.in28minnutes.springboot.myfirstwebapp.todo;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
public interface TodoRepository extends JpaRepository<Todo, Integer>{
public List<Todo> findByUsername(String username);
}
뷰에 출력하기 위해서 JPA REPOSITORY를 생성해준다.
public class TodoControllerJpa {
public TodoControllerJpa(TodoService todoService, TodoRepository todoRepository) {
super();
this.todoService = todoService;
this.todoRepository = todoRepository;
}
private TodoService todoService;
private TodoRepository todoRepository;
// /list-todos
@RequestMapping("list-todos")
public String listAllTodos(ModelMap model) {
String username = getLoggedInUsername(model);
List<Todo> todos = todoRepository.findByUsername(username);
model.addAttribute("todos",todos);
//todoRepository.getById(1);//select
return "listTodos";
}
Controller에 연결하기 (select, delete, update)
// /list-todos
@RequestMapping("list-todos")
public String listAllTodos(ModelMap model) {
String username = getLoggedInUsername(model);
List<Todo> todos = todoRepository.findByUsername(username);
model.addAttribute("todos",todos);
//todoRepository.getById(1);//select
return "listTodos";
}
@RequestMapping("delete-todo")
public String deleteTodo(@RequestParam int id) {
todoRepository.deleteById(id);
//todoService.deleteById(id);
return "redirect:list-todos";
}
@RequestMapping(value = "update-todo", method = RequestMethod.GET)
public String showUpdateTodoPage(@RequestParam int id, ModelMap model) {
Todo todo = todoRepository.findById(id).get();
System.out.println(todo.toString());
model.addAttribute("todo", todo);
return "todo";
}
@RequestMapping(value="update-todo", method = RequestMethod.POST)
public String updateTodo(//@RequestParam String description,
ModelMap model, @Valid Todo todo, BindingResult result) {
if(result.hasErrors()) {
return "todo";
}
String username = getLoggedInUsername(model);
todo.setUsername(username);
todoRepository.save (todo);
return "redirect:list-todos";
}