자바 과정 11회차/spring mvc1 게시판

[MVC] ajax로 회원가입시 아이디 중복확인

y2on 2019. 1. 9. 22:32





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
<form action="" method="post" id="_regiForm" name="regiForm">
                    
                    <table class="content_table" style="width: 75%">
                    <colgroup>
                        <col style="width:30%">
                        <col style="width:70%">
                    </colgroup>    
                    
                    <tr>
                        <th>아이디첵크</th>
                        <td>
                            <input type="text" id="c_id" size="30">
                            <a href="#none" id="_btnGetId" title="회원가입">
                                <img alt="회원가입" src="img/idcheck.png">
                            </a>
                            <div id="_rgetid"></div>
                        </td>                    
                    </tr>
                    <tr>
                        <th>아이디</th>
                        <td>
                            <input type="text" name="id" id="_userid" size="30" data-msg="아이디를" readonly="readonly">
                        </td>    
                    </tr>
                    
                    <tr>
                        <th>패스워드</th>
                        <td>
                            <input type="text" name="pw" id="_pw" size="30" data-msg="패스워드를">
                        </td>    
                    </tr>
                    
                    <tr>
                        <th>주소</th>
                        <td>
                            <input type="text" name="address" id="_address" size="30" data-msg="이름을 ">
                        </td>    
                    </tr>
                    
                    <tr>
                        <th>핸드폰 번호</th>
                        <td>
                            <input type="text" name="phone" id="_phone" size="30" data-msg="이메일을 ">
                        </td>    
                    </tr>
                    
                    <tr>
                        <th>이름</th>
                        <td>
                            <input type="text" name="name" id="_name" size="30" data-msg="이메일을 ">
                        </td>    
                    </tr>
  
                    
                    <tr>
                        <td colspan="2" style="height: 50px; text-align: center">
                        <a href="#none" id="regiBTN" title="회원가입">
                            <img alt="회원가입" src="img/regiBTN.png">
                        </a>
                        
                        <a href="#none" id="logBTN" title="로그인">
                            <img alt="회원가입" src="img/logBTN.png">
                        </a>
                        
                        </td>                    
                    </tr>
                    
                    
                    
                    </table>
                    
                    
</form>
 
cs


js 공백제어 , ajax 실행

1
2
3
4
5
6
7
8
$("#_btnGetId").click(function() {
    var id = $("#c_id").val();
    if(id == ""){
        alert("아이디를 입력해 주십시오");
    }else{
        idCheckFunc(id);
    }    
})
cs



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
function idCheckFunc(id) {
    //alert("idCheckFunc");
    
    $.ajax({
        
        type:"post",
        url:"checkID.do",
        async:true,
        data:"id=" + id,
        success:function(msg){
            alert("ajax success")
            idCheckMsg(msg);
        },
         error : function(){
            alert("ajax error");
        }
    });
}    
cs


8행 : 비동기 처리방식인 ajax를 동기방식으로 설정하고 싶을때는 async:false



>>>>>>>.1번 방법 : 

디비결과를 int로 바꾸어 컨트롤러에 보내고, 컨트롤러에서 int값에 따라 message를 set해준다

set한 message를 가지고 regi.jsp에서 새로운 함수(결과에 따라 뷰를 수정)에 값을 보낸다 

새로운 함수는( 아래의 다시js   idCheckMsg


컨트롤러

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
@ResponseBody
    @RequestMapping(value="checkID.do", method={RequestMethod.GET, RequestMethod.POST})
    public MemIdCheck checkID(MemberDto mdto) {
        logger.info("MemberController checkID" + new Date());
        
        System.out.println(mdto);
        
        int count  = memberService.checkID(mdto);
        MemIdCheck mic = new MemIdCheck();
        logger.info("checkID.do count: " + count);
        
        if(count>0){
            mic.setMessage("YES");
        }else {
            mic.setMessage("NO");
        }
        
        return mic;
    }
cs

8행 : 디비에 접근하여 mdto(입력한정보) 가 있는지 확인한다

13행 : MemIdCheck 형태의 mic 에다가 setMessage 한다  12행일경우 YES

15행 : MemIdCheck 형태의 mic 에다가 setMessage 한다  12행이 아닐경 경우 NO

18행 : 반환값 mic   ( "YES" 또는 "NO" )



memberService


memberServiceImpl

1
2
3
4
5
6
7
@Override
    public int checkID(MemberDto mem) {
      System.out.println(mem);
      int i = memberDao.checkID(mem);
      System.out.println(i + "i는");
        return memberDao.checkID(mem);
    }
cs

결과메시지 출력할때 쉽게구분할수있도록 int형태로 반환


MemberDao


MemberDaoImpl

1
2
3
4
5
6
7
8
9
10
11
12
@Override
 
    public int checkID(MemberDto mem) {    
        System.out.println("MemberDaoImpl num");
        
        int num = sqlSession.selectOne(namespace + "checkID", mem);
        
        System.out.println("MemberDaoImpl num = " + num);
        
        return num;
    }
    
cs



member.xml

1
2
3
4
5
<select id="checkID" parameterType="kh.com.a.model.MemberDto" resultType="java.lang.Integer">
SELECT NVL(COUNT(*),0)
FROM MEMBER
WHERE ID=#{id}
</select>
cs


id가 존재하면 양수, 그렇지 않으면 음수로 return 

>>결과메시지 출력할때 쉽게구분할수있도록 int형태로 반환



다시 js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
function idCheckMsg(msg) {
    
        if(msg.message == 'YES'){
            $("#_rgetid").html("사용할 수 없는 아이디");
            $("#_rgetid").css("margin""2px");
            $("#_rgetid").css("font-family""Nanum Gothic");
            $("#_rgetid").val("");        
        }else{
            $("#_rgetid").html("사용가능 아이디");
            $("#_rgetid").css("margin""2px");
            $("#_rgetid").css("font-family""Nanum Gothic");
            $("#_userid").val( $("#c_id").val() );        
        }        
    
    }
cs





dto

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
package kh.com.a.model;
 
import java.io.Serializable;
 
/*
DROP TABLE MEMBER
CASCADE CONSTRAINTS;
CREATE TABLE MEMBER(
    ID VARCHAR2(50) PRIMARY KEY,
    PWD VARCHAR2(50) NOT NULL,
    NAME VARCHAR2(50) NOT NULL,
    EMAIL VARCHAR2(50) UNIQUE,
    AUTH NUMBER(1) NOT NULL
);
*/
 
public class MemberDto implements Serializable {
    private String id;
    private String pwd;
    private String name;
    private String email;
    private int auth;    // 사용자/관리자
    
    public MemberDto() {
    }
 
    public MemberDto(String id, String pwd, String name, String email, int auth) {
        super();
        this.id = id;
        this.pwd = pwd;
        this.name = name;
        this.email = email;
        this.auth = auth;
    }
 
    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 int getAuth() {
        return auth;
    }
 
    public void setAuth(int auth) {
        this.auth = auth;
    }
 
    @Override
    public String toString() {
        return "MemberDto [id=" + id + ", pwd=" + pwd + ", name=" + name + ",
                email=" + email + ", auth=" + auth + "]";
    }
}
 
 
 
cs



>>>> 두번째 방법

뷰에서(id="_id") 받아온 값을 db에 접근하여 반환된 결과값으로(resultType="Integer")

뷰의 js안에서  if(map.cnt > 0){ }조건을 걸어 결과 처리(idCheckMessage)





컨트롤러

1
2
3
4
5
6
7
8
9
10
11
12
@ResponseBody //ajax 사용시
    @RequestMapping(value = "idCheck.do", method = RequestMethod.POST)
    public Map<Object, Object> idCheck(String id) throws Exception {
        logger.info("id 출력확인점1~~~" + id);
        int cnt = 0;
        Map<Object, Object> map = new HashMap<>();
        cnt = khMemberService.idCheck(id);
        logger.info("id 출력확인점2~~~" + cnt);    
        map.put("cnt", cnt);
 
        return map;
    }
cs


xml

1
2
3
4
5
    <select id="idCheck" parameterType="String" resultType="Integer">
        SELECT NVL(COUNT(*), 0)
        FROM MEMBER
        WHERE ID=#{id}    
    </select>
cs


regi.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
$("#_btnGetId").click(function() {
    var _id = $("#_id").val();
    if(_id == ""){
        alert("아이디를 입력해 주십시오");
    }else{
        idCheckFunc(_id);
    }    
});
 
function idCheckFunc(id) {
    alert("idCheckFunc 발동");
 
    $.ajax({
        type:"post",
        url:"idCheck.do",
        async:true,
        data:"id=" + id,
        success:function(map){
            idCheckMessage(map);
        }        
    });
}
 
function idCheckMessage(map) {
    if(map.cnt > 0){
        $("#_rgetid").html("사용할 수 없는 아이디입니다");
        $("#_rgetid").css("background-color""#ff0000");
        $("#_rgetid").val("");        
    }else{
        $("#_rgetid").html("사용하실 수 있습니다");
        $("#_rgetid").css("background-color""#0000ff");
        $("#_userid").val( $("#_id").val() );        
    }    
}
cs