INTP의 멋대로 개발 세상

[📚상품 구매 사이트 3단계] 구매자 서버 만들기 - 4. 회원가입 기능 만들기 본문

KDT 풀스택 국비 과정/파이널 프로젝트(미니)

[📚상품 구매 사이트 3단계] 구매자 서버 만들기 - 4. 회원가입 기능 만들기

인팁구름 2023. 4. 17. 15:39

 

 

📺 화면 구현📺

 

회원가입 화면

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%> <%@ include file="../layout/header.jsp"%>

<div class="container">
    <form action="/join" method="post" name="form" contenttyp>
        <div class="mb-3 mt-3">
            <input
                type="text"
                class="form-control"
                placeholder="아이디"
                name="userName"
            />
        </div>
        <div class="mb-3">
            <input
                type="password"
                class="form-control"
                placeholder="비밀번호"
                name="userPassword"
            />
        </div>
        <div class="mb-3">
            <input
                type="email"
                class="form-control"
                placeholder="이메일"
                name="userEmail"
            />
        </div>

        <button
            type="submit"
            class="btn btn-primary">
            회원가입
        </button>
    </form>
</div>

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

 

회원가입 DTO 생성

 

나중에 알게된 건데.. 사용하지 않더라도 primary key는 넣어주자..!

안 넣어서 코드가 여러모로 복잡해졌었다..🤨

package shop.mtcoding.productapp_buyer.dto.user;

import lombok.Getter;
import lombok.Setter;

@Getter
@Setter
public class JoinDto {

    private String userName;
    private String userPassword;
    private String userEmail;

}

 

 Controller

package shop.mtcoding.productapp_buyer.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import shop.mtcoding.productapp_buyer.dto.user.JoinDto;
import shop.mtcoding.productapp_buyer.model.user.UserRepository;

@Controller
public class UserController {

    @Autowired
    private HttpSession session;
    
    @Autowired
    private UserRepository userRepository;
 
    @GetMapping("/joinForm")
    public String joinForm() {
        return "user/joinForm";
    }

    @PostMapping("/join")
    public String join(JoinDto joinDto) {

    // 유효성 체크
    if (joinDto.getUserName().isEmpty()) {
        throw new CustomException("username을 입력해 주세요.", HttpStatus.BAD_REQUEST);
    }
    if (joinDto.getUserPassword().isEmpty()) {
        throw new CustomException("password를 입력해 주세요.", HttpStatus.BAD_REQUEST);
    }
    if (joinDto.getUserEmail().isEmpty()) {
        throw new CustomException("email을 입력해 주세요.", HttpStatus.BAD_REQUEST);
    }

    // 기존 동일 유저 확인 (username,email만)
    if (userRepository.findByUserName(joinDto.getUserName()) != null) {
        throw new CustomException("이미 가입된 유저입니다.", HttpStatus.BAD_REQUEST);
    }
    if (userRepository.findByUserEmail(joinDto.getUserEmail()) != null) {
        throw new CustomException("이미 가입된 이메일입니다.", HttpStatus.BAD_REQUEST);
    }

    // 유저 정보 인서트
    userRepository.insert(joinDto);

    return "redirect:/";
    
    }

}

 

UserRepository

package shop.mtcoding.productapp_buyer.model.user;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;

import shop.mtcoding.productapp_buyer.dto.user.JoinDto;
import shop.mtcoding.productapp_buyer.dto.user.LoginDto;

@Mapper
public interface UserRepository {

    public void insert(JoinDto joinDto);

    public User findById(Integer userId);

    public User findByUserName(String userName);

    public User findByUserEmail(String userEmail);

    public User findByUsernameAndPassword(LoginDto loginDto);

    public List<User> findAll();

    public void update(User user);

    public void delete(Integer userId);
}

 

 

User.xml

세팅 때 insert 쿼리문에 created_at을 빠뜨려서 추가해 주었다

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="shop.mtcoding.productapp_buyer.model.user.UserRepository">

	<select id="findByUsername"
		resultType="shop.mtcoding.productapp_buyer.model.user.User">
		SELECT * FROM user WHERE user_name = #{userName}
	</select>
    
	<select id="findByUsernameAndPassword"
		resultType="shop.mtcoding.productapp_buyer.model.user.User">
		SELECT * FROM user WHERE user_name = #{userName} and user_password = #{userPassword}
	</select>
    
	<select id="findById"
		resultType="shop.mtcoding.productapp_buyer.model.user.User">
		SELECT * FROM user WHERE user_id = #{userId}
	</select>

	<insert id="insert">
		INSERT INTO user(user_name, user_password, user_email,
		created_at)
		VALUES(#{userName}, #{userPassword}, #{userEmail}, now())
	</insert>

	<select id="findAll"
		resultType="shop.mtcoding.productapp_buyer.model.user.User">
		SELECT * FROM user ORDER BY user_id DESC
	</select>
    
	<update id="update">
		UPDATE user SET user_password = #{userPassword}, user_email =
		#{userEmail}
		WHERE user_id = #{userId}
	</update>
    
	<delete id="deleteById">
		DELETE FROM user WHERE user_id = #{userId}
	</delete>
    
</mapper>

 


 

📊 결과 확인 📊

 

회원가입 화면

 

가입할 유저입력

 

회원가입 완료되면 로그인 창으로 이동

 

로그인 하기

 

로그인이 완료되면 상품 목록 페이지로 이동

 

DB에도 잘 들어가 있다!

 

Comments