[국비학원 기록/Servlet] 데이터베이스 연동 2, JNDI, 회원 정보 등록, 삭제하기
my code archive
반응형
DataSource 이용해 데이터베이스 연동

1) ConnectionPool 등장 배경

  -애플리케이션에서 DB 연결 과정에 시간이 많이 걸림(기존 연동 방법 문제점)

   ==>미리 Connection 객체를 생성한 후 미리 데이터베이스 연결을 맺음,

         애플리케이션은 DB 연동 작업 발생시 이 Connection 객체를 이용해서 작업.

 

2)JNDI(Java Naming and Directory Interface)

-필요한 자원을 키/값(key/value)쌍으로 저장한 후 필요할 때 키를 이용해 값을 얻는 방법.

-커넥션 풀에 적용

-톰캣 컨테이너가 ConnectionPool 객체를 생성하면 이 객체에 대한 JNDI 이름(key)을 미리 설정해놓음.

-그러면 웹 애플리케이션에서 DB와 연동 작업할 때 이 JNDI 이름으로 접근하여 작업을 수행함

 

<JNDI 사용한 DB 연결>

톰캣 server.xml 파일에 DB 정보를 입력.

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<Resource 
 
        name="jdbc/oracle" //DataSource에 대한 JNDI 이름
 
        auth="Container"
 
        type="javax.sql.DataSource"
 
        driverClassName="oracle.jdbc.driver.OracleDriver"
 
        url="jdbc:oracle:thin:@localhost:1521:XE"
 
        username="wdsql"
 
        password="0311"
 
        maxActive="50"
 
        maxWait="-1"
 
    />
cs

 

PreparedStatement

1)회원 정보를 저장하기 위해 ?(물음표)를 사용.

2)?는 id,pwd,name,email 순서대로 대응.

3)각 ?에 대응하는 값을 지정하기 위해 setter를 사용.

4)?은 1부터 시작함.

 

회원 정보 등록, 삭제
memberServlet.java

-doHandle() 메서드에서 command 값을 받아
만약(if) addMember이면 전송된 값을 받아옴,
delMember이면 (else if) id값을 받아와 회원 정보를 삭제함.
-memberForm.html에 작성된 값을 얻어와 MemberVO 객체에 저장 후 SQL문으로 전송.
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
import java.io.IOException;
 
 
import java.io.PrintWriter;
import java.sql.Date;
import java.util.List;
 
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("/member3")
public class MemberServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
 
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doHandle(request, response);
    }
    
    private  void doHandle(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out=response.getWriter();
        MemberDAO dao=new MemberDAO();                        
        
        
        String command=request.getParameter("command");        //command 값 받아옴.
        if(command !=null && command.equals("addMember")) {        //회원가입 창에서 전송된 command가 addMember이면
            String _id = request.getParameter("id");            //전송된 값들을 받아옴.
            String _pwd = request.getParameter("pwd");
            String _name = request.getParameter("name");
            String _email = request.getParameter("email");        //회원 가입 창에서 전송된 값들을 얻어와
            
            MemberVO vo=new MemberVO();                            //MemberVO 객체에 저장한 후
            vo.setId(_id);
            vo.setPwd(_pwd);
            vo.setName(_name);
            vo.setEmail(_email);
            
            
            dao.addMember(vo);        //SQL문을 실행할 메서드에 전달함.
            
        }else if(command!=null && command.contentEquals("delMember")) {
                String id=request.getParameter("id");
        }
            
            List<MemberVO> list= dao.listMembers();
            
            out.print("<html><body>");
            out.print("<table border=1><tr align='center' bgcolor='lightgreen'>");
            out.print("<td>아이디</td><td>비밀번호</td><td>이름</td><td>이메일</td><td>가입일</td><td>삭제</td></tr>");
            
            
            for(int i=0;i<list.size();i++) {                //조회환 회원 정보를 for문 <tr>태그 이용해 출력함.
                MemberVO memberVO = list.get(i);            //i번째를 가져오면 전부 MemberVO에 해당됨.
                String id=memberVO.getId();
                String pwd=memberVO.getPwd();
                String name=memberVO.getName();
                String email=memberVO.getEmail();
                Date joinDate=memberVO.getJoinDate();
                
                out.print("<tr><td>"+id+"</td><td>"
                                    +pwd+"</td><td>"
                                    +name+"</td><td>"
                                    +email+"</td><td>"
                                    +joinDate+"</td></td>"        //삭제 클릭하면 command값과 회원 ID를 서블릿으로 전송함
                                    +"<a href='/chap03_Servlet/member3?command=delMember&id=" + id+" '>삭제</a></td></tr>");
                
            }
            
            out.print("</table>");
            out.print("<a href='/chap03_Servlet/memberForm.html'>새 회원 등록하기</a>");
            out.print("</body></html>");
        
    }
    
}
cs
MemberDAO

-addMember() : DataSource를 이용해 데이터베이스와 연결
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
 
public class MemberDAO {
    
    private Connection conn;
    private PreparedStatement pstmt;
    private DataSource dataFactory;
    

    public MemberDAO() {
        try {
            Context ctx=new InitialContext();
            Context envContext=(Context)ctx.lookup("java:/comp/env");    //JNDI에 접근하기 위해 기본 경로를 지정함.
            //톰캣 context.xml에 설정한 name값인 jdbc/oracle를 이용해 톰캣이 미리 연결한 DataSource 받아오기
            dataFactory=(DataSource)envContext.lookup("jdbc/oracle");    
        } catch (NamingException e) {                                    
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public List<MemberVO> listMembers(){
        List<MemberVO> list=new ArrayList<>();
        
        
        try {
            
        conn=dataFactory.getConnection();
        
        String query="SELECT * FROM T_MEMBER";
        System.out.println(query);
        
        
            pstmt=conn.prepareStatement(query);        //prepareStatement()메서드에 SQL문을 전달해 객체 생성함.
            ResultSet rs = pstmt.executeQuery();    //미리 설정한 SQL문 실행함.
            
            while(rs.next()) {
                String id = rs.getString("id");
                String pwd=rs.getString("pwd");
                String name=rs.getString("name");
                String email=rs.getString("email");
                Date joinDate=rs.getDate("joinDate");    //조회한 레코드의 각 컬럼 값을 받아옴.
                
                MemberVO vo=new MemberVO();
                vo.setId(id);
                vo.setPwd(pwd);
                vo.setName(name);
                vo.setEmail(email);
                vo.setJoinDate(joinDate);                //각 컬럼 값을 다시 MemberVO 객체의 속성에 설정함.
                
                list.add(vo);
                
            }
            
            rs.close();
            pstmt.close();
            conn.close();
            
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        
        return list;                                    //조회한 레코드의 개수만큼 MemberVO 객체를 저장한 ArrayList를 반환함.
    }
    
    public void addMember(MemberVO memberVO) {
        
        try {
            conn=dataFactory.getConnection();            //DataSource를 이용해 DB 연결
            
            String id=memberVO.getId();                    //태이블에 저장할 회원 정보 받아옴.
            String pwd=memberVO.getPwd();
            String name=memberVO.getName();
            String email=memberVO.getEmail();
            
            String query="insert into t_member (id,pwd,name,email) values (?,?,?,?)";
            System.out.println("prepareStatement:" + query);
            
            pstmt=conn.prepareStatement(query);
            
            pstmt.setString(1, id);                        //insert문의 ?에 순서대로 회원 정보 셋팅
            pstmt.setString(2, pwd);
            pstmt.setString(3, name);
            pstmt.setString(4, email);
            
            pstmt.executeUpdate();                        
            pstmt.close();
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    
    public void delMember(String id) {
        try {
            conn = dataFactory.getConnection();
            
            String query="DELETE FROM T_MEMBER WHERE ID = ?";        //delete문을 문자열로 만듦.
            System.out.println("prepareStatement:"+query);
            
            pstmt=conn.prepareStatement(query);
            pstmt.setString(1, id);                //첫번째 '?'에 전달된 ID를 인자로 넣음.
            pstmt.executeUpdate();                //실질적으로 delete문 실행 => 테이블에서 해당 ID 회원 정보 삭제
            pstmt.close();
            
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
}
 
cs
MemberVO
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
package kr.co.ezenac.member04;
 
import java.sql.Date;
 
/*
 *  id       VARCHAR2(10)    PRIMARY KEY
,   pwd      VARCHAR2(10)    NOT NULL
,   name     VARCHAR2(50)
,   email    VARCHAR2(50)
,   joinDate DATE           DEFAULT sysdate
 */
 
public class MemberVO {
 
    private String id;
    private String pwd;
    private String name;
    private String email;
    private Date joinDate;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPwd() {
        return pwd;
    }
    public void setPwd(String pwd) {
        this.pwd = pwd;
    }
    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    public Date getJoinDate() {
        return joinDate;
    }
    public void setJoinDate(Date joinDate) {
        this.joinDate = joinDate;
    }
}
 
cs
memberForm.html

-자바스크립트를 활용하여 아이디,비밀번호,이름,이메일을 입력하지 않았을 경우 경고창 띄우기
-frmMember를 post 방식, member3과 매핑되도록 설정.
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
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원가입</title>
    <script type="text/javascript">
    
        function fn_sendMember() {
            
            var frmMember = document.frmMember;
            var id = frmMember.id.value;
            var pwd = frmMember.pwd.value;
            var name = frmMember.name.value;
            var email = frmMember.email.value;            //입력한 값들을 얻음.
        
            if(id.length==0 || id=="") {
            alert("아이디는 필수입니다.");
            }
            else if(pwd.length==0 || pwd=="") {
            alert("비밀번호는 필수입니다.");
            }
            else if(name.length==0 || name=="") {
            alert("이름은 필수입니다.");
            }
            else if(email.lenth==0 || email=="") {
            alert("이메일은 필수입니다.");
            }
            else {
            frmMember.method = "post";                //전송 방법을 post로 지정함.
            frmMember.action = "member3";            //서블릿 매핑 이름 지정함. 
            frmMember.submit();                        //서블릿으로 전송함.
        }
    }
    </script>
</head>
<body>
    <form action="frmMember">
        <table>
        <th>회원 가입창</th>
        <tr>
            <td>아이디</td>
            <td><input type="text" name="id"></td>
        </tr>
        <tr>
            <td>비밀번호</td>
            <td><input type="password" name="pwd"></td>
        </tr>
        <tr>
            <td>이름</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>이메일</td>
            <td><input type="text" name="email"></td>
        </tr>
        </table>
        <input type="button" value="가입하기" onclick="fn_sendMember()">
        <input type="reset" value="다시 입력">
        <input type="hidden" name="command" value="addMember">
    </form>
</body>
</html>
cs
반응형
profile

my code archive

@얼레벌레 개발자👩‍💻

포스팅이 좋았다면 "좋아요❤️" 또는 "구독👍🏻" 해주세요!

반응형