Study/Java

[spring, jQWidgets] 주소록 CRUD 만들기

momong'-' 2020. 7. 5. 20:03

UserVo.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
package simple.user;
 
public class UserVo {
    
    private String userId;
    private String passwd;
    private String name;
    private String birth;
    private String gender;
    private String createDate;
    
    public UserVo() {}
    
    public UserVo(String userId) {
        this.userId = userId;
    }
    
    public UserVo(String userId, String passwd) {
        this.userId = userId;
        this.passwd = passwd;
    }
 
    public UserVo(String userId, String name, String birth, String gender) {
        this.userId = userId;
        this.name = name;
        this.birth = birth;
        this.gender = gender;
    }
 
    public String getUserId() {
        return userId;
    }
 
    public void setUserId(String userId) {
        this.userId = userId;
    }
    
    public String getPasswd() {
        return passwd;
    }
    
    public void setPasswd(String passwd) {
        this.passwd = passwd;
    }
 
    public String getName() {
        return name;
    }
 
    public void setName(String name) {
        this.name = name;
    }
 
    public String getBirth() {
        return birth;
    }
 
    public void setBirth(String birth) {
        this.birth = birth;
    }
 
    public String getGender() {
        return gender;
    }
 
    public void setGender(String gender) {
        this.gender = gender;
    }
 
    public String getCreateDate() {
        return createDate;
    }
 
    public void setCreateDate(String createDate) {
        this.createDate = createDate;
    }
 
    @Override
    public String toString() {
        return "UserVo [userId=" + userId + ", passwd=" + passwd + ", name=" + name + ", birth=" + birth + ", gender=" + gender
                + ", createDate=" + createDate + "]";
    }
}
 
cs

 

UserMapper.xml

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
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="simple.user.UserDao">    
 
    <select id="selectUserList" parameterType="simple.user.UserVo" resultType="simple.user.UserVo">
        SELECT 
            USER_ID
            , NAME
            , date_format(BIRTH, '%m월 %d일') AS BIRTH
            , CASE WHEN GENDER='W' THEN '여' ELSE '남' END AS GENDER
            , date_format(CREATE_DATE, '%y-%m-%d %H:%i:%s') AS CREATE_DATE
        FROM
            TB_USER
    </select>
    
    <select id="selectUserOne" parameterType="simple.user.UserVo" resultType="simple.user.UserVo">
        SELECT 
            USER_ID, NAME, BIRTH, GENDER, PASSWD
        FROM
            TB_USER
        WHERE
            USER_ID = #{userId}
            <if test="passwd != null and passwd != ''">
            and PASSWD = #{passwd}
            </if>
    </select>
    
    <insert id="insertUser" parameterType="simple.user.UserVo">
        INSERT INTO TB_USER
            (USER_ID, NAME, BIRTH, GENDER, CREATE_DATE)
        VALUES
            (#{userId}, #{name}, #{birth}, #{gender}, sysdate())
    </insert>
    
    <update id="updateUser" parameterType="simple.user.UserVo">
        UPDATE TB_USER 
        SET 
            NAME             = #{name}
            , BIRTH         = #{birth}
            , GENDER        = #{gender}
            , CREATE_DATE     = sysdate()
        WHERE
            USER_ID = #{userId}            
    </update>
    
    <delete id="deleteUser" parameterType="simple.user.UserVo">
        DELETE FROM TB_USER
        WHERE
            USER_ID = #{userId}            
    </delete>
 
</mapper>
cs

 

 

UserDao.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package simple.user;
 
import java.util.List;
 
import org.apache.ibatis.annotations.Mapper;
 
@Mapper
public interface UserDao {
    
    public List<UserVo> selectUserList(UserVo userVo);
 
    public UserVo selectUserOne(UserVo userVo);
    
    public int insertUser(UserVo userVo);
    
    public int updateUser(UserVo userVo);
    
    public int deleteUser(String userId);
    
}
 
cs

 

UserService.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package simple.user;
 
import java.util.List;
 
import org.springframework.security.crypto.password.PasswordEncoder;
 
 
public interface UserService {
    
    public List<UserVo> selectUserList(UserVo userVo);
 
    public UserVo selectUserOne(UserVo userVo);
    
    public int insertUser(UserVo userVo);
    
    public int updateUser(UserVo userVo);
    
    public int deleteUser(String userId);
    
}
 
cs

 

UserServiceImpl.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
package simple.user;
 
import java.util.List;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
 
@Service
public class UserServiceImpl implements UserService {
    
    @Autowired
    private UserDao userDao;
 
    @Override
    public List<UserVo> selectUserList(UserVo userVo) {
        return userDao.selectUserList(userVo);
    }
 
    @Override
    public UserVo selectUserOne(UserVo userVo) {
        return userDao.selectUserOne(userVo);
    }
 
    @Override
    public int insertUser(UserVo userVo) {
        return userDao.insertUser(userVo);
    }
 
    @Override
    public int updateUser(UserVo userVo) {
        return userDao.updateUser(userVo);
    }
 
    @Override
    public int deleteUser(String userId) {
        return userDao.deleteUser(userId);
    }
 
}
 
cs

 

UserController.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
package simple.user;
 
import java.util.HashMap;
import java.util.List;
import java.util.Map;
 
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
 
@Controller
@RequestMapping("/user")
public class UserController {
 
    @Autowired
    private UserService userService;
    
    @RequestMapping(value="/index", method = RequestMethod.GET)
    public String index() {
        return "user/index";
    }
    
    @RequestMapping(value="/indexWindow", method = RequestMethod.GET)
    public String indexWindow(Model model) {
        return "user/indexWindow3";
    }
    
    @RequestMapping(value="/list", method = RequestMethod.GET)
    public @ResponseBody List<UserVo> getUser(HttpServletRequest request, HttpServletResponse response) {
        return userService.selectUserList(new UserVo());
    }
    
    @RequestMapping(value="/save", method = RequestMethod.POST)
    public @ResponseBody Map<StringString> save(@RequestParam HashMap<StringString> param, @ModelAttribute UserVo userVo) {
        Map<StringString> resultMap = new HashMap<StringString>();
        String mode = param.get("mode");
        
        if ( mode.equals("INSERT") ) {
            userService.insertUser(userVo);
        }
        else if ( mode.equals("UPDATE") ) {
            userService.updateUser(userVo);
        }
        else if ( mode.equals("DELETE") ) {
            param.get("userVo");
 
            int result = userService.deleteUser(userVo.getUserId());
            if ( result == 1 ) {
                resultMap.put("userId", userVo.getUserId());
                resultMap.put("result""OK");
            }
            else {
                resultMap.put("result""FAIL");
            }
            
        }
        else {
            resultMap.put("result""FAIL");
        }
        
        return resultMap;
    }
    
}
 
cs

 

userWindow3.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
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
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<title>user information</title>
<link rel="stylesheet" href="/resources/lib/jqWidgets/styles/jqx.base.css" type="text/css" />
 
<script type="text/javascript" src="/resources/lib/jquery/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="/resources/lib/jqWidgets/jqx-all.js"></script>
<style>
body {
    width: 100%;
    height: 800px;
    background: #000;
    margin: auto;
}
</style>
<script type="text/javascript">
    $(function() {
        initComponent();
        initData();
    });
    
    function initComponent() {
        //grid
        $("#jqxgrid").jqxGrid({
            columns: [
              { text: '아이디', datafield: 'userId', width: '20%', align: 'center' },
              { text: '이름', datafield: 'name', width: '15%', align: 'center'  },
              { text: '성별', datafield: 'gender', width: '15%', align: 'center' , cellsalign: 'center' },
              { text: '생일', datafield: 'birth', width: '20%', align: 'center'  },
              { text: '갱신날짜', datafield: 'createDate', width: '30%', align: 'center' }
            ]
            , width : '100%'
            , height: 500
        });
        
        //button
        $("#insertBtn").jqxButton({ width: '100', height: '25', value:'등록', template:'success'});
        $("#insertBtn").on('click'function() {
            openDetailPopup('INSERT');
        });
        $("#updateBtn").jqxButton({ width: '100', height: '25', value:'수정', template:'warning'});
        $("#updateBtn").on('click'function() {
            openDetailPopup('UPDATE');
        });
        $("#deleteBtn").jqxButton({ width: '100', height: '25', value:'삭제', template:'danger'});
        $("#deleteBtn").on('click'function() {
            deleteUser();
        });
        
    }
    
    function initData() {
        $.get('/user/list'nullfunction(data) {
               var source = { localdata: data, datatype: "array" };
               
               var dataAdapter = new $.jqx.dataAdapter(source, {
                loadComplete: function (data) { },
                loadError: function (xhr, status, error) { }      
            });
               
               $("#jqxgrid").jqxGrid({ source : dataAdapter });
           });
    }
    
    function initPopup() {
        var htmlArr = [];
        htmlArr.push('<div id="popupForm"></div>');
        htmlArr.push('<div style="width: 100%; text-align: center;">');
        htmlArr.push(    '<div style="display: inline-flex; text-align: center; margin-top:10px;">');
        htmlArr.push(        '<input type="button" id="saveBtn" style="margin-right: 10px" />');
        htmlArr.push(        '<input type="button" id="cancelBtn"/>');
        htmlArr.push(    '</div>');
        htmlArr.push('</div>');
        $('#jqxwindow .popupContents').html(htmlArr.join(''));
        
        $("#saveBtn").jqxButton({ width: '100', height: '25', value:'저장'});
         $("#jqxwindow").on('click''#saveBtn'function() {
             saveUser();
        });
        $("#cancelBtn").jqxButton({ width: '100', height: '25', value:'취소'});
        $("#jqxwindow").on('click''#cancelBtn'function() {
            $('#jqxwindow').jqxWindow('close');
        });
    }
    
    function openDetailPopup(type) {
        initPopup();
        $('#jqxwindow').jqxWindow({
            autoOpen: false
            , width: 400, height: 300
        });
        
        var template = [
            {bind:'userId'name:'userId', type:'text', label:'아이디', required:true, labelWidth:'80px', width:'250px'}
            , {bind:'name'name'name', type:'text', label:'이름', required:true, labelWidth:'80px', width:'250px'}
            , {type:'label', label: '성별', required:true, rowHeight: '40px'}
            , {bind:'gender'name:'gender', type:'option', width:'250px', optionslayout: 'horizontal', options:[{label:'남자', value:'M'}, {label:'여자', value:'W'}]}
            , {bind:'birth'name:'birth', type:'date', label:'생일', formatString: "yyyy-MM-dd", labelPosition:'left', labelWidth:'80px', align:'left', width:'250px', required:true}
        ];
 
        $('#popupForm').jqxForm({
            template: template,
            padding: { left: 10, top: 10, right: 10, bottom: 10 }
        });
        
        $('#jqxwindow').data('type', type);
        
        if ( 'INSERT' == type ) {
            $('#jqxwindow').jqxWindow('open');
        }
        else if ( 'UPDATE' == type) {
            // getUser
            var selectedrowindex = $('#jqxgrid').jqxGrid('getselectedrowindex');
            
            if ( selectedrowindex == -1 ) {
                alert("수정할 유저를 선택하세요");
            }
            else {
                var data = $('#jqxgrid').jqxGrid('getrowdata', selectedrowindex);
                var param = {userId : data.userId};
                $.get('/user/one', param, function(result) {
                    $('#popupForm').jqxForm('val', result );
                    $('#popupForm').jqxForm('getComponentByName','userId')[0].disabled = true;
                    $('#jqxwindow').jqxWindow('open');
                }).fail(function () {
                    alert('해당유저를 수정할 수 없습니다.');
                });
            }
        }
        else { console.log('openDetailPopup - type :'+type); }
    }
    
    function deleteUser() {
        var param = {mode : 'DELETE'};
        var selectedrowindex = $('#jqxgrid').jqxGrid('getselectedrowindex');
        
        if ( selectedrowindex == -1 ) {
            alert("삭제할 유저를 선택하세요");
        }
        else {
            var data = $('#jqxgrid').jqxGrid('getrowdata', selectedrowindex);
            param.userId = data.userId;
            
            $.post('/user/save', param, function(result) {
                console.log(result);
                if ( result.result == 'OK' ) {
                    alert(result.userId + ' >> 삭제되었습니다.');
                    initData();
                }
                else {
                    alert('삭제에 실패 하였습니다.');
                }
            });
        }
    }
    
    function saveUser() {
        var type = $('#jqxwindow').data('type');
        var param = {mode : type};
        var inputData = $('#popupForm').jqxForm().val();
        $.extend(param, inputData);
        
        $.post('/user/save', param, function(result) {
            if ( result.result = 'OK' ) {
                $('#jqxwindow').jqxWindow('close');
                initData();
            }
            else {
                alert('등록에 실패 하였습니다.');
            }
        });
    }
    
</script>
</head>
 
<body>
    <div id="top" style="width: 100%; height: 200px; background: #ff9999;">
        <h1 style="color: #fff; text-align: center;">User Information</h1>
    </div>
    <div id="bottom" style="width: 100%; height: 600px; background: #fff; display: inline-flex;">
        <div id="left" style="width: 300px; height: 100%; background: #ede6e6"></div>
        <div id="right" style="width: calc(100% - 300px); height: calc(100% - 20px); margin: 10px; background: #fff">
            <div style="height: 30px; background: #fff; float: right; margin: 5px;">
                <input id="insertBtn" type="button"/>
            </div>
 
            <div id="jqxgrid"></div>
 
            <div id="button" style="width: 100%; background: #fff; display: inline-flex;">
                <input id="updateBtn" type="button" style="margin-top: 10px; margin-right: 10px;"/> 
                <input id="deleteBtn" type="button" style="margin-top: 10px;"/>
            </div>
        </div>
    </div>
    <div hidden="hidden">
        <div id="jqxwindow">
            <div>상세정보</div>
            <div class="popupContents">
                <div id="popupForm">
                </div>
                <div style="width: 100%; text-align: center;">
                    <div style="display: inline-flex; text-align: center; margin-top:10px;">
                        <input type="button" id="saveBtn" style="margin-right: 10px" />
                        <input type="button" id="cancelBtn"/>
                    </div>
                </div>
            </div>
        </div>
    </div>
</body>
</html>
cs