系統(tǒng)前后臺分離
登錄后保存token
Demo登錄地址:
http://192.168.5.108:8088/oa/loginiframe.aspx
登錄后cookie中存入訪問token和有效期expire-
客戶端可取token進行資源訪問
Demo訪問地址
http://192.168.5.108:8088/demo.html
可以看到這個頁面是靜態(tài)的html文件蜻直,它通過cookie中的token對原系統(tǒng)進行資源訪問
實現(xiàn)代碼:var getToken = function(){ //從cookie中獲取token var tokenCookie = getCookie('token'); if(tokenCookie!=''){ var usertoken = tokenCookie.split('&')[0].split('=')[1]; var expire = tokenCookie.split('&')[1].split('=')[1]; var timestamp = Date.parse(new Date())/ 1000; if(expire>timestamp){ //有效期內(nèi) return usertoken; } } return ''; } $(function(){ if(getToken() == ''){ alert('尚未登錄'); window.location.; return false; } var postData = '{ "sql":"bookPagesByUnit @id=1","udx":"-1","flt":"","sortby":"","server":"","DB":"","token":"'+getToken()+'"}'; $.ajax({ type: 'POST', url: "/oa/api/doclistm.asmx/djson", data: postData, success: function (data) { if(typeof (data.d)!='undefined'){ var json = JSON.parse(data.d);//d的值為json的轉(zhuǎn)義文本盯质,需轉(zhuǎn)化成json使用 var str = '<tr><td>'+json.data.lid+'</td><td>'+json.data.mc+'</td><td><button class="btn btn-danger btn-xs">刪除</button></td></tr>'; $('#showlist').append(str); } }, dataType: "json", beforeSend: function (x) { x.setRequestHeader("Content-Type", "application/json"); }, }); });
已實現(xiàn)的ajax接口地址:http://192.168.5.108:8088//oa/api/doclistm.asmx
系統(tǒng)間的token傳遞
服務(wù)器配置CORS協(xié)議支持跨域訪問,這里可以直接使用ajax調(diào)用8080的接口
-
頁面間跳轉(zhuǎn):先訪問java系統(tǒng)的接口地址傳遞cookie
實現(xiàn)代碼:var modelHost = 'http://192.168.5.108:8080/api/route'; $('#in-btn').on('click',function(){ $('#ifm').attr("src",modelHost+'?token='+usertoken+'&expire='+expire+'&model='+$(this).data('model')); }); $('#go-btn').on('click',function(){ window.location = modelHost+'?token='+usertoken+'&expire='+expire+'&model='+$(this).data('model'); });
該接口把token和expire存入localStorage(解決ajax跨域問題)
-
頁面中獲取token訪問java業(yè)務(wù)接口
var getToken = function(){ var token = window.localStorage.getItem('everestec-usertoken'); var expire = window.localStorage.getItem('everestec-expire'); if(token==null||token==''||expire==null||expire==''){ return ''; } var timestamp = Date.parse(new Date())/ 1000; if(expire<timestamp){ return ''; } else return token; } $(function(){ var usertoken = getToken(); //從localStorage從獲取token if(usertoken==''){ alert('尚未登錄'); window.location.; return; } $.post('/api/wage/ctype?usertoken='+usertoken,function(data){ if(data.ret != 0){ //服務(wù)器對token的判斷 alert('尚未登錄'); window.location.; return false; } $("#showlist").empty(); $.each(data.data, function (i, row) { var str = '<tr id="tr_'+row.id+'"><td>'+row.mname+'</td><td> '+row.sname+'</td><td>' +'<button class="btn btn-danger btn-xs">刪除</button>' +'</td></tr>'; $("#showlist").append(str); }); }); });
ios和安卓或者其他系統(tǒng)只需要直接使用token 訪問業(yè)務(wù)接口(不涉及跨域)