My Project/도서 관리 프로그램 (final project)

5일차 - 기본 로그인 완료

미로910 2024. 9. 5. 09:33
SignInDTO
package com.library.bookwave.dto;

import com.library.bookwave.repository.model.User;

import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.ToString;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@ToString

// 로그인 DTO
public class SignInDTO {
	
	private String loginId; // 아이디
	private String password; // 비밀번호
	
	public User toUser() {
		return User.builder()
				   .loginId(this.loginId)
				   .password(this.password)
				   .build();
	}
	

}
UserService
@Service
@RequiredArgsConstructor
public class UserService {

	@Autowired
	private final UserRepository userRepository;

	@Autowired
	private final MemberRepository memberRepository;


	/**
	 * 로그인 처리
	 * 
	 * @param dto
	 * @return
	 */
	public User readUser(SignInDTO dto) {

		User userEntity = null;

		try {

			userEntity = userRepository.findByUserIdAndPassword(dto.getLoginId(), dto.getPassword());

		} catch (DataDeliveryException e) {
			e.printStackTrace();
			throw new DataDeliveryException("잘못된 처리 입니다.", HttpStatus.INTERNAL_SERVER_ERROR);
		} catch (Exception e) {
			e.printStackTrace();
			throw new RedirectException("알 수 없는 오류", HttpStatus.SERVICE_UNAVAILABLE);
		}
		if (userEntity == null) {
			throw new DataDeliveryException("아이디 또는 비밀번호가 잘못되었습니다.", HttpStatus.BAD_REQUEST);
		}

		return userEntity;
	}
user.xml
	<!-- select 로그인 -->
	<select id="findByUserIdAndPassword"
		resultType="com.library.bookwave.repository.model.User">
		select * from user_tb where login_id = #{loginId} and password = #{password}
	</select>
UserController
/*
	 * 로그인
	 * 주소설계: http://localhost:8080/user/sign-in
	 */
	
	// 로그인 화면 요청
	@GetMapping("/sign-in")
	public String signInPage() {
		return "user/signIn";
	}

	// 로그인 요청 처리
	@PostMapping("/sign-in")
	public String signInProc(SignInDTO dto) {
		System.out.println("DTO:" + dto);

		if (dto.getLoginId() == null || dto.getLoginId().isEmpty()) {
			throw new DataDeliveryException("아이디를 입력해주세요.", HttpStatus.BAD_REQUEST);
		}
		if (dto.getPassword() == null || dto.getPassword().isEmpty()) {
			throw new DataDeliveryException("비밀번호를 입력해주세요.", HttpStatus.BAD_REQUEST);
		}

		User principal = userService.readUser(dto);

		// 세션 메모리에 등록 처리
		session.setAttribute("principal", principal);

		// TODO 수정
		return "redirect:/user/sign-in";
	}
signIn.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ include file="../layout/header.jsp"%>
    <meta charset="UTF-8">
    <title>로그인</title>
    <link rel="stylesheet" href="/css/signIn.css" type="text/css" />


    <main class="container_wrapper">
        <section class="contents_wrap login">
            <div class="login_form_wrap">
				<form action="/user/sign-in" method = "post">

                <!-- 로그인 -->
                <div class="form_col_group valid_check">
                    <div class="col_box id">
                        <input type="text" title="아이디 입력" class="form_ip" id="loginId" name="loginId" placeholder="아이디를 입력해 주세요." >
                        <!-- 아이디 상태값 -->
                        <span class="form_desc tip"></span>
                    </div>
                    <div class="col_box pw">
                        <div class="form_ip_pw">
                            <input type="password" class="form_ip" id="password" name="password" placeholder="비밀번호를 입력해 주세요." title="비밀번호 입력">
                         
                        </div>
                    </div>
                    <!-- 로그인 페이지의 경고 문구는 모두 여기에 표시됩니다.  -->
                    <span class="valid_desc"></span>
                </div>
                <!-- // 로그인 -->

                <div class="btn_wrap justify">
                    <button class="btn_lg btn_light_gray" type="submit" id="loginBtn" >
                       로그인
                    </button>
                </div>
                </form>

                <!-- 아이디 저장 -->
                <div class="save_id_box">
                    <span class="form_chk">
                        <input id="formSaveId" type="checkbox" >
                        <label for="formSaveId">아이디 저장</label>
                    </span>
                    <div class="right_area">
                        <a href="#"><span class="text btn_text_id_link">아이디 찾기</span></a>
                        <span class="gap">|</span>
                        <a href="#"><span class="text btn_text_pw_link">비밀번호 찾기</span></a>
                    </div>
                </div>
                <!-- // 아이디 저장 -->

                <!-- SNS 로그인 -->
                <div class="sns_login_box">
                    <ul class="sns_login_list">
                        <li class="sns_login">
                            <button class="btn_sns_login naver">
                                <span class="hidden">네이버로그인</span>
                            </button>
                        </li>
                        <li class="sns_login">
                            <button class="btn_sns_login kakao">
                                <span class="hidden">카카오로그인</span>
                            </button>
                        </li>
                        <li class="sns_login">
                        <div class="btn_sns_login google" >
                            <a href="https://accounts.google.com/o/oauth2/v2/auth/oauthchooseaccount?client_id=202693057051-amq7bn7fcoblosijrvt32o1nnq1bt879.apps.googleusercontent.com&redirect_uri=http%3A%2F%2Flocalhost%3A8080%2Flogin%2Foauth2%2Fcode%2Fgoogle&response_type=code&scope=email%20profile&service=lso&o2v=2&ddm=1&flowName=GeneralOAuthFlow">
                            구글 로그인
                            </a>
                        </div>
                        </li>
                    </ul>
                </div>
                
    
                <!-- // SNS 로그인 -->

                <!-- 회원가입 -->
                <div class="btn_wrap justify">
                    <a href="/user/sign-up" class="btn_lg btn_line_primary" id="join">
                        <span class="text">회원가입</span>
                    </a>
                </div>
                <!-- // 회원가입 -->

            </div>
        </section>
    </main>
<%@ include file="../layout/footer.jsp"%>