프로젝트

주말에 프로젝트조금해보기(회원가입만 해보자...!)

동곤일상 2025. 5. 10. 16:33
반응형

1) 회원가입폼 수정

2) picture.jsp 생성(사진관련전부)

3) id생성 및 DB연결 (s+랜덤한숫자6개)

4) 테스트


 

1) 회원가입폼 수정 (registerUser)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>회원가입</title>
<link rel="stylesheet"
	href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.2/dist/css/bootstrap.min.css">

</head>
<body>
<!--  onsubmit :  나의 form 내부에 submit버튼 클릭되면 
			form 태그에 이벤트 발생(target == form)
return input_check(this) : input_check()함수 호출 , 매개변수this : form객체를 의미					
				-->
<form action="join" name="f" method="post" onsubmit="return input_check(this)">
	<input type="hidden" name="picture" value=""><!-- 업로드된 이미지의 이름이 들어갈태그 -->
	<table class="table">
		<tr>
		<td rowspan="4" valign="bottom">
		<img src="" width="100" height="120"  id="pic"><br>

		<font size="1"><a href="javascript:win_upload()">사진등록</a></font>
		</td><th>아이디</th>
		<td><input type="text" name="id"  class="form-control">
		<button type="button" onclick="idchk()" class="btn btn-dark" id="chk" name="chk">중복검색</button>
		</td></tr>
		<tr><th>비밀번호</th><td><input type="password" name="pass" onkeyup="pChk(this)"></td></tr>
		<tr><td id="passValid"></td></tr>
		<tr><th>이름</th><td><input type="text" name="name"></td></tr>
		<tr><th>성별</th>
		<td>
		<label for="gender1" class="form-check-label">
		남<input type="radio" name="gender" id="gender1" value="1">
		</label>
		
		<label for="gender2" class="form-check-label">
		여<input type="radio" name="gender" id="gender2" value="2" >
		</label>
		
		</td></tr>
		<tr><th>전화번호</th><td colspan="2"><input type="text" name="tel" class="form-control" onkeyup="tChk(this)"></td></tr>
		<tr><td id="telValid"></td></tr>
		<tr><th>이메일</th><td colspan="2"><input type="text" name="email" class="form-control" onkeyup="eChk(this)"></td></tr>
		<tr><td id="emailValid"></td></tr>
		<!-- button태그의 기본type : submit임 -->
		<tr><td colspan="3"><button class="btn btn-outline-dark">회원가입</button ></td></tr>
	</table>
</form>
<script>
function pChk(p){
	const passVal = document.querySelector("#passValid");
	if(!valid(p.value,'pass')){
		passVal.innerHTML= '특수문자포함 8~16자리';
		passVal.style.color='red';
	}
	else{
		passVal.innerHTML= '유효한비밀번호';
		passVal.style.color='green';
	}
}
function tChk(t){
	const telVal = document.querySelector("#telValid");
	if(!valid(t.value,'tel')){
		telVal.innerHTML= '올바른 휴대폰번호입력바람';
		telVal.style.color='red';
	}
	else{
		telVal.innerHTML= '유효한 번호';
		telVal.style.color='green';
	}
}
function eChk(e){
	const emailVal = document.querySelector("#emailValid");
	if(!valid(e.value,'email')){
		emailVal.innerHTML= '올바른 Email형식작성하세요';
		emailVal.style.color='red';
	}
	else{
		emailVal.innerHTML= '유효한E-mail';
		emailVal.style.color='green';
	}
}

function valid(text,type){
	if(type==='email'){//넘어온값과 name=email의 값이 동일할때
		const regex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9._]+\.[a-zA-Z]{2,}$/;
		return regex.test(text);
	}
	else if(type==='tel'){ //넘어온값과 name=tel의 값이 동일할때
		const regex = /^(01[0126789])-?\d{3,4}-?\d{4}$/;
		return regex.test(text);
	}
	else if(type==='pass'){ //비밀번호유효성검사
		const regex = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[\W_])[A-Za-z\d\W_]{8,16}$/;
		//(?=.*[A-Za-z]) → 문자열 어딘가에 영문자가 있어야 해 (확인만)
		//\W : 특수문자 , [A-Za-z\d\W_]{8,16} : 해당문자들이 8개~16개존재해야함
		return regex.test(text);
	}
}

	
    
function input_check(f){
	//f : <form...>
	//f.id : <input name="id">name이 id인태그
	if(f.id.value.trim() == ""){ 
		alert("아이디입력")
		f.id.focus(); //name이id인 곳에 포커스를 둠
		return false; //기본이벤트 취소
	}
	if(f.pass.value.trim() == ""){ 
		alert("비밀번호입력")
		f.pass.focus();
		return false; 
	}
	if(f.name.value.trim() == ""){ 
		alert("이름입력")
		f.name.focus();
		return false; 
	}
	if(f.gender.value.trim() == ""){ 
		alert("성별체크")
		return false; 
	}
	if(f.tel.value.trim() == ""){ 
		alert("전화번호입력바람")
		f.tel.focus();
		return false; 
	}
	if(f.email.value.trim() == ""){ 
		alert("email입력바람")
		f.email.focus();
		return false; 
	}
	if(!(valid(f.pass.value.trim()) 
		&& valid(f.email.value.trim())
		&& valid(f.tel.value.trim()))){ //3개중 한개라도 유효성검사를 실패했다면 실행
	alert("형식을준수해주세요")
	return false;
	}
	return true;//아이디비번이름이 입력됐다면 true
}

function win_upload(){
	let op = "width=500,height=500 ,top=50 ,left=150";
	open("pictureForm","",op);
	//pictureForm.jsp를 연다 (해당페이지가 opener가 될것임)
}

</script>
</body>
</html>

 

 

2)picture.jsp 생성

(사진의 경로 , 사진이름을 opener의 picture , img에 넣어주는곳)

(실제페이지는 존재하지않음 작업만처리해줌)

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<script>
img = opener.document.getElementById("pic");//id="pic" ..이미지객체임
img.src = "${pageContext.request.contextPath}/picture/${fname}"; 
/*form하위의 name=picture인 값에(type=hidden) 넣어라
 * DB에 경로를 전부다 넣기에는 길다.
 */
opener.document.f.picture.value = "${fname}";
//opener : registerImg를 열게만든 창 (ex)registerUser의 picture에 이미지이름을넣는다.
//self : 현재페이지
self.close();//창을 닫는다
</script>

 

mypageController에 picture매핑부분을 추가해줬음

@RequestMapping("picture")
	public String picture(HttpServletRequest request, HttpServletResponse response) throws IOException {
		String path = request.getServletContext().getRealPath("")+"/picture/";
		//기준 디렉토리 의 실제 경로
		//D:\java\.metadata\.plugins\org.eclipse.wst.server.core\tmp0\wtpwebapps\LMSProject1\picture
		String fname = null;
		File f = new File(path);//업로드되는 폴더정보
		if(!f.exists()){
			f.mkdirs(); //없으면 폴더생성
		}
		//request : 이미지데이터저장
		//path : 업로드되는 폴더정보
		//10*1024*1024 : 최대업로드크기(10M)
		//new DefaultFileRenamePolicy() : 중복파일명존재시 이름변경해

		MultipartRequest multi = new MultipartRequest(
					request,path,10*1024*1024,"UTF-8",new DefaultFileRenamePolicy());
		fname = multi.getFilesystemName("picture");//사진명
		request.setAttribute("fname", fname);
		return "mypage/picture";
	}

 


3) id자생성 및 DB연결 (s+랜덤한숫자6개)

mypageController 에IdChk메서드 추가

package controller.mypage;

import java.io.File;
import java.io.IOException;
import java.util.Random;

import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.mindrot.jbcrypt.BCrypt;

import com.oreilly.servlet.MultipartRequest;
import com.oreilly.servlet.multipart.DefaultFileRenamePolicy;

import gdu.mskim.MskimRequestMapping;
import gdu.mskim.RequestMapping;
import model.dao.mypage.StudentDao;
//http://localhost:8080/LMSProject1/dist/pages/mypage/registerUserChk
@WebServlet(urlPatterns = {"/mypage/*"},
initParams = {@WebInitParam(name="view", value="/dist/pages/")}
)
public class MypageController  extends MskimRequestMapping{
	
	
	
	public String IdChk(String a) { //아이디를 만들어줌 교수는 pxxxx , 학생은 sxxxx
		int[] num = {1,2,3,4,5,6,7,8,9,10};
		String sNum="s";
		
		for(int i=0;i<5;i++) {
			//0 ~ (num.length-1)의 랜덤한숫자반환
			int ranNum = new Random().nextInt(num.length);
			sNum+=num[ranNum]; //랜덤한 5개의숫자
		}
		StudentDao memberDao = new StudentDao();
		
		while(true) { 
        //Dao의 idchk메서드에 랜덤하게만든 id를 넘긴다
			if(memberDao.idchk(sNum)) { //true(id가존재하지않을 시 )면 루프탈출
				break;
			}
			else {
				int iNum = Integer.parseInt(sNum);//sNum을 Integer로형변환 
				iNum +=1; // 1 증가
				sNum = String.valueOf(iNum); // sNum으로 다시넣기
			}
		}
		return sNum;
	}
	
	
	
		@RequestMapping("registerUserChk")
	public String  registerUser(HttpServletRequest request , HttpServletResponse response) {
		
		String name  = request.getParameter("name");
		String birth = request.getParameter("birth");
		String pass = request.getParameter("password");
		String hashpw = BCrypt.hashpw(pass, BCrypt.gensalt());//hashPassword : 암호화 (복호화는불가능)
		String position = request.getParameter("position");
		String picture = request.getParameter("picture");
		String idChk = IdChk(position);
		
		System.err.println("pictureName : "+picture);
		System.out.println("id : "+idChk);
		System.err.println("학번 : "+idChk.substring(1)); //앞에영어를 제외한것이 학번
		System.out.println("pass : "+pass);
		System.out.println("hashpass : "+hashpw);
		System.out.println("birthday : "+birth);
		System.out.println("name : "+ name);
		return "mypage/doLogin";
	}
}

파라미터로 직급정보(학생,교수를받아) 

직급에따라 아이디의 시작 문자를 다르게할거임(아직미완성)

교수 : p + 5자리숫자

학생 : s + 6자리숫자

여기서 문자를뺀게 학번이될거임

(교수는 학번이없음!!!!!)

 


StudentDao

/java/model/dao/mypage/StudentDao.java

package model.dao.mypage;

import org.apache.ibatis.session.SqlSession;

import config.MyBatisConnection;

public class StudentDao {
	
	public boolean idchk(String id) {
		SqlSession connection = MyBatisConnection.getConnection();
		int x  = (Integer)connection.selectOne("student.cnt",id);
		if(x!=0) {
			return false;
		}
		return true;
		
	}

}

 

파라미터로 넘겨받은 id를 이용해 mapper에서 id가존재하는지 검증 후

true or false반환(이미조재하는아이디라면 1을 반환할것임 false)

 

 


/resources/mapper/mybatis-config.xml

config파일에 Mapper파일의 정보를 꼭 넣어줘야해!!!

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration PUBLIC "-//mybatis.org/DTD config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<!-- config파일에서 사용되는 환경변수 설정 -->
  <properties resource="mapper/mybatis.properties" />
  
  <!-- 별명들 -->
  <typeAliases>
.....
  	<typeAlias type="domain.Student" alias="Student" />  	
  </typeAliases>
  
  <!-- Connection 객체  -->
  <environments default="development">
    <environment id="development">
      <transactionManager type="JDBC" />
      <dataSource type="POOLED" >
         <property name="driver" value="${driver}"/>
         <property name="url" value="${url}"/>
         <property name="username" value="${username}"/>
         <property name="password" value="${password}"/>
      </dataSource>
    </environment>
  </environments>
  <!-- 위에서 ${}로 properties에서 지정한값들을 가져온다 -->
  
  <!--  sql 구문을 가진 파일 목록 -->
  <mappers>
 .......
  	<mapper resource="mapper/student/StudentMapper.xml"/>
  </mappers>

</configuration>

StudentMapper

/resources/mapper/student/StudentMapper.xml

<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">


<mapper namespace="student">
<select id="cnt" resultType="int" parameterType="String"> 
		select count(*) from student where student_id=#{id}
	</select>
</mapper>

int를 반환


4)테스트