教你一步步做restful程序(3)

11 篇文章 0 订阅
6 篇文章 0 订阅

教你一步步做 Restful程序(3)


  用户的crud操作代码:

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
@Controller
public class UserAction {

    public static final String PRE_FIX_URL = "userManager/";

    public static final Logger log = LoggerFactory.getLogger(UserAction.class);

    @Resource
    private ObjectMapper om ;

    @Resource
    private ISystemManagerService systemManagerService;

    @InitBinder
    protected void initBinder(HttpServletRequest request,
                ServletRequestDataBinder binder) throws Exception {
            DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd");
            CustomDateEditor dateEditor = new CustomDateEditor(fmt, true);
            binder.registerCustomEditor(Date.class, dateEditor);

    }

    @RequestMapping(value= PRE_FIX_URL + "getState", method=RequestMethod.GET)
    public void getLogingUserState(
            HttpSession session,
            HttpServletResponse response)  throws Exception {

        User user = (User)session.getAttribute("session_key");
        response.setCharacterEncoding("utf-8");
        MyResponse resp = new MyResponse();

        if (user == null) {
            resp.setErrorCode();
            resp.setMsg("该用户没有登录!");
            om.writeValue(response.getOutputStream(), resp);
            return;
        }

        UserDTO u = new UserDTO();
        BeanUtils.copyProperties(user, u);

        resp.setData(u);

        om.writeValue(response.getOutputStream(), resp);

    }



    @RequestMapping(value=PRE_FIX_URL + "upload_img")
    public void uploadFile(
            HttpSession session,
            HttpServletResponse response,
            @RequestParam("imgFile") CommonsMultipartFile imgFile
            )  throws Exception {
        //对上传的文件进行处理
        String dir = session.getServletContext().getRealPath("upload");
        String new_fileName = UUID.randomUUID().toString() + imgFile.getOriginalFilename().substring(imgFile.getOriginalFilename().lastIndexOf("."));

        String save_file = dir + File.separator + new_fileName;
        System.out.println(save_file);

        FileUtils.writeByteArrayToFile(new File(save_file), imgFile.getBytes());
        //发回新文件名给客户端

        Map result = new HashMap();
        result.put("error", 0);
        result.put("url", "upload/" + new_fileName);

        om.writeValue(response.getOutputStream(), result);

    }


    @RequestMapping(value=PRE_FIX_URL + "deleteUsers",method=RequestMethod.DELETE)
    public void deleteUsers(
            @RequestBody String ids,
            HttpServletResponse response
            ) throws Exception {
        response.setCharacterEncoding("utf-8");
        MyResponse resp = new MyResponse();

        try {

            if (ids.endsWith("-")) {
                ids = ids.substring(0, ids.length() - 1);
            }
            String[] str_ids = ids.split("-");
            for (String id : str_ids) {
                systemManagerService.deleteUser(systemManagerService.getUserById(Integer.parseInt(id)));
            }

        } catch (Exception e) {
            log.error("delete user error, exception is:{}", e);
            resp.setErrorCode();
            resp.setData("error!!!!");
        }


        om.writeValue(response.getOutputStream(), resp);

    }

    @RequestMapping(value=PRE_FIX_URL + "user",method=RequestMethod.POST)
    public void addUser(
            @ModelAttribute User user,
            HttpServletResponse response
            ) throws Exception {
        response.setCharacterEncoding("utf-8");
        MyResponse resp = new MyResponse();

        try {
            System.out.println(user);
            systemManagerService.addUser(user);
        } catch (Exception e) {
            log.error("add user error, exception is:{}", e);
            resp.setErrorCode();
        }

        resp.setData(user.getId());
        om.writeValue(response.getOutputStream(), resp);

    }




    @RequestMapping(value=PRE_FIX_URL + "users/{pno}",method=RequestMethod.GET)
    public void getUsersByPage(
            @PathVariable("pno") int pageNo,
            @RequestParam(value="ps", defaultValue="2")int pageSize,
            HttpServletResponse response

            )   throws Exception  {

        response.setCharacterEncoding("utf-8");

        MyResponse resp = new MyResponse();

        Page page = systemManagerService.getUserByPage(pageNo, pageSize, null);

        resp.setData(page);


        om.writeValue(response.getOutputStream(), resp);


    }

    @RequestMapping(value=PRE_FIX_URL + "user/{id}",method=RequestMethod.GET)
    public void getUserById(
            @PathVariable("id")int id,
            HttpServletResponse response
            ) throws Exception {

        MyResponse resp = new MyResponse();
        resp.setData(systemManagerService.getUserById(id));
        response.setCharacterEncoding("utf-8");
        om.writeValue(response.getOutputStream(), resp);

    }

    @RequestMapping(value=PRE_FIX_URL + "user/{id}",method=RequestMethod.DELETE)
    public void deleteUserById(
            @PathVariable("id")int id,
            HttpServletResponse response
            ) throws Exception {

        MyResponse resp = new MyResponse();
        systemManagerService.deleteUser(systemManagerService.getUserById(id));
        response.setCharacterEncoding("utf-8");
        om.writeValue(response.getOutputStream(), resp);

    }

    @RequestMapping(value=PRE_FIX_URL + "user/{id}",method=RequestMethod.POST)
    public void updateUser(
            @PathVariable("id")int id,
            @ModelAttribute User user,
            HttpServletResponse response) throws Exception {

        MyResponse resp = new MyResponse();

        User user2save = systemManagerService.getUserById(id);

        BeanUtils.copyProperties(user, user2save, new String[]{"id", "password"});

        systemManagerService.updateUser(user2save);

        response.setCharacterEncoding("utf-8");
        om.writeValue(response.getOutputStream(), resp);

    }

  客户端比较复杂,先看分页查看用户部分的代码:

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
<link type="text/css" href="../css/redmond/jquery-ui-1.8.16.custom.css" rel="stylesheet" />
<style type="text/css">
.if_u{
    border: none;
}
table a{
    margin-left: 10px;
}
</style>
<script type="text/javascript" src="../js/jquery-1.6.2.min.js"></script>
<script type="text/javascript" src="../js/jquery-ui-1.8.16.custom.min.js"></script>
<script type="text/javascript">
var pageSize = 4;
var pageNo = 1;
function refresh(){
    getUsersByPage(pageNo, pageSize);
};

function getUsersByPage(pageNo, pageSize) {

    $.ajax({
        type:"get",
        url:"users/" +pageNo ,
        cache:false,
        dataType:"json",
        data:"ps=" + pageSize,
        success:function(result) {
            if (result.code == 1 ) {

                var datas = "";
                $(result.data.data).each(function(){
                    datas = datas + "<tr><td><input type='checkbox' name='uid' value='"+ this.id+"'/></td><td>"+this.id+"</td><td>"+this.loginCode+"</td><td>"+
                    this.name+"</td><td>"+this.birthday+"</td><td><a href='" + this.id
                    +"' class='view_user'>查看</a>"
                    +"<a href='"+this.id
                        +"' class='modify_user'>修改</a>"
                    +"<a href='"+this.id
                        +"' class='delete_user'>删除</a>"
                    +"</td></tr>"
                });
                $("#users").html("");
                $(datas).appendTo("#users");

                $("#pageInfo").text(result.data.currentPageNo + "/" + result.data.totalPages);
                $("#pageCount").text(result.data.totalRows);
                $(".fp").attr("href",result.data.firstPageNo);
                $(".pp").attr("href",result.data.prePageNo);
                $(".np").attr("href",result.data.nextPageNo);
                $(".lp").attr("href",result.data.lastPageNo);

            } else {
                alert("取分页数据发生错误!!");
            }
        }
    });

}
$(function(){

    $.ajax({
        type:"get",
        url:"getState" ,
        cache:false,
        dataType:"json",
        success:function(result) {
            if (result.code == 1 ) {
                $("#loginState").text("欢迎" + result.data.name + "使用本系统!");

            } else {
                alert(result.msg);
            }
        }
    });



    $("#btn_delete_users").click(function(){
        var ids = "";
        if ($("input[name='uid']:checked").size() == 0) {
            return;
        } else {
            if  (window.confirm("您确定要删除所选择的数据吗?") == false) {
                return;
            }
        }
        $("input[name='uid']:checked").each(function(i){
            ids =  $(this).val() + "-" + ids;
        });
        $.ajax({
            type:"delete",
            url:"deleteUsers" ,
            cache:false,
            dataType:"json",
            data:ids,
            success:function(result) {
                if (result.code == 1 ) {

                    alert("删除成功  !");
                    window.location.reload();
                } else {
                    alert("删除数据发生错误!!");
                }
            }
        });

    });

    $(".view_user").live("click",function(){
        //window.location.href = "user_detail.html?uid=" + $(this).attr("href");
        $("<div class='view_user_dlg'><iframe height='150' frameborder=0 class='if_u' src='user_detail.html?uid="+ $(this).attr("href") +"'></iframe></div>")
        .dialog({title:"用户详细信息",width:350, height:200,modal:true});
        return false;
    });

    $(".modify_user").live("click",function(){
        $("<div class='modify_user_dlg'><iframe height='150' frameborder=0 class='if_u' src='user_modifyl.html?uid="+ $(this).attr("href") +"'></iframe></div>")
        .dialog({title:"修改用户信息",width:350, height:200,modal:true});
        return false;
    });

    $(".delete_user").live("click",function(){
        if (window.confirm("您确定要删除该用户信息吗?")) {

            $.ajax({
                type:"delete",
                url:"user/" + $(this).attr("href"),
                cache:false,
                dataType:"json",
                success:function(result) {
                    if (result.code == 1 ) {
                        window.parent.refresh();
                        alert("删除成功!");
                        $("#btn_close").click();
                    } else {
                        alert("删除失败!原因:!" + result.msg);
                    }
                }
            });

        }
        return false;
    });

    getUsersByPage(1,pageSize);

    $(".page").click(function(){
        pageNo = $(this).attr("href");
        getUsersByPage(pageNo,pageSize);
        return false;
    });

    $("#btn_add_user").click(function(){
        $("<div class='add_user_dlg'><iframe src='user_add.html' height='100%' width='100%' class='if_u' frameborder=0></iframe></div>")
        .dialog({title:'新增用户',width:550,height:500,modal:true});
    });

});
</script>

  网页body中的内容是:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
<h1 style="color: red;" id="loginState"></h1>
<h2>用户列表</h2>
<input type="button" value="新增" id="btn_add_user"/><input type="button" value="批量删除" id="btn_delete_users"/>
<table>
<tr><th>选择</th><th>id</th><th>登录编码</th><th>姓名</th><th>出生日期</th><th>操作</th></tr>
<tbody id="users">
</tbody>

</table><br/>
<span id="pageInfo"></span><span id="pageCount"></span>条记录
<a href="1" class="page fp">第一页</a>&nbsp;&nbsp;
<a href="#" class="page pp" >上一页</a>&nbsp;&nbsp;
<a href="#" class="page np">下一页</a>&nbsp;&nbsp;
<a href="#" class="page lp">末一页</a>

  分页页面效果:

restful参考运行界面

本文转载于:http://yanyaner.com/blog/2012/12/28/restful3/

刘江华的博客

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值