教你一步步做restful程序(3)
来源:互联网 发布:php 队列发送短信 编辑:程序博客网 时间:2024/06/02 08:24
教你一步步做 Restful程序(3)
用户的crud操作代码:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
@Controllerpublic 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); }
客户端比较复杂,先看分页查看用户部分的代码:
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158
<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中的内容是:
1234567891011121314
<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> <a href="#" class="page pp" >上一页</a> <a href="#" class="page np">下一页</a> <a href="#" class="page lp">末一页</a>
分页页面效果:
本文转载于:http://yanyaner.com/blog/2012/12/28/restful3/
刘江华的博客
0 0
- 教你一步步做restful程序(3)
- 教你一步步做restful程序(1)
- 教你一步步做restful程序(2)
- 教你一步步做 Restful程序(4)
- 教你一步步做 Restful程序(5)
- 教你一步步做restful程序(6)------总结
- 一步步照着做,你也会用cocosbuilder
- 一步步做程序优化【2】OpenACC指令
- 【ZT】从安装到做项目一步步教你ROS学习入门
- 手把手教你一步步用批处理程序打包你的android App
- 一步步教你用liferay
- 一步步教你创建widget
- 一步步教你ARC-详解
- 教你一步步搞定 Handoff
- 一步步教你安装CocoaPad
- 一步步教你安装hadoop
- 一步步做程序优化【3】OpenHMPP指令(更加灵活的使用异构计算)
- 教你做“可执行的JAVA程序”
- HibernateTemplate的save方法不能保存
- 正则表达式与委托初探
- Java中经常使用的一些DOS命令
- Gnu Linux下文件的字符编码及转换工具
- hdu 2368 Alfredo's Pizza Restaurant(简单数学题)
- 教你一步步做restful程序(3)
- FPGA机器学习之stanford机器学习第八堂
- java中运用socket通信,http和socket的区别
- 软件架构师的定位、成长曲线及能力模型
- cocos2d-x之触摸的响应
- 在v$lock里找Holder和Waiter
- tcp/ip
- 段落标签
- Java Thread join() 的用法