[Spring] Spring boot JPA사용해 로그인, 회원가입 구현
인프런의 김영한 님의 스프링 MVC 2편 - 백엔드 웹 개발 활용 기술편을 참고하였습니다.
https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-mvc-2/dashboard
Spring boot JPA와 mysql을 이용하여 간단한 로그인과 회원가입을 구현해보겠습니다.
👉프로젝트 생성
언어: Java 17
타입: Gradle - Groovy
패키지 생성: Jar
종속성: Spring Web, Spring Data JPA, Lombok
build.gradle
implementation 'com.mysql:mysql-connector-j'
build.gradle의 dependencies에 위 한줄 추가
application.properties
# db source url
spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true&useUnicode=true&serverTimezone=Asia/Seoul&allowPublicKeyRetrieval=true
# db response name
spring.datasource.username=root
# db response password
spring.datasource.password=1234
spring.jpa.show-sql=true
spring.jackson.property-naming-strategy=SNAKE_CASE
db sourceurl 부분의 test에 MySQL에서 만든 스키마의 이름을 넣고 username과 password를 본인 설정에 맞춘다.
MySQL에서 만든 테이블의 컬럼이 위와 같이 있으므로 Member클래스를 아래와 같이 맞춘다.
👉domain 생성
Member
@Data
@Table(name = "log_info")
@Entity
public class Member {
@Column(name = "password")
private String password;
@Id
@Column(name = "studentid")
private String studentId;
@Column(name = "name")
private String name;
@Column(name = "grade")
private String grade;
}
그리고 MemberInfoRepository 인터페이스를 만들어 아래와 같이 작성한다.
MemberInfoRepository
@Repository
public interface MemberInfoRepository extends JpaRepository<Member, Long> {
Optional<Member> findByStudentId(String studentId);
}
👉Controller 생성
그리고 로그인을 할 LoginController와 회원가입을 할 MemberController를 만든다.
LoginController
@Slf4j
@Controller
@RequiredArgsConstructor
public class LoginController {
private final LoginService loginService;
@GetMapping("/login")
public String loginForm(@ModelAttribute("loginView") LoginForm form) {
return "login/loginView";
}
@PostMapping("/login")
public String login(@Valid @ModelAttribute("loginView") LoginForm form,
@RequestParam(defaultValue = "/") String redirectURL,
BindingResult bindingResult, HttpServletRequest request) {
if (bindingResult.hasErrors()) {
return "login/loginView";
}
Member loginMember = loginService.login(form.getStudentId(),
form.getPassword());
log.info("login? {}", loginMember);
if (loginMember == null) {
bindingResult.reject("loginFail", "아이디 또는 비밀번호가 맞지 않습니다.");
return "login/loginView";
}
HttpSession session = request.getSession();
session.setAttribute(SessionConst.LOGIN_MEMBER, loginMember);
return "redirect:" + redirectURL;
}
}
MemberController
@Controller
@RequiredArgsConstructor
@RequestMapping("/members")
public class MemberController {
private final MemberInfoRepository memberInfoRepository;
@GetMapping("/add")
public String addForm(@ModelAttribute("member") Member member) {
return "members/register";
}
@PostMapping("/add")
public String save(@Valid @ModelAttribute Member member, BindingResult bindingResult) {
if (bindingResult.hasErrors()) {
return "members/register";
}
memberInfoRepository.save(member);
return "redirect:/login";
}
👉View 생성
그리고 로그인 화면과 회원가입 화면을 보여줄 View를 작성합니다.
loginView.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link th:href="@{/css/loginstyle.css}"
href="../css/loginstyle.css" rel="stylesheet">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>로그인</title>
<script src="jquery-3.4.1.js"></script>
<style>
.container {
max-width: 560px;
}
.field-error {
border-color: #dc3545;
color: #dc3545;
}
</style>
</head>
<body>
<section class="login-form">
<h1 class="h1">Inje Complition 로그인</h1>
<form action="item.html" th:action th:object="${loginView}" method="post">
<div th:if="${#fields.hasGlobalErrors()}">
<p class="field-error" th:each="err : ${#fields.globalErrors()}" th:text="${err}">전체 오류 메시지</p>
</div>
<div class="int-area">
<input type="text" name="id" id="userId" th:field="*{studentId}" th:errorclass="field-error"
autocomplete="off" required>
<label for="userId">학번 입력</label>
<div class="field-error" th:errors="*{studentId}"/>
</div>
<div class="int-area">
<input type="password" name="pw" id="pw" th:field="*{password}" th:errorclass="field-error"
autocomplete="off" required>
<label for="pw">비밀번호 입력</label>
<div class="field-error" th:errors="*{password}"/>
</div>
<div class="row">
<div class="btn-area">
<button id="btn" class="w-100 btn btn-primary btn-lg" type="submit">로그인</button>
</div>
</div>
</form>
<div class="caption">
<a href="" th:href="@{/members/add}">회원가입</a>
</div>
</section>
</body>
</html>
register.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="UTF-8">
<link th:href="@{/css/register.css}"
href="../css/register.css" rel="stylesheet">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>회원가입</title>
<script src="jquery-3.4.1.js"></script>
<style>
.container {
max-width: 560px;
}
.field-error {
border-color: #dc3545;
color: #dc3545;
}
</style>
</head>
<body>
<section class="login-form">
<h1 class="h1">Inje Complition 회원가입</h1>
<form action="" th:action th:object="${member}" method="post">
<div th:if="${#fields.hasGlobalErrors()}">
<p class="field-error" th:each="err : ${#fields.globalErrors()}"
th:text="${err}">전체 오류 메시지</p>
</div>
<div class="int-area">
<input type="text" name="name" id="name" th:field="*{name}" class="formcontrol"
th:errorclass="field-error" autocomplete="off" required>
<label for="name">이름 입력</label>
<div class="field-error" th:errors="*{name}"/>
</div>
<div class="int-area">
<input type="text" name="grade" id="grade" th:field="*{grade}" class="formcontrol"
th:errorclass="field-error" autocomplete="off" required>
<label for="grade">학년 입력</label>
<div class="field-error" th:errors="*{grade}"/>
</div>
<div class="int-area">
<input type="text" name="studentid" id="studentid" th:field="*{studentId}" class="formcontrol"
th:errorclass="field-error" autocomplete="off" required>
<label for="id">학번 입력</label>
<div class="field-error" th:errors="*{studentId}"/>
</div>
<div class="int-area">
<input type="password" name="pw" id="pw" th:field="*{password}" class="formcontrol"
th:errorclass="field-error" autocomplete="off" required>
<label for="pw">비밀번호 입력</label>
<div class="field-error" th:errors="*{password}"/>
</div>
<div class="btn-area">
<button class="w-100 btn btn-primary btn-lg" type="submit" >회원가입</button>
</div>
</form>
<div class="caption">
<!-- 모달 창 -->
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close" onclick="closeModal()">×</span>
<h2>로그인</h2>
<!-- 로그인 폼 -->
<form>
<div class="id">
<label for="id" class="id">학번:</label>
<input type="text" id="id" name="id">
</div>
<div class="pw">
<label for="password">비밀번호:</label>
<input type="password" id="password" name="password">
</div>
<!-- 추가 필드들을 여기에 추가하십시오 -->
<input type="submit" value="로그인">
</form>
</div>
</div>
</div>
</section>
</body>
</html>
👉실행 화면
정보를 넣어주고 회원가입 버튼은 눌러주면 테이블에 정상적으로 들어가는 것을 볼 수 있습니다.
로그인도 정상적으로 작동하는 것을 볼 수 있습니다.
'Spring Boot' 카테고리의 다른 글
[Spring] Grafana와 Prometheus로 서버 모니터링 하기 (0) | 2023.07.07 |
---|---|
[Spring] Spring MVC의 구조 (0) | 2023.06.03 |
[Spring]@ModelAttribute 어노테이션의 기능과 사용법 (0) | 2023.05.23 |
[Spring]메시지와 국제화 (0) | 2023.05.12 |
[Spring]Spring Boot로 Hello World찍기 (0) | 2023.01.29 |
댓글