티스토리 뷰

이어서 servlet, biz, dao 를 만들어보자.

일반적으로 한 태스크당 하나의 메소드를 만든다. 


프로젝트 구성도



1. 문자를 UTF-8 로 인코딩한다.

CharacterEncodingFilter.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
package com.ktds.smahn.filter;
 
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
 
/**
 * Servlet Filter implementation class CharacterEncodingFilter
 */
public class CharacterEncodingFilter implements Filter {
 
    /**
     * Default constructor. 
     */
    public CharacterEncodingFilter() {
        
    }
 
    /**
     * @see Filter#destroy()
     */
    public void destroy() {
        
    }
 
    /**
     * @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
     */
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
 
        request.setCharacterEncoding("UTF-8");
        
        chain.doFilter(request, response);
    }
 
    /**
     * @see Filter#init(FilterConfig)
     */
    public void init(FilterConfig fConfig) throws ServletException {
 
    }
 
}
 
 
cs

이렇게 해주면 servlet에서 일일히 setCharacterEncoding("UTF-8") 을 해줄 필요가 없게 된다.


2. 데이터베이스의 컬럼대로 VO 클래스를 만들어준다.

MemberVO.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
 
package com.ktds.smahn.member.vo;
 
public class MemberVO {
    
    private String memberId;
    private String nickName;
    private String password;
    private String email;
    
    public String getMemberId() {
        return memberId;
    }
    public void setMemberId(String memberId) {
        this.memberId = memberId;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public String getPassword() {
        return password;
    }
    public void setPassword(String password) {
        this.password = password;
    }
    public String getEmail() {
        return email;
    }
    public void setEmail(String email) {
        this.email = email;
    }
    
    
 
}
 
cs


3. 로그인 버튼을 누르면 DoLogin 서블릿으로 온다. 이때, userId와 userPw를 가져와서 MemberVO의 인스턴스로 생성해준 loginMember에 넣어준다. 그리고 biz 클래스로 로그인 업무를 위임하고, 로그인 성공 여부를 받아 페이지를 넘기거나, 에러코드를 보여준다.

DoLoginServlet.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
 
package com.ktds.smahn.member.web;
 
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import com.ktds.smahn.member.biz.MemberBiz;
import com.ktds.smahn.member.vo.MemberVO;
 
/**
 * Servlet implementation class DoLoginServlet
 * 로그인 버튼 눌렀을 때 처리하는 서블릿
 */
public class DoLoginServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;
    
    private MemberBiz memberBiz;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public DoLoginServlet() {
        super();
        memberBiz = new MemberBiz();
    }
 
    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        response.sendError(HttpServletResponse.SC_FORBIDDEN, "로그인 할 수 없습니다.");
    }
 
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
        String memberId = request.getParameter("userId");
        String memberPassword = request.getParameter("userPw");
        
        MemberVO loginMember = new MemberVO();
        loginMember.setMemberId(memberId);
        loginMember.setPassword(memberPassword);
        
        boolean isLoginSuccess = memberBiz.login(loginMember, request);
        
        // 로그인 성공 여부에 따라 다음 페이지를 보여줄 것인지, 에러코드와 함께 그 페이지에 머물를것인지를 선택한다.
        if ( isLoginSuccess ) {
            response.sendRedirect("/list");
            return;
        }
        else {
            response.sendRedirect("/login?errorCode=1");
            return;
        }
        
    }
 
}
 
cs



4. dao 클래스를 생성하고 입력받은 아이디와 패스워드를 db에서 찾는 코드를 적는다.

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
 
package com.ktds.smahn.member.dao;
 
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
 
import com.ktds.smahn.member.vo.MemberVO;
import com.ktds.smahn.util.xml.XML;
 
/**
 * 
 * @author sm ahn
 *
 */
public class MemberDAO {
 
    public MemberVO getMemberByIdAndPassword(MemberVO member) {
        
        loadOracleDriver();
 
        Connection conn = null;
        PreparedStatement stmt = null;
        ResultSet rs = null;        
        
        try {
 
            conn = DriverManager.getConnection(Const.DB_URL, Const.DB_ID, Const.DB_PASSWORD);
 
            // 아이디, 패스워드를 테이블에서 꺼내온다.
            String query = XML.getNodeString("//query/member/getMemberByIdAndPassword/text()");
            stmt = conn.prepareStatement(query);
            stmt.setString(1, member.getMemberId());
            stmt.setString(2, member.getPassword());
 
            rs = stmt.executeQuery();
 
            MemberVO validMember = null;
 
            // 한건만 가지고 올 것이므로 if문을 쓴다.
            // 세션은 노출될 위험은 있지만, 도난당할 위험은 있다. 누구도 session에 있는 정보를 꺼내볼 수 없다.
            if( rs.next() ){
                validMember = new MemberVO();
                validMember.setMemberId( rs.getString("MEMBER_ID") );
                validMember.setNickName( rs.getString("NICK_NAME") );
                validMember.setPassword( rs.getString("PASSWORD") );
                validMember.setEmail( rs.getString("EMAIL") );
            }
            
            return validMember;
            
        } catch (SQLException e) {
            throw new RuntimeException(e.getMessage(), e);
 
        } finally {
            closeDB(conn, stmt, rs);
        }
    }
 
    private void loadOracleDriver() {
        try {
            Class.forName("oracle.jdbc.driver.OracleDriver");
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e.getMessage(), e);
        }
    }
 
    private void closeDB(Connection conn, PreparedStatement stmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
            }
        }
 
    }
}
 
cs


5. biz 클래스에서 로그인 업무를 처리한다.

MemberBiz.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
 
package com.ktds.smahn.member.biz;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
 
import com.ktds.smahn.member.dao.MemberDAO;
import com.ktds.smahn.member.vo.MemberVO;
 
/**
 * 
 * @author sm ahn
 *
 */
public class MemberBiz {
    
    private MemberDAO memberDAO;
    
    public MemberBiz() {
        memberDAO = new MemberDAO();
    }
    
    /**
     * 로그인 업무를 하는 메소드
     * @param member
     * @param request 세션
     * @return
     */
    public boolean login(MemberVO member, HttpServletRequest request) {
        
        // 원래는 테스크 별로 메소드를 분리시키는게 맞다.
        // 1. 회원 정보를 가져온다.
        MemberVO loginMember = memberDAO.getMemberByIdAndPassword(member);
        
        // 2. 회원 정보가 존재한다면, 세션에 집어 넣는다.
        // 세션은 request가 가지고 있다. 
        if ( loginMember != null ) {
            
            // 세션을 가지고 온다.
            HttpSession session = request.getSession();
            
            // 세션에 한 회원의 정보를 저장한다.
            // session.setAttribute("_KEY명_", VALUE);
            session.setAttribute("_MEMBER_", loginMember);
        }
        
        // 3. 널이 아니면(회원 정보가 있다면) true 결과를 보고한다.
        return loginMember != null;
    }
 
}
 
cs


6. XML.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
 
package com.ktds.smahn.util.xml;
 
import java.io.IOException;
import java.io.InputStream;
 
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
 
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
 
public class XML {
 
    public static String getNodeString(String nodePath) {
 
        XPathFactory xPathFactory = XPathFactory.newInstance();
        XPath xPath = xPathFactory.newXPath();
 
        XPathExpression expr = null;
        try {
            expr = xPath.compile(nodePath);
        } catch (XPathExpressionException e) {
            throw new RuntimeException(e);
        }
 
        if (expr != null) {
 
            Document doc = null;
            try {
 
                DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
                DocumentBuilder builder = factory.newDocumentBuilder();
                InputStream is = XML.class.getClassLoader().getResource("query.xml").openStream();
 
                doc = builder.parse(is);
            } catch (SAXException e) {
                throw new RuntimeException(e);
            } catch (IOException e) {
                throw new RuntimeException(e);
            } catch (ParserConfigurationException e) {
                throw new RuntimeException(e);
            }
 
            if (doc != null) {
                try {
                    Object result = expr.evaluate(doc, XPathConstants.NODESET);
 
                    NodeList nodes = (NodeList) result;
                    for (int i = 0; i < nodes.getLength(); i++) {
                        Node node = nodes.item(i);
                        return node.getNodeValue();
                    }
                } catch (XPathExpressionException e) {
                    throw new RuntimeException(e);
                }
            }
        }
 
        return null;
    }
 
}
 
cs


7. query.xml

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
 
<?xml version="1.0" encoding="UTF-8"?>
<query>
    <member>
        <getMemberByIdAndPassword>
            SELECT    MEMBER_ID
                    , NICK_NAME
                    , PASSWORD
                    , EMAIL
            FROM    MEMBERS
            WHERE    MEMBER_ID = ?
            AND        PASSWORD = ?
        </getMemberByIdAndPassword>
    </member>
</query>
cs


공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/12   »
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
글 보관함