Day 5(9/21) 회원 추가 기능 구현

2016. 9. 27. 11:16Programming/JSP

MemberAdd.java

index.jsp에서 회원 추가하는 기능을 구현


<구성 요소>


1) INSERT 쿼리 실행


2) 클라이언트가 입력한 파라미터 저장

String id = req.getParameter("uId");


3) 이러한 파라미터를 SQL문 속 ?에 모두 채워준다.


pstmt = conn.prepareStatement(sql);

pstmt.setString(1, id);


4) 입력한 값 유무(insert:0)에 따라 분기


5) 존재하는 아이디일 경우 경고창 띄우기


<script>

alert("존재하는 아이디. 저장실패!"); //확인 버튼 누르기 전까지 대기

history.go(-1); //이전 페이지로

</script>


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
 
import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
 
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletResponse; //서버가 clinet에 응답
import javax.servlet.http.HttpServletRequest; //client가 서버에 요청
import javax.servlet.annotation.WebServlet;
 
//DB 연관 라이브러리
import java.sql.DriverManager; //접속 DB 드라이버를 설정
import java.sql.Connection; //DB 접속해서
import java.sql.PreparedStatement; //쿼리를 실행하는 클래스
import java.sql.ResultSet; //쿼리의 결과값을 받는다.
 
@WebServlet("/MemberAdd")
public class MemberAdd extends HttpServlet {
          String url = "jdbc:mysql://localhost:3306/JAVA_LESSON" // DB 서버 주소
                              + "?useUnicode=true&characterEncoding=utf8";
          String uid = "root";
          String upw = null// cmd 창에 mysql -uroot -p
 
          @Override
          protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
                    Connection conn = null;
                    String sql = "INSERT INTO MEMBER (id,pwd,name,phone,email,admin) VALUES(?,?,?,?,?,?)";
                    String id_sql = "SELECT id FROM MEMBER WHERE id = ?";
                    PreparedStatement pstmt = null// sql 실행하는 클래스
                    ResultSet rs = null// 결과값 받는 클래스
                    boolean flag = false// 결과값이 있을 때만 돌아가게 하기 위한 flag 변수
                    int insert = 0// 저장을 몇 개 성공했는지 확인
                    req.setCharacterEncoding("UTF-8");

 

                    //파라미터 받아오기

                    String id = req.getParameter("uId");
                    String pwd = req.getParameter("uPass");
                    String name = req.getParameter("uName");
                    String phone = req.getParameter("uPhone");
                    String email = req.getParameter("uEmail");
                    int admin = Integer.parseInt(req.getParameter("admin")); // Integer.parseInt:숫자로 바꿨다가 char형으로
                                                                                                            
                                                                                                                                                                 
                    try {
                              Class.forName("com.mysql.jdbc.Driver");
                              conn = DriverManager.getConnection(url, uid, upw);
 
                              pstmt = conn.prepareStatement(id_sql);
                              pstmt.setString(1, id);
                              rs = pstmt.executeQuery(); // select문으로 id 검색한 결과값 저장(해당 id가 있을 경우에만
                                                                                                    // 저장됨)
                              if (!rs.next()) {
                                        flag = true// 저장된 결과값이 없을 때(=id가 중복되지 않을 때)에 밑에 것이 돌아가도록
                              }
                              if (flag) {
                                        pstmt = conn.prepareStatement(sql);
                                        pstmt.setString(1, id);
                                        pstmt.setString(2, pwd);
                                        pstmt.setString(3, name);
                                        pstmt.setString(4, phone);
                                        pstmt.setString(5, email);
                                        pstmt.setInt(6, admin);
                                        insert = pstmt.executeUpdate(); // 몇 개의 데이터 저장됐는지 표시
                              }
 
                              if (insert > 0) {
                                        resp.sendRedirect("./MemberList"); // a 태그 같은 것. 동작이 끝나면 자동으로 돌아감
                                                                                                                         
                              } else {
                                        resp.sendRedirect("./index.jsp");
                              }
                    } catch (Exception e) {
                              e.printStackTrace();
                    } finally {
                              try {
                                        if (pstmt != null) {
                                                  pstmt.close();
                                        }
                                        if (conn != null) {
                                                  conn.close();
                                        }
                              } catch (Exception e) {
                                        e.printStackTrace();
                              }
                    }
          }
}
 
cs