記錄

oracle database -3 본문

Web/JSP

oracle database -3

surhommejk 2018. 1. 17. 14:46

로그인, 회원가입, 회원정보 변경과 같은 일반적인 회원정보관리 사항을 구현해보는 강의였다








실습은 위에서 했던 것을 안하고 내가 설계한(더 간단하게) 것을 바탕으로 하였다







Home.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    </br>
    <button type="button" onclick="location.href='registration.jsp'" > 회원가입</button>
    <button type="button" onclick="location.href='modification.jsp'" > 회원정보 변경</button>
    <button type="button" onclick="location.href='login.jsp'" > 로그인</button>
    <button type="button" onclick="location.href='logout.jsp'" > 로그아웃</button></br></br>
    
    Hello~
    
    Welcome to my homepage!
    
</body>
</html>




login.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>

    <form action="loginck" method="post">
        아 이 디:<input type="text" name="id" size=15></br>
        비밀번호:<input type="password" name="pw" size=15></br>
        <input type="submit" value="로그인">
    </form>
        <button type="button" onclick="location.href='registration.jsp'">회원가입</button>

</body>
</html>




registration.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>
    
    </br></br></br>
    
    회원가입(모두 입력해주시기 바랍니다)</br></br>

    <form action="register" method="post">
    아 이 디:<input type="text" name="id" size="15"></br>
    비밀번호:<input type="password" name="pw" size="15"></br>
    휴 대 폰:<input type="text" name="tel" size="15"></br>
    지 역:<select name="region">
    <option value="seoul">서울</option>
    <option value="pusan">부산</option>
    <option value="ulsan">울산</option>
    <option value="gwanju">광주</option>
    <option value="daegu">대구</option>
    </select></br></br>
    <input type="submit" value="회원가입완료">
    <input type="reset" value="초기화">
    </form>

</body>
</html>




register.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import jdk.nashorn.internal.ir.RuntimeNode.Request;

import java.sql.*;

@WebServlet("/register")
public class register extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private Connection cn;
    private Statement stm;
    private int rs;

    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String uid = "scott";
    String upw = "tiger";

    public register() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.getWriter().append("Served at: ").append(request.getContextPath());
        doAction(request, response); // doGet으로 하든 doPost로 하든 doAction실행 되도록 함
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        doAction(request, response); // doGet으로 하든 doPost로 하든 doAction실행 되도록 함

    }

    protected void doAction(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html; charset=euc-kr");

        // 변수값 받아오기
        String id = request.getParameter("id");
        String pw = request.getParameter("pw");
        String tel = request.getParameter("tel");
        String region = request.getParameter("region");

        // 받은 데이터를 바탕으로 쿼리문 작성
        String query = "insert into member values('" + id + "','" + pw + "','" + tel + "','" + region + "')";

        try {

            Class.forName(driver);
            cn = DriverManager.getConnection(url, uid, upw);
            stm = cn.createStatement();
            rs = stm.executeUpdate(query);

            if (rs == 1) {
                System.out.println("회원가입 완료");
                response.sendRedirect("login.jsp");
            } else {

                response.sendRedirect("login.jsp");
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {

            if (stm != null)
                stm.close();
            if (cn != null)
                cn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }

    } // doAction end

} // class end




loginck.java

import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/loginck")
public class loginck extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private Connection cn;
    private Statement stm;
    private ResultSet rs;
    private int i = 0;
    
    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String uid = "scott";
    String upw = "tiger";

    public loginck() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html; charset=euc-kr");

        // login.jsp에서 id와 pw를 받아서 초기화
        String id = request.getParameter("id");
        String pw = request.getParameter("pw");

        String query = "select id, pw from member";

        try {
            Class.forName(driver);
            cn = DriverManager.getConnection(url, uid, upw);
            stm = cn.createStatement();
            rs = stm.executeQuery(query);

            while (rs.next()) {
                String uid = rs.getString("id");
                String upw = rs.getString("pw");

                if ((id.equals(uid)) && (pw.equals(upw))) {
                    System.out.println("로그인 성공");
                    response.sendRedirect("Home.jsp");
                    i++;
                }
                
            }

            if (i == 0) response.sendRedirect("loginFail.jsp");

        } catch (Exception e) {
            e.printStackTrace();
        }
        try {
            if (rs != null)
                rs.close();
            if (stm != null)
                stm.close();
            if (cn != null)
                cn.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }

} // class end




modification.jsp

<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
<title>Insert title here</title>
</head>
<body>

    </br>
    </br>
    </br> 회원정보 변경(모두 입력해주시기 바랍니다)
    </br>
    </br>

    <form action="changing" method="post">
        아 이 디:<input type="text" name="id" size="15"></br>
        비밀번호:<input type="password" name="pw" size="15"></br>
        휴 대 폰:<input type="text"    name="tel" size="15"></br>
        지 역:<select name="region">
            <option value="seoul">서울</option>
            <option value="pusan">부산</option>
            <option value="ulsan">울산</option>
            <option value="gwanju">광주</option>
            <option value="daegu">대구</option>
        </select></br></br>
        <input type="submit" value="회원정보수정">
        <input type="reset" value="초기화">
        <button type="button" onclick="location.href='delete.jsp'" >회원탈퇴</button>
    </form>


</body>
</html>




changing.java

import java.sql.*;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/changing")
public class changing extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private Connection cn;
    private Statement stm;
    private int rs;

    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String uid = "scott";
    String upw = "tiger";

    public changing() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html; charset=euc-kr");

        String id = request.getParameter("id");
        String pw = request.getParameter("pw");
        String tel = request.getParameter("tel");
        String region = request.getParameter("region");
        
        String query = "update member set id = '" + id + "', pw = '" + pw + "', tel = '" + tel + "', region = '" + region
                + "'";

        try {

            Class.forName(driver);
            cn = DriverManager.getConnection(url, uid, upw);
            stm = cn.createStatement();
            rs = stm.executeUpdate(query);

            if (rs == 1) {
                System.out.println("정보변경 완료");
                response.sendRedirect("Home.jsp");
            } else {
                System.out.println("정보변경 실패");
                response.sendRedirect("Home.jsp");
            }

        } catch (Exception e)

        {
            e.printStackTrace();
        }
        try {

            if (stm != null)
                stm.close();
            if (cn != null)
                cn.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }
} // class end




unregister.java

import java.sql.*;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/unregister")
public class unregister extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private Connection cn;
    private Statement stm;
    private ResultSet rs;
    private int i = 0;

    String driver = "oracle.jdbc.driver.OracleDriver";
    String url = "jdbc:oracle:thin:@localhost:1521:xe";
    String uid = "scott";
    String upw = "tiger";

    public unregister() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html; charset=euc-kr");

        String id = request.getParameter("id");
        String pw = request.getParameter("pw");
        String phone = request.getParameter("phone");
        String region = request.getParameter("region");

        String search = "select id from member";
        String query = "delete from member where id='" + id + "'";

        try {

            Class.forName(driver);
            cn = DriverManager.getConnection(url, uid, upw);
            stm = cn.createStatement();
            rs = stm.executeQuery(search);

            while (rs.next()) {
                if (rs.getString("id").equals(id))
                    i = stm.executeUpdate(query);

            }
            if (i != 0) {
                System.out.println("회원탈퇴 완료");
                response.sendRedirect("Home.jsp");
            } else if (i == 0) {
                System.out.println("회원탈퇴 실패");
                response.sendRedirect("Home.jsp");
            }
        } catch (Exception e)

        {
            e.printStackTrace();
        }

    }
} // class end



cf)

1) loginFail.jsp, logout.jsp는 너무 간단해서 생략

2) 세션 활용은 하지 않았으나 강의에서는 세션 활용을 하였음(추후 세션 학습 및 정리 필요)




tip_1) servlet에서 만드는 session 과 jsp 내에 있던 session은 뭐가 다른가?


test.jsp

    <%
        session.setAttribute("name1", "jk");
        session.setAttribute("name2", "블스");
    %>

    <form action="testprint" method="post">

        <input type="submit" value="이동">

    </form>


testprint.java

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@WebServlet("/testprint")
public class testprint extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public testprint() {
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
    }

    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/html; charset=euc-kr");
        PrintWriter wt = response.getWriter();

        HttpSession ss1 = request.getSession();
        String name1 = (String) ss1.getAttribute("name1");
        
        HttpSession ss2 = request.getSession();
        String name2 = (String) ss2.getAttribute("name1");
        
        // 세션 변수를 두 개 만들었고 둘 다 request.getSession()으로 받아서 초기화 하였다
        // 받아온 세션이 같은 세션인지를 보기 위해서 같은 값을 밑에서 출력한다
        
        wt.println("<html>");
        wt.println("<head>");
        wt.println("</head>");
        wt.println("<body>");

        wt.println("출력 테스트_ name1 출력 : " + name1 + "<br>"); // jk
        wt.println("출력 테스트_ name2 출력 : " + name2 + "<br>"); // jk
        
        // 같은 값임을 확인했다
        // 결론적으로 servlet에서 각각 다른 세션 변수로 생성한 각각 다른 세션이라도
        // 결국 같은 주소값을 가지고 있다는 것을 알 수 있다
    
        wt.println("</body>");
        wt.println("</html>");

    }

} // class end

/*

서버는 각각의 클라이언트에게 고유의 세션 id를 부여하게 되는데

결국 서블릿에서 세션을 몇 개를 만들든 어차피 request객체에서 세션을 get하므로

서블릿에서 만든 세션 변수들은 같은 주소값을 가지게 된다

*/



    private boolean pwConfirm() {
        boolean rs = false;
        
        String sessionpw = httpsession.getAttribute("password");
        
        if(sessionpw.equlas(pw) {
            rs = true;
        } else {
            rs = false;
        }
        
        return rs;
    }









tip_2) servlet에서 session을 이용해 비밀번호 인증하는 함수 방식

    private boolean pwConfirm() {
        boolean rs = false;
        
        String sessionpw = httpsession.getAttribute("password");
        
        if(sessionpw.equlas(pw) {
            rs = true;
        } else {
            rs = false;
        }
        
        return rs;
    }


유용하니까 익혀두자. 핵심은 간단하다.


'boolen 변수 선언해서 기본 false로 초기화 하고 session에서 받아온 password값과 비교해서 같으면 true, 다르면 false를 반환(혹은 else문 버리고 그냥 if문만 걸어놔도 됨)한다. 결과적으로 servlet에서 간단히 pwconfirm()을 하면 password를 확인 하여 맞으면 true 틀리면 false를 반환하게 된다'


전제 조건은 미리 password를 session에 넣어둔 상태여야 한다는 것이다.

'Web > JSP' 카테고리의 다른 글

회원 인증 프로그래밍  (0) 2018.01.22
DAO, DTO, PreparedStatement, 커넥션 풀(DBCP)  (0) 2018.01.19
oracle database -2 (JDBC 상세설명 포함)  (0) 2017.12.08
oracle database -1  (0) 2017.12.08
자바 빈(bean)  (0) 2017.12.07
Comments