본문 바로가기
CLASS/SERVLET

#6-1 / 간편 회원가입⭐

by eungSe__ 2024. 6. 18.
⚡ 회원가입

- html

<body>
    <form id="frm">
        <p>회원 로그인</p>
        아이디 : <input type="text" name="uid" id="uid"><br>
        패스워드 : <input type="text" name="upass" id="upass"><br>
        <button>로그인</button>
    </form>
</body>

<script type="text/javascript">
	$(function(){
		$("#frm").submit(function(){
			if($("#uid").val() == "" || $("#upass").val() == ""){
				alert("id 및 패스워드를 입력하세요");
				return false;
			}else{
				$("#frm").attr("method","post");
				$("#frm").attr("action","./loginok.do");
				return true; //submit에선 이렇게 작성해도됨
			}
		});		
	})
</script>​


-  module : database 접속 환경설정 파일 생략 (https://dev-eunse.tistory.com/148 와 동일)

- servelete (insertok.java)
public class insertok extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
	dbconfig db = new dbconfig(); //db정보
	PrintWriter pw = null;
	private Connection con = null; //보안 중요
	private Statement st = null;
		
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String uid = request.getParameter("uid");
		String upass = request.getParameter("upass");
		String uname = request.getParameter("uname");
		
		try {
			this.con = this.db.info();
			
			//sql문법(=DML)
			String sql = "insert into user(uidx,uid,upass,uname,ujoin) "
					+ "values('0','"+ uid +"','"+ upass +"','"+ uname +"',now())";
			this.st = this.con.createStatement(); //sql 문법 실행시키는 라이브러리
			int result = this.st.executeUpdate(sql); //실행 및 결과값을 return(숫자로 return)
			this.pw = response.getWriter();
			
			if(result>0) { //정상 query 작동
				this.pw.write("<script>"
						+ "alert('회원가입이 완료되었습니다');"
						+ "location.href='./login.html';"
						+ "</script>");
			}else { //오류 query 작동
				this.pw.write("<script>"
						+ "alert('회원가입 실패!');"
						+ "history.go(-1);"
						+ "</script>");
			}
		}catch(Exception e) {
			System.out.println("database 연결실패");
		}finally {
			try {
				this.pw.close();
				this.st.close();
				this.con.close();
			}catch(Exception e) {
				System.out.println("database 접속해제 실패");
			}
		}
	}

}

 

 

🔽 회원가입 완료 후 로그인 페이지로 이동

 

⚡ 로그인

ResultSet :

select문에서만 사용하는 라이브러리 / 변수.next() 로 발동 필수
배열형태(db 전용배열) + bufferReader 기능 포함
getString,getInt,getArary...등 : 데이터베이스에 맞는 자료형을 가져올 때 사용 (getint시 1부터 : 0은 다른거임..)

public class loginok extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	dbconfig db = new dbconfig();
	Connection con = null;
	PrintWriter pw = null;
	Statement st = null;
	HttpSession hs = null; //session
	
	//로그인파트
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		
		String uid = request.getParameter("uid");
		String upass = request.getParameter("upass");
		
		try {
			this.con= this.db.info();
			String sql = "select * from user where uid='"+uid+"' and upass='"+upass+"'";
			this.st = this.con.createStatement();
			ResultSet rs = this.st.executeQuery(sql); //ResultSet : select문에서만 사용하는 라이브러리
			
			//rs.next(); //rs 1번은 발동시켜줘야함 (=buffer같은거)			
			//System.out.println   (rs.getString("uname")); //로그인 성공시 username sysout
			
			this.pw = response.getWriter();
			String mid=""; //session에 저장할 id 
			String mname=""; //session에 저장할 이름
			while(rs.next()) {
				mid = rs.getString("uid");
				//System.out.println(rs.getDate(5)); //timestamp는 getdate or getstring으로 받음
				mname = rs.getString("uname");
			}
			//=> 로그인페이지라 반복문에 넣을필요 x,게시판등 여러번 가져올거라면 반복문에 넣어야함(배열이기때문)
			
			if(mname.equals("")) { //select의 값이 없을 경우
				this.pw.write("<script>"
						+ "alert('아이디 및 비밀번호를 확인하세요!');"
						+ "history.go(-1);"
						+ "</script>");
			}else { //해당 sql쿼리가 정상 작동하여 값을 로드하였을 경우
				this.hs = request.getSession();
				this.hs.setAttribute("id",mid);
				this.hs.setAttribute("name",mname);
				
				this.pw.write("<script>"
						+ "alert('로그인 성공!');"
						+ "location.href = './top.jsp';"
						+ "</script>");
			}
			this.pw.close();
			
			rs.close();
		}catch(Exception e) {
			System.out.println(e);
			System.out.println("db연결실패!!");
			try {
				this.st.close();
				this.con.close();
			}catch(Exception e2) {
				System.out.println("db 해제 실패 !");
			}
		}
	}
}

 

 

'CLASS > SERVLET' 카테고리의 다른 글

#6-3 / storage  (0) 2024.06.18
#6-2 / session,cookie  (0) 2024.06.18
#5 / 🌺 MVC? / excute,statement정리  (0) 2024.06.17
#4-2 / 동의 체크박스 Map 배열로 받기  (0) 2024.05.31
#4-1 / html에서 java class로 값 전달,로그인 예제  (0) 2024.05.31