"Uncaught Error: Bootstrap's JavaScript requires jQuery at" 와 같은 에러의 원인은 부트스트랩을 사용하기 위해서는 jQuery가 필수적으로 요구되는데, jQuery가 로드되지 않아서 생기는 에러이다. 즉, html 페이지에 link 혹은 script src로 스크립트들을 로드할때, jQuery라이브러리를 먼저 임포트하고 그 밑에 부트스트랩을 임포트 시키면 해결되는 문제이다. 즉, 해당 에러는 반대로 부트스트랩 라이브러리를 jQuery보다 위에 임포트해놔서 생기는 에러인 것이다.

 

1
2
3
4
5
6
7
8
OK=>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
 
Failed=>
<script src="//maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script>
<script src="//code.jquery.com/jquery-1.11.1.min.js"></script>
 
cs

 

posted by 여성게
:

JavaScript 타이머 함수


자바스크립트에서 타이머함수란 전역객체인 window 객체 안에 있는 함수들입니다. 그렇다면 타이머 함수가 할수 있는 일은 무엇이 있을까요?


1. 특정시간마다 특정 함수를 계속 호출해서 실행 시킬 수 있다. => setInterval(function, duration)

2. 특정시간 이후에 딱 한번만 특정함수를 호출해 실행시킨다. => setTimeOut(function, duration)

3. 특정 타이머 id값을 가진 타이머 함수를 종료시킨다. => clearInterval(timerid)






1. 특정시간마다 특정함수를 호출/실행, setInterval 함수



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
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        #output {
            width: 200px;
            height: 200px;
            border: 4px solid #000;
            margin: 50px;
 
            font-size: 100px;
            text-align: center;
            line-height: 200px;
            vertical-align: middle;
 
        }
    </style>
    <script src="../../libs/jquery-1.11.0.min.js"></script>
 
    <script>
        // 예제01: 1초에 한 번씩 변수 값을 1씩 증가시키고 이 값을 #output 영역에 출력해 주세요.
        $(document).ready(function () {
 
            var $output = $("#output");
            var count = 0;
 
            // 여기에 풀이를 입력해주세요.
            // 함수 생성
            function addCount() {
                // 값 증가
                count++;
                // 값을 출력
                $output.text(count);
            }
 
            addCount();
            setInterval(addCount, 1000);
 
        })
 
    </script>
 
 
</head>
 
<body>
<div id="output">
    0
</div>
</body>
</html>
 
cs


이 코드는 1초 마다 숫자를 1씩 증가시켜주는 코드입니다. 딱히 어렵지 않은 코드라고 생각합니다. 여기서 하나 알아야 할 것은 setInterval 함수가 어떠한 리턴 값 없이 매개변수안에 있는 실행구문을 실행시켜주고 끝이 아닙니다. setInterval 함수는 코드내 유일한 timer id를 int 형태로 반환하는 함수입니다. (timer id값은 clearInterval 함수로 타이머 함수를 종료시킬 때 사용 될수 있는 유니크 키 값이라고 생각해도 좋습니다.)






2. 특정시간 이후에 딱 한번만 함수 호출/실행 , setTimeOunt 함수



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
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        #output {
            width: 600px;
            height: 200px;
            border: 4px solid #000;
            margin: 50px;
 
 
            text-align: center;
            line-height: 200px;
            vertical-align: middle;
 
        }
    </style>
    <script src="../../libs/jquery-1.11.0.min.js"></script>
 
    <script>
        // 예제02: 3초 후에 “안녕하세요. 환영합니다.” 메시지를 화면에 출력해 주세요.
        $(document).ready(function () {
 
            var $output = $("#output");
 
            // 여기에 풀이를 입력해주세요.
            setTimeout(function () {
                $output.text("안녕하세요. 환영합니다.")
            }, 3000);
 
        })
 
    </script>
 
 
</head>
 
<body>
<div id="output">
 
</div>
</body>
</html>
 
cs

이 코드는 3초 후에 매개변수 안에 있는 익명함수를 호출하여 "안녕하세요. 환영합니다"라는 메시지를 $("#output") 안에 출력하는 기능을 딱 한번만 실행시켜주는 코드입니다.





3. 특정 타이머 함수를 종료시켜주는 함수 , clearInterval 함수



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
<!DOCTYPE html PUBLIC "-//W3C//DTD Xhtml 1.0 Transitional//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title></title>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
 
        #output {
            width: 200px;
            height: 200px;
            border: 4px solid #000;
            margin: 50px;
 
            font-size: 100px;
            text-align: center;
            line-height: 200px;
            vertical-align: middle;
 
        }
    </style>
    <script src="../../libs/jquery-1.11.0.min.js"></script>
 
    <script>
        /*
         예제 03: 1초에 한번씩 숫자 값 출력하기
         변수 값을 1초에 한 번 1씩 증가시키고 이 값을 화면에 출력해 주세요.
         단, 정지버튼(#stip)을 누르면 더 이상 실행되지 않게 타이머 함수를 중지시켜 주세요.
         */
        $(document).ready(function() {
 
            var $output = $("#output");
            var count = 0;
            var timerID=0;
            timerID = setInterval(function() {
                // 값 증가
                count++;
                // 값을 출력
                $output.text(count);
            }, 1000);
 
 
            $("#stop").click(function() {
                // 여기에 풀이를 입력해주세요.
                clearInterval(timerID);
            });
 
        })
 
    </script>
 
 
</head>
 
<body>
<button id="stop">멈춤</button>
<div id="output">
    0
</div>
</body>
</html>
 
cs

이 코드는 setInterval 함수에 의해서 1초마다 1씩 증가되는 값을 출력시켜주는 타이머 함수를 종료시켜주는 코드입니다. 여기에 쓰이는 함수가 clearInterval 함수입니다. 여기서 보이는 것은 setInterval 함수의 리턴 값을 timerID라는 변수에 담아주고 이 변수를 이용해 clearInterval 함수를 사용하여 특정타이머를 종료시켜줍니다. 






posted by 여성게
:

JSON객체의 배열로 넘어온 데이터 출력하기


단순히 JSON 객체로 넘어온 것이 아니라 JSON 객체 배열로 넘어온 데이터를 javascript로 출력하는 반복문을 작성하는 예제입니다.  Spring으로 프로젝트를 하는 도중에 ajax로 리스트를 받아야 하는 기능이 있었는데, 그것이 @Response 어노테이션을 이용하여 자동으로 json객체의 배열로 넘겨받는 상황이었습니다. 순간 json객체 단위로 받는 것은 많이 했었지만 json객체의 배열? 생각하니 혼란이 와서 정리해봅니다.



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
 var i=[{"t_no":"120","t_content":"test11","t_writer":"임광빈","obtain":"0","t_date":"2018-         04-27"},
            {"t_no":"119","t_content":"test10","t_writer":"임광빈","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"118","t_content":"test9","t_writer":"임광빈","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"117","t_content":"test8","t_writer":"임광빈","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"114","t_content":"test7","t_writer":"임광빈","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"113","t_content":"test6","t_writer":"임광빈","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"110","t_content":"hi","t_writer":"임광빈","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"109","t_content":"test5","t_writer":"임광빈","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"107","t_content":"test4","t_writer":"임광빈","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"76","t_content":"test3","t_writer":"임광빈","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"75","t_content":"test2","t_writer":"임광빈","obtain":"0","t_date":"2018-04-25"},
            {"t_no":"74","t_content":"test1","t_writer":"임광빈","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"72","t_content":"hello","t_writer":"임광빈","obtain":"0","t_date":"2018-04-25"},
            {"t_no":"49","t_content":"spring create","t_writer":"임광 빈","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"29","t_content":"도전과제","t_writer":"임광빈","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"28","t_content":"서블릿공부","t_writer":"임광빈","obtain":"0","t_date":"2018-04-25"},
            {"t_no":"8","t_content":"헬로우","t_writer":"임광빈","obtain":"1","t_date":"2018-04-24"},
            {"t_no":"7","t_content":"안녕하세요.","t_writer":"임광빈","obtain":"0","t_date":"2018-04-24"},
            {"t_no":"5","t_content":"오늘할일4","t_writer":"임광빈","obtain":"1","t_date":"2018-04-24"},
            {"t_no":"1","t_content":"오늘할일1","t_writer":"임광빈","obtain":"1","t_date":"2018-04-24"}];
cs

상황은 위의 변수처럼 json type의 객체들을 배열형태로 받는 상황이었습니다.


1
2
3
4
5
6
7
$.ajax({
    url:"toDoList.do",
    success:function(data){
    //json type array 처리구문
    }
});
 
cs
 
위와 같이 toDoList.do url 요청을 통해 controller 단에서 toDoList를 비동기로 전달 받는 상황이었습니다.(dataType은 default로 json 형태이기 때문에 명시하지 않았습니다. 그리고 controller단에서 @ResponseBody 형태로 달아놨기에 자동으로 json 형태로 데이터를 파싱해서 보낸 상황입니다.)

보통 function(data) 에서 data가 json 객체 형태로 넘어온다면 단순히 data.name(요소) 로 출력하면 되었습니다. 하지만 배열은 이와는 조금 다른 형태로 진행됩니다.


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
<script>
    var i=[{"t_no":"120","t_content":"test11","t_writer":"여성게","obtain":"0","t_date":"2018-         04-27"},
            {"t_no":"119","t_content":"test10","t_writer":"여성게","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"118","t_content":"test9","t_writer":"여성게","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"117","t_content":"test8","t_writer":"여성게","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"114","t_content":"test7","t_writer":"여성게","obtain":"0","t_date":"2018-04-27"},
            {"t_no":"113","t_content":"test6","t_writer":"여성게","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"110","t_content":"hi","t_writer":"여성게","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"109","t_content":"test5","t_writer":"여성게","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"107","t_content":"test4","t_writer":"여성게","obtain":"0","t_date":"2018-04-26"},
            {"t_no":"76","t_content":"test3","t_writer":"여성게","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"75","t_content":"test2","t_writer":"여성게","obtain":"0","t_date":"2018-04-25"},
            {"t_no":"74","t_content":"test1","t_writer":"여성게","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"72","t_content":"hello","t_writer":"여성게","obtain":"0","t_date":"2018-04-25"},
            {"t_no":"49","t_content":"spring create","t_writer":"여성게","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"29","t_content":"도전과제","t_writer":"여성게","obtain":"1","t_date":"2018-04-25"},
            {"t_no":"28","t_content":"서블릿공부","t_writer":"여성게","obtain":"0","t_date":"2018-04-25"},
            {"t_no":"8","t_content":"헬로우","t_writer":"여성게","obtain":"1","t_date":"2018-04-24"},
            {"t_no":"7","t_content":"안녕하세요.","t_writer":"여성게","obtain":"0","t_date":"2018-04-24"},
            {"t_no":"5","t_content":"오늘할일4","t_writer":"여성게","obtain":"1","t_date":"2018-04-24"},
            {"t_no":"1","t_content":"오늘할일1","t_writer":"여성게","obtain":"1","t_date":"2018-04-24"}];
    
   for(var ele in i){ for(var ele2 in i[ele]){ console.log(i[ele][ele2]); } }
</script>
 
cs


배열 형태로 넘어오기 때문에 for문을 사용하여 출력해 줍니다. for(var ele in i) 에서 만약 i가 단순 배열이라면 ele에 할당되는 데이터는 배열의 인덱스 숫자입니다.(0,1,2.....i.length) 하지만 이번에 전달 받은 data 변수는 일반 배열이 아닌 json객체의 배열이므로 ele에 할당되는 데이터는 조금 다릅니다. 하지만 로그를 남기는 부분의 코드를 보면 배열과 흡사하다 못해 아주 똑같은 형식입니다. 즉 ele2는 json 객체의 key값이 할당되는 것입니다. 

i[ele][ele2] -> i[0,1...i.length][t_no,t_content......t_date] 이런식으로 값이 할당 됩니다. 


1
2
3
4
5
6
7
8
9
10
for(var ele in i){
        /*for(var ele2 in i[ele]){
            console.log(i[ele][ele2]);
        } */
        console.log(i[ele].t_no);
        console.log(i[ele].t_content);
        console.log(i[ele].t_writer);
        console.log(i[ele].obtain);
        console.log(i[ele].t_date);
    }
cs

그리고 두번째로는 이렇게 단일 for문을 이용해 각각의 키값으로 참조해서 출력도 가능합니다.!!!  혹시 틀렸거나 부족한 부분이 있었다면 지적부탁드립니다...... :)

posted by 여성게
:


ajax를 이용한 실시간 아이디 중복 체크 구현



1. 개발 환경




1. Spring 4.3.7

2. tomcat 8.0

3. oracle





2. 프로젝트 구조






3. UserDTO, UserDAO 구현


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.web.nuri.user;
 
public class UserDTO {
    private String id;
    private String pw;
    private String pwConfirm;
    private String nickName;
    private int grade;
    private int isAdmin;
    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public String getPw() {
        return pw;
    }
    public void setPw(String pw) {
        this.pw = pw;
    }
    public String getPwConfirm() {
        return pwConfirm;
    }
    public void setPwConfirm(String pwConfirm) {
        this.pwConfirm = pwConfirm;
    }
    public String getNickName() {
        return nickName;
    }
    public void setNickName(String nickName) {
        this.nickName = nickName;
    }
    public int getGrade() {
        return grade;
    }
    public void setGrade(int grade) {
        this.grade = grade;
    }
    public int getIsAdmin() {
        return isAdmin;
    }
    public void setIsAdmin(int isAdmin) {
        this.isAdmin = isAdmin;
    }
    @Override
    public String toString() {
        return "UserDTO [id=" + id + ", pw=" + pw + ", nickName=" + nickName + ", grade=" + grade + ", isAdmin="
                + isAdmin + "]";
    }
    
}
cs


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
package com.web.nuri.userImpl;
 
import org.mybatis.spring.SqlSessionTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
 
import com.web.nuri.user.UserDTO;
import com.web.nuri.user.UserService;
 
@Repository("UserDAO")
public class UserDAO{
    
    @Autowired
    private SqlSessionTemplate mybatis;
    
    public UserDAO() {
        // TODO Auto-generated constructor stub
        System.out.println("UserDAO 객체 생성");
    }
    public void updateUser(UserDTO udto){
        System.out.println("UserDAO.updateUser() 호출");
        mybatis.update("UserDAO.updateUser",udto);
    }
    public void deleteUser(UserDTO udto){
        System.out.println("UserDAO.deleteUser() 호출");
        mybatis.delete("UserDAO.deleteUser",udto);
    }
    public void insertUser(UserDTO udto) {
        System.out.println("UserDAO.insertUser() 호출");
        mybatis.insert("UserDAO.insertUser",udto);
    }
    public UserDTO getUser(UserDTO udto){
        System.out.println("UserDAO.getUser() 호출");
        return (UserDTO)mybatis.selectOne("UserDAO.getUser",udto);
    }
    public UserDTO getNickNameUser(UserDTO udto) {
        System.out.println("UserDAO.getNickNameUser() 호출");
        return (UserDTO)mybatis.selectOne("UserDAO.getNickNameUser",udto);
    }
    /*public int confirmUser(UserDTO udto) {
        System.out.println("UserDAO.confirmUser() 호출");
        return mybatis.selectOne("UserDAO.confirmUser",udto);
    }*/
}
 
cs





4. UserService, UserServiceImpl 구현



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
package com.web.nuri.user;
 
public interface UserService {
 
    void updateUser(UserDTO udto);
 
    void deleteUser(UserDTO udto);
 
    void insertUser(UserDTO udto);
 
    UserDTO getUser(UserDTO udto);
    
    UserDTO getNickNameUser(UserDTO udto);
    //int confirmUser(UserDTO udto);
 
}
cs


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
package com.web.nuri.userImpl;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
 
import com.web.nuri.user.UserDTO;
import com.web.nuri.user.UserService;
 
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDAO udao;
    public UserServiceImpl() {
        // TODO Auto-generated constructor stub
        System.out.println("UserServiceImpl() 객체 생성");
    }
    @Override
    public void updateUser(UserDTO udto) {
        // TODO Auto-generated method stub
        System.out.println("UserServiceImpl:updateUser() 호출");
        udao.updateUser(udto);
    }
 
    @Override
    public void deleteUser(UserDTO udto) {
        // TODO Auto-generated method stub
        System.out.println("UserServiceImpl:deleteUser() 호출");
        udao.deleteUser(udto);
    }
 
    @Override
    public void insertUser(UserDTO udto) {
        // TODO Auto-generated method stub
        System.out.println("UserServiceImpl:insertUser() 호출");
        udao.insertUser(udto);
    }
 
    @Override
    public UserDTO getUser(UserDTO udto) {
        // TODO Auto-generated method stub
        System.out.println("UserServiceImpl:getUser() 호출");
        return udao.getUser(udto);
    }
    @Override
    public UserDTO getNickNameUser(UserDTO udto) {
        // TODO Auto-generated method stub
        return udao.getNickNameUser(udto);
    }
 
    /*@Override
    public int confirmUser(UserDTO udto) {
        // TODO Auto-generated method stub
        System.out.println("UserServiceImpl:confirmUser() 호출");
        return udao.confirmUser(udto);
    }*/
 
}
 
cs


UserService클래스와 그 구현 클래스인 UserServiceImpl를 구현한 이유는 컨트롤러에서 직접적으로 DAO에 접근을 하지 않고 Service 클래스를 한번 거쳐 비즈니스 로직을 수행하게 됨으로 DAO의 변경이 있더라도 컨트롤러 클래스의 코드의 변경은 최소화 되기 때문에 유지보수 능력이 향상 되기때문입니다.




5. UserController 구현



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
package com.web.nuri.controller;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
 
import com.web.nuri.user.UserDTO;
import com.web.nuri.user.UserService;
 
@Controller
public class UserController {
    
    @Autowired
    private UserService userService;
    
    @RequestMapping(value="/login.do",method=RequestMethod.GET)
    public ModelAndView loginView(ModelAndView mav) {
        System.out.println("Controller.loginView() 호출");
        mav.setViewName("login");
        return mav;
    }
    @RequestMapping(value="/insertUser.do",method=RequestMethod.GET)
    public ModelAndView insertUserView(ModelAndView mav) {
        System.out.println("Controller.insertUserView() 호출");
        mav.setViewName("insertUser");
        return mav;
    }
    @ResponseBody
    @RequestMapping(value="/checkId.do")
    public int idCheck(UserDTO udto,ModelAndView mav) {
        System.out.println("Controller.idCheck() 호출");
        int result=0;
        UserDTO user=userService.getUser(udto);
        if(user!=null) result=1;
        else System.out.println("아이디사용가능");
        return result;
    }
    @ResponseBody
    @RequestMapping(value="/checkNickName.do")
    public int nickNameCheck(UserDTO udto,ModelAndView mav) {
        System.out.println("Controller.nickNameCheck() 호출");
        int result=0;
        UserDTO user=userService.getNickNameUser(udto);
        if(user!=null) result=1;
        return result;
    }
    @RequestMapping(value="/insertUser.do",method=RequestMethod.POST)
    public ModelAndView insertUser(UserDTO udto,ModelAndView mav) {
        System.out.println("Controller.insertUser() 호출");
        userService.insertUser(udto);
        mav.setViewName("login");
        return mav;
    }
}
 
cs


여기서 ajax의 실시간 아이디 중복체크에 쓰이는 메소드는 "/checkId.do"(동일 아이디가 있는지 체크)와 "/checkNickName.do"(동일 닉네임이 있는지 체크) url 매핑입니다. 각 메소드에 @ResponseBody 어노테이션이 붙은 이유는 jsp파일에서 넘어온 데이터를 이용해 로직을 처리하고 다시 jsp로 가공된 데이터를 넘길때 자동으로 json객체로 데이터를 바인딩해서 보내기 위해 붙인 어노테이션입니다.





6. pom.xml



1
2
3
4
5
6
            <!-- jackson2 -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.7.2</version>
        </dependency>
cs


Controller에서 @ResponseBody를 이용하기 위해 jackson2 라이브러리를 받아줍니다.

(기타 applicationContext.xml , presentation-layer.xml 등의 스프링 설정파일은 Spring 카테고리의 Spring으로 회원가입을 구현한 글을 참고하시면 됩니다.)




7. insertUser.jsp



55
5657
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
149
150
151
152
153
154
155
156
157
<%@ page language="java" contentType="text/html; charset=EUC-KR"
    pageEncoding="EUC-KR"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=EUC-KR">
    <link href="//maxcdn.bootstrapcdn.com/bootstrap/latest/css/bootstrap.min.css" rel="stylesheet">
    <script type="text/javascript" src="//ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
    <script type="text/javascript" src="//maxcdn.bootstrapcdn.com/bootstrap/latest/js/bootstrap.min.js"></script>
    <style>
    body {
        background: #f8f8f8;
        padding: 60px 0;
    }
    
    #login-form > div {
        margin: 15px 0;
    }
 
</style>
<title>회원가입</title>
</head>
<body>
    <div class="container">
        <div class="col-md-6 col-md-offset-3 col-sm-8 col-sm-offset-2">
            <div class="panel panel-success">
                <div class="panel-heading">
                    <div class="panel-title">환영합니다!</div>
                </div>
                <div class="panel-body">
                    <form action="insertUser.do" id="login-form" method="post">
                        <div>
                            <input type="email" class="form-control id" name="id" placeholder="Email" oninput="checkId()" id="checkaa" autofocus>
                        </div>
                        <div>
                            <input type="password" class="form-control pass" name="pw" placeholder="Password" oninput="checkPwd()">
                        </div>
                        <div>
                            <input type="password" class="form-control pass" name="pwConfirm" placeholder="Confirm Password" id="repwd" oninput="checkPwd()">
                        </div>
                        <div>
                            <input type="text" class="form-control nickname" name="nickName" id="nickname" placeholder="Your Nickname" oninput="checkNick()" autofocus>
                        </div>
                        <div>
                            <button type="submit" class="form-control btn btn-primary signupbtn" disabled="disabled">회원가입</button>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
    <script>
 
    //아이디와 비밀번호가 맞지 않을 경우 가입버튼 비활성화를 위한 변수설정
    var idCheck = 0;
    var nickCheck = 0;
    var pwdCheck = 0;
    //아이디 체크하여 가입버튼 비활성화, 중복확인.
    function checkId() {
        var inputed = $('.id').val();
        console.log(inputed);
        $.ajax({
            data : {
                id : inputed
            },
            url : "checkId.do",
            success : function(data) {
                if(inputed=="" && data=='0') {
                    $(".signupbtn").prop("disabled"true);
                    $(".signupbtn").css("background-color""#aaaaaa");
                    $("#checkaa").css("background-color""#FFCECE");
                    idCheck = 0;
                } else if (data == '0') {
                    $("#checkaa").css("background-color""#B0F6AC");
                    idCheck = 1;
                    if(idCheck==&& pwdCheck == 1) {
                        $(".signupbtn").prop("disabled"false);
                        $(".signupbtn").css("background-color""#4CAF50");
                    } 
                } else if (data == '1') {
                    $(".signupbtn").prop("disabled"true);
                    $(".signupbtn").css("background-color""#aaaaaa");
                    $("#checkaa").css("background-color""#FFCECE");
                    idCheck = 0;
                } 
            }
        });
    }
  //재입력 비밀번호 체크하여 가입버튼 비활성화 또는 맞지않음을 알림.
    function checkPwd() {
        var inputed = $('.pass').val();
        var reinputed = $('#repwd').val();
        console.log(inputed);
        console.log(reinputed);
        if(reinputed=="" && (inputed != reinputed || inputed == reinputed)){
            $(".signupbtn").prop("disabled"true);
            $(".signupbtn").css("background-color""#aaaaaa");
            $("#repwd").css("background-color""#FFCECE");
        }
        else if (inputed == reinputed) {
            $("#repwd").css("background-color""#B0F6AC");
            pwdCheck = 1;
            if(idCheck==&& pwdCheck == 1) {
                $(".signupbtn").prop("disabled"false);
                $(".signupbtn").css("background-color""#4CAF50");
            }
        } else if (inputed != reinputed) {
            pwdCheck = 0;
            $(".signupbtn").prop("disabled"true);
            $(".signupbtn").css("background-color""#aaaaaa");
            $("#repwd").css("background-color""#FFCECE");
            
        }
    }
    //닉네임과 이메일 입력하지 않았을 경우 가입버튼 비활성화
    function checkNick() {
        var nickname = $("#nickname").val();
        console.log(nickname);
        $.ajax({
            data : {
                nickName : nickname
            },
            url : "checkNickName.do",
            success : function(data) {
                if(nickname=="" && data=='0') {
                    $(".signupbtn").prop("disabled"true);
                    $(".signupbtn").css("background-color""#aaaaaa");
                    $("#nickname").css("background-color""#FFCECE");
                    nickCheck = 0;
                } else if (data == '0') {
                    $("#nickname").css("background-color""#B0F6AC");
                    nickCheck = 1;
                    if(nickCheck ==&& pwdCheck == 1) {
                        $(".signupbtn").prop("disabled"false);
                        $(".signupbtn").css("background-color""#4CAF50");
                    } 
                } else if (data == '1') {
                    $(".signupbtn").prop("disabled"true);
                    $(".signupbtn").css("background-color""#aaaaaa");
                    $("#nickname").css("background-color""#FFCECE");
                    nickCheck = 0;
                } 
            }
        });
    }
    /*캔슬버튼 눌렀을 눌렀을시 인풋박스 클리어
    $(".cancelbtn").click(function(){
            $(".id").val(null);
            $(".pass").val('');
            $(".signupbtn").prop("disabled", true);
            $(".signupbtn").css("background-color", "#aaaaaa");
    });*/
    
   </script>
</body>
</html>
 
cs


여기서 밑에 보이는 function checkId() 함수가 실시간 아이디 중복체크를 위한 함수입니다. var inputed에 입력된 id 값을 받습니다. 그리고 ajax 코드안에 json형태의 데이터(id:inputed)로 /checkId.do url에 실시간으로 아이디값을 보내게 됩니다. 그러면 controller 안에 idCheck 메소드가 실행되게 됩니다. 그래서 만약 입력한 아이디가 존재한다면 리턴 값으로 1 값을 리턴하게 됩니다. 그러면 리턴된 데이터가  success : function(data){..} 함수의 data라는 매개변수로 값이 들어가게 됩니다. 그리고 그 매개변수로 조건문을 실행하게 되어 각 조건에 맞는 분기를 하게 됩니다. 그래서 아이디가 존재한다면 input 태그의 backgroud 색이 빨간색, 사용 할 수 있는 id인 경우 초록색으로 css를 변경하게 됩니다. 비밀번호의 경우는 jsp 파일 내에서 모두 체크를 하게 됩니다. 그래서 두번의 비밀번호의 입력이 같은 경우 input태크의 background 색이 초록색으로 변하게 됩니다. 마지막으로 닉네임 체크 같은 경우는 아이디 중복 체크와 모든 로직이 동일함으로 실시간 아이디 체크와 동일하게 코드 해석이 가능합니다.




8. 실행화면




이미 아이디가 존재하고 패스워드 두개가 다른 값을 가지며 또한, 이미 사용중인 닉네임인 경우 모든 input태그의 background 색이 빨간색으로 변함과 동시에 회원가입 버튼이 disabled가 된 것을 볼 수 있습니다.





사용가능한 아이디이며, 두개의 패스워드가 같고 또한 사용가능한 닉네임인 경우 모두 input 태그가 초록색으로 변하고 회원가입 버튼 또한 사용할 수 있게 disabled가 false로 변하게 됩니다.



9. 마치며



혹시 잘못된 점이 있으면 많은 지적부탁드립니다... 혹시 코드가 전체 필요하신 분은 댓글로 남겨주시면 확인하는 즉시 바로 보내드리겠습니다~!



posted by 여성게
: