본문 바로가기
JSP/JSP & Servlet

MVC 파라미터 - 회원가입

by avvin 2019. 5. 22.

MVC 파라미터 - 회원가입 1



model-2 방식(MVC)으로 회원가입 페이지 만들기


MemberJoin.jsp와 MemberBean.java 생성하고 서버로 한번 실행한뒤 스레드풀 사용할 수 있도록 server.xml 코드 수정



MemberJoin.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
<div style="text-align:center;">
<h2 align="center">회원가입</h2>
 
    <form action="proc.do" method="post">
 
    <table align="center" width="500" border="1">
        <tr height="50">
            <td width="150" align="center">아이디</td>
            <td width="350" align="left" ><input type="text" name="id"
                placeholder="id를 입력하세요" size="40"></td>
                </tr>
        <tr height="50">
            <td width="150" align="center">패스워드</td>
            <td width="350" align="left"><input type="password"
                name="password" placeholder="비밀번호는 영문과 숫자만 넣어주세요" size="40"></td>
                </tr>
        <tr height="50">
            <td width="150" align="center">패스워드 확인</td>
            <td width="350" align="left"><input type="password"
                name="password2" size="40"></td>
                </tr>
        <tr height="50">
            <td width="150" align="center">이메일</td>
            <td width="350" align="left"><input type="email" name="email" size="40"></td>
            </tr>
        <tr height="50">
            <td width="150" align="center">전화번호</td>
            <td width="350" align="left"><input type="tel" name="tel" size="40"></td>
            </tr>
        <tr height="50">
            <td width="150" align="center">관심분야</td>
            <td width="350" align="center">
            <input type="checkbox"
                name="hobby" value="캠핑"> 캠핑 &nbsp;&nbsp; 
                <input type="checkbox" name="hobby" value="독서"> 독서 &nbsp;&nbsp; 
                <input type="checkbox" name="hobby" value="영화"> 영화 &nbsp;&nbsp; 
                <input type="checkbox" name="hobby" value="등산"> 등산 &nbsp;&nbsp;
                </td>
                </tr>
        <tr height="50">
            <td width="150" align="center">당신의 직업</td>
            <td width="350" align="center"><select name="job">
                    <option value="교사">교사</option>
                    <option value="개발자">개발자</option>
                    <option value="의사">의사</option>
                    <option value="상담사">상담사</option>
            </select></td>
            </tr>
        <tr height="50">
            <td width="150" align="center">당신의 연령</td>
            <td width="350" align="center"><input type="radio" name="age"
                value="10">10대 &nbsp; &nbsp; <input type="radio" name="age"
                value="20">20대 &nbsp; &nbsp; <input type="radio" name="age"
                value="30">30대 &nbsp; &nbsp; <input type="radio" name="age"
                value="40">40대 &nbsp; &nbsp;</td>
                </tr>
        <tr height="50">
            <td width="150" align="center">남기고 싶은 말</td>
            <td width="350" align="center"><textarea rows="5" cols="40"
                    name="info">
            </textarea></td>
        </tr>
        <tr height="50">
            <td align="center" colspan="2"><input type="submit"
                value="회원가입"> &nbsp; &nbsp; &nbsp; &nbsp; <input
                type="reset" value="다시 입력"></td>
        </tr>
    </table>
      
    </form>    
</div>
</body>
</html>
cs



MemberBean.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
package model;
 
public class MemberBean {
    
    private String id;
    private String password;
    private String email;
    private String tel;
    private String hobby; //다른 변수는 일대일로 Bean 클래스에 매핑되는데 
                    //배열은 회원가입 처리페이지에서 for문으로 하나의 String으로 만든 후
                    // setProperty 또는 setter메서드로 Bean클래스에 직접 넣어줘야한다.★
    private String job;
    private String age;
    private String info;
    
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    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;
    }
    public String getTel() {
        return tel;
    }
    public void setTel(String tel) {
        this.tel = tel;
    }
    public String getHobby() {
        return hobby;
    }
    public void setHobby(String hobby) {
        this.hobby = hobby;
    }
    public String getJob() {
        return job;
    }
    public void setJob(String job) {
        this.job = job;
    }
    public String getAge() {
        return age;
    }
    public void setAge(String age) {
        this.age = age;
    }
    public String getInfo() {
        return info;
    }
    public void setInfo(String info) {
        this.info = info;
    }
            
 
}
 
cs




MemberJoin : 원가입 정보를 DB에 저장하는  MemberJoinProc 서블릿 클래스 필요


MemberJoinProc에서 비밀번호 확인이 일치할 경우 mdao.insertMember(bean); 메서드를 호출하여 데이터를 저장하고

DB에 저장된 회원 데이터를 불러오는 메서드를 실행할  MemberListCon.do (서블릿 실행 url)를 실행


일치하지 않을 경우 LoginError.jsp페이지가 실행


MemberJoinProc.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
package control;
 
import java.io.IOException;
 
import javax.servlet.RequestDispatcher;
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 model.MemberBean;
import model.MemberDAO;
 
/**
 * Servlet implementation class MemberJoinProc
 */
@WebServlet("/proc.do")
public class MemberJoinProc extends HttpServlet {
    
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
 
        reqPro(request, response);
        
    }
 
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        reqPro(request, response);
        
    }
 
    protected void reqPro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
 
        request.setCharacterEncoding("UTF-8");
        MemberBean bean = new MemberBean();
        
        bean.setId(request.getParameter("id"));
        bean.setPassword(request.getParameter("password"));
        bean.setEmail(request.getParameter("email"));
        bean.setTel(request.getParameter("tel"));
        
        String [] arr = request.getParameterValues("hobby");
        String hobby="";
        
        for(String hob : arr) {
            hobby += hob;
        }
        
        bean.setHobby(hobby);
        bean.setJob(request.getParameter("job"));
        bean.setAge(request.getParameter("age"));
        bean.setInfo(request.getParameter("info"));
        
        request.setAttribute("bean",bean);
 
        //패스워드가 같은 경우에만 데이터베이스에 저장
        
        if(bean.getPassword().equals(request.getParameter("password2"))) {
            
            MemberDAO mdao = new MemberDAO();
            
            mdao.insertMember(bean);
            
 
            //컨트롤러에서 또다른 컨트롤러를 호출해주어야한다.
            RequestDispatcher rd2 = request.getRequestDispatcher("MemberListCon.do");
            rd2.forward(request, response);
            
        } else {
            
            //★★★
            //jsp페이지에서 보여주어야할 모든 것은 request에 붙여서 dispatcher로 보내야한다
            request.setAttribute("msg","패스워드가 일치하지 않습니다.");
            RequestDispatcher rd2 = request.getRequestDispatcher("LoginError.jsp");
            rd2.forward(request, response);
        }
 
    }
}
 
cs



 이 때, 컨트롤러에서 또다른 컨드롤러를 호출할 때에도 RequestDispatcher 객체로 보낸다





MemberListCon.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
package control;
 
import java.io.IOException;
 
import model.MemberBean;
import model.MemberDAO;
 
@WebServlet("/MemberListCon.do")
public class MemberListCon extends HttpServlet {
 
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        reqPro(request, response);
    }
 
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        reqPro(request, response);
    }
    
    //멤버리스트이므로 모든 회원정보를 리턴하는 메서드의 리턴값을 벡터로 받는다.
    protected void reqPro(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
        //데이터베이스에 연결하여 회원의 모든 정보를 리턴
        MemberDAO mdao = new MemberDAO();
        Vector<MemberBean> v = mdao.getAllMember();
        
        //메서드로 받은 데이터를 jsp페이지로 넘겨준다.
        request.setAttribute("v", v);
        
        RequestDispatcher rd = request.getRequestDispatcher("MemberList.jsp"); 
        rd.forward(request, response);
        
    }
 
}
 
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
package model;
 
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Vector;
 
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
 
public class MemberDAO {
    
    Connection con;
    PreparedStatement pstmt;
    ResultSet rs;
    
    public void getCon() {
        
        try {
            Context initctx = new InitialContext();
            Context envctx = (Context)initctx.lookup("java:comp/env");
            DataSource ds = (DataSource) envctx.lookup("jdbc/pool");
            con = ds.getConnection();
            //InitialContext는 프로젝트에서 서버를 사용할 수 있도록 Context를 구성, 
            //Context의 앤트리나 리소스 정보가 위치해있는 곳이 "java.comp:env"
            //Context의 lookup(참고)메서드로 "java:comp/env" 정보 읽어들임
            //읽어들인 정보를 envctx에 담고 서버를 사용하기위해 설정했던 이름인 jdbc/pool를 참고하여
            //DataSource객체에 담는다.
            //(생성된 Context객체에서 리소스 위치한 환경 참고, 커넥션풀 리소스의 이름 참고하여 데이터소스 객체에 담음 ) 
            //DataSource객체에서 getConnection하여 커넥션 객체에 담는다.
            
            //정리 : Context 객체로 리소스 위치와 리소스 이름을 참고하여 
            //미리 설정해둔 타입(데이터소스)으로 커넥션 객체를 얻음
            
        }catch(Exception e) {
            
            e.printStackTrace();
        }
    }
    
    //request로 받아온 데이터를 bean에 하나씩 맵핑하고 insertMember(bean)호출
    public void insertMember(MemberBean bean) {
        
        getCon();
        try {
            String sql = "insert into member values(?,?,?,?,?,?,?,?)";
            pstmt = con.prepareStatement(sql);
            pstmt.setString(1, bean.getId());
            pstmt.setString(2, bean.getPassword());
            pstmt.setString(3, bean.getEmail());
            pstmt.setString(4, bean.getTel());
            pstmt.setString(5, bean.getHobby());
            pstmt.setString(6, bean.getJob());
            pstmt.setString(7, bean.getAge());
            pstmt.setString(8, bean.getInfo());
            pstmt.executeUpdate();
            con.close();
        }catch(Exception e) {
            e.printStackTrace();
        }
                
    }
    
    public Vector<MemberBean> getAllMember(){
        
        Vector<MemberBean> vec = new Vector<MemberBean>();
        getCon();
        try {
            String sql ="select * from member";
            pstmt = con.prepareStatement(sql);
            rs = pstmt.executeQuery();
            
            while(rs.next()) {
                
                MemberBean bean = new MemberBean();
                bean.setId(rs.getString(1));
                bean.setPassword(rs.getString(2));
                bean.setEmail(rs.getString(3));
                bean.setTel(rs.getString(4));
                bean.setHobby(rs.getString(5));
                bean.setJob(rs.getString(6));
                bean.setAge(rs.getString(7));
                bean.setInfo(rs.getString(8));
                
                vec.add(bean);
            }
            
            con.close();
            
        }catch(Exception e) {
            
            e.printStackTrace();
        }
 
        return vec;
    }
    
}
 
cs




MemberList.jsp

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
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@taglib prefix="c"  uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<body>
 
<div style="text-align:center">
<h2> 모든 회원 보기 </h2>
<table width=800" align ="center" border="1" bordercolor="gray">
    <tr height="40">
        <td align ="center" width="50">아이디</td>
        <td align ="center" width="200">이메일</td>
        <td align ="center" width="150">전화</td>
        <td align ="center" width="150">취미</td>
        <td align ="center" width="150">직업</td>
        <td align ="center" width="100">나이</td>
    </tr>
    
    <c:forEach var="bean" items="${v}">
    <tr height="40">
        <td align ="center" width="50">${bean.id}</td>
        <td align ="center" width="200"><a href=#>${bean.email}</a></td>
        <td align ="center" width="150">${bean.tel}</td>
        <td align ="center" width="150">${bean.hobby}</td>
        <td align ="center" width="150">${bean.job}</td>
        <td align ="center" width="100">${bean.age}</td>
    </tr>
    </c:forEach>
</table>
</div>
 
</body>
</html>
cs


LoginError.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<body>
 
<script type="text/javascript">
alert(패스워드가 일치하지 않습니다.)
location.href='MemberJoin.jsp'
</script>
 
</body>
</html>
cs


'JSP > JSP & Servlet ' 카테고리의 다른 글

ORA-00001: unique constraint (SYSTEM.MEMBER_PK) violated  (0) 2019.05.23
커넥션풀 : java:comp/env  (1) 2019.05.23
서블릿 활용 2 - 파라미터 사용  (0) 2019.05.22
서블릿 활용 1  (0) 2019.05.22
서블릿의 이해  (0) 2019.05.22