[국비학원 기록/JSP] 액션태그(2)-useBean, setProperty, getProperty, 회원 가입 구현
my code archive
article thumbnail
반응형
useBean, setProperty, getProperty

1)자바 빈(Bean)

-Java EE 프로그래밍 시 여러 객체를 거치면서 만들어지는 데이터를 저장하거나 전달할 때 사용되는 클래스

-DTO (Data Transfer Object, 데이터 전송 객체)클래스,

 VO (Value Object, 값 객체)클래스와 같은 개념.

 

2)자바 빈 특징

-기본(default) 패키지 이외의 패키지에 속해있어야함.

-기본 생성자가 있어야함.

-각 속성(attribute, property)은 각각의 setter/getter를 가짐.

-setter/getter 이름의 첫 글자는 반드시 소문자.

-인자 없는 생성자를 반드시 가지며 다른 생성자도 추가 가능.

 

3)useBean ActionTag

<jsp:useBean id="빈 이름" class="패키지 이름 포함한 자바빈 클래스 이름" [scope="접근 범위"]/>

-JSP 페이지에서 자바 빈을 대체하기 위한 태그

 

4)setProperty/getProperty ActionTag

<jsp:getProperty name="자바 빈 이름" property="속성 이름"/>

-useBean 속성에 값을 얻는 태그

 

useBean ActionTag 회원 가입 구현

--이전 포스팅에서 생성했던 t_member 테이블 활용

 

memberForm.html
--회원가입 화면
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
<!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 = "member.jsp";            //서블릿 매핑 이름 지정함. 
                frmMember.submit();                        //서블릿으로 전송함.
            }
        }
    
    </script>
</head>
<body>
    <form name="frmMember" method="post" action="member.jsp" >
        <table>
            <th>회원 가입창</th>
            <tr>
                <td>아이디</td>
                <td><input type="text" name="id"></td>            <!-- 입력한 ID를 서블릿으로 전송함-->
            </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
MemberDAO.java
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
 
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
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<MemberBean> listMembers() {
        List<MemberBean> list = new ArrayList<>();
        
        //connDB();        // 네가지 정보로 DB를 연결함.
        
 
        
        try {
            conn = dataFactory.getConnection();            // DataSource를 이용해 DB에 연결함.
 
            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");        //조회한 레코드의 각 컬럼 값을 받아 옴.
                 
                 MemberBean vo = new MemberBean();
                 vo.setId(id);
                 vo.setPwd(pwd);
                 vo.setName(name);
                 vo.setEmail(email);
                 vo.setJoinDate(joinDate);                     //각 컬럼 값을 다시 MemberVO 객체의 속성에 설정함.
                 
                 list.add(vo);                                //설정된 MemberVO 객체를 다시 ArrayList에 저장함.
                         
            }
            
            rs.close();
            pstmt.close();
            conn.close();
            
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
                
        return list;        // 조회한 레코드의 개수만큼 MemberVO 객체를 저장한 ArrayList를 반환함.
    }
    
    public void addMember(MemberBean memberBean) {
        try {
            conn = dataFactory.getConnection();                    // DataSource를 이용해 DB 연결
            
            String id = memberBean.getId();                        // 테이블에 저장할 회원 정보 받아옴.
            String pwd = memberBean.getPwd();
            String name = memberBean.getName();
            String email = memberBean.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();
        }
    }
}
 
cs
MemberBean.java

--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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
package kr.co.ezenac.bean;
 
import java.sql.Date;
 
/*
 *  회원 테이블의 컬럼 이름과 동일하게
 *  이름과 자료형을 선언함.
 */
 
public class MemberBean {
 
    private String id;
    private String pwd;
    private String name;
    private String email;
    private Date joinDate;
    
    public MemberBean() {
        // TODO Auto-generated constructor stub
    }
    
    //인자가 4개인 생성자 추가
    public MemberBean(String id, String pwd, String name, String email) {
        super();
        this.id = id;
        this.pwd = pwd;
        this.name = name;
        this.email = email;
    }
    
    //getter/setter 추가
    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
member.jsp

--액션태그 사용하지 않은 ver.
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
<%@page import="java.util.List"%>
<%@page import="kr.co.ezenac.bean.MemberDAO"%>
<%@page import="kr.co.ezenac.bean.MemberBean"%>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%
    request.setCharacterEncoding("utf-8");
%>
<%
    String id = request.getParameter("id");
    String pwd = request.getParameter("pwd");
    String name = request.getParameter("name");
    String email = request.getParameter("email");
    
    MemberBean memberBean = new MemberBean(id, pwd, name, email);
    MemberDAO memberDAO = new MemberDAO();
    memberDAO.addMember(memberBean);
    List<MemberBean> membersList = memberDAO.listMembers();
%>
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>회원-목록</title>
</head>
<body>
    <table align="center" width="100%">
        <tr align="center" bgcolor="#99ccff">
            <td width="7%">아이디</td>
            <td width="7%">비밀번호</td>
            <td width="5%">이름</td>
            <td width="11%">이메일</td>
            <td width="5%">가입일</td>
        </tr>
        <%
            if(membersList.size()==0){
        %>
        <tr>
            <td colspan="5">
                <p align="center">
                    <b><span style="font-size: 9pt">등록된 회원이 없습니다.</span></b>
                </p>
            </td>
        </tr>
        <%
            }else{
                for(int i=0;i<membersList.size();i++){
                    MemberBean bean = membersList.get(i);
        %>
        <tr align="center">
            <td><%=bean.getId() %></td>
            <td><%=bean.getPwd() %></td>
            <td><%=bean.getName() %></td>
            <td><%=bean.getEmail() %></td>
            <td><%=bean.getJoinDate() %></td>
        </tr>
        <%
                }
            }
        %>
        <tr height="1" bgcolor="#99ccff">
            <td colspan="5"></td>
        </tr>
    </table>
</body>
</html>
cs
01.useBean 액션태그로 객체 생성 ver.

02.setProperty ver.

03. param 액션태그로 좀 더 간결하게 ver.

04. 동일한 빈 값을 자동으로 설정하는 와일드카드 * 사용 ver.

각각 버전을 확인할 때에는
memberForm.html 에서 이 부분만 바꿔가면서 실행하면 된다.

반응형
profile

my code archive

@얼레벌레 개발자👩‍💻

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

반응형