ajax跨域

  因工做需求,須要給一個移動端寫一個登陸驗證。具體需求:由移動端訪問java項目並傳遞相應的參數,項目後臺接收參數並進行查詢判斷,而後返回給移動端,從而是移動端完成登陸。css

  解決步驟一,首先要在java項目中編寫一個免登錄的方法,java項目正常都會有登陸驗證,想要訪問項目中的某個方法時,均須要先進行登陸,有個過濾器能夠控制。個人登陸驗證方法以下:html

  

/**
     * @param p
     * @throws Throwable
     */
    @Around("allMethod()")
    public Object apple(ProceedingJoinPoint p) throws Throwable {    
        /** 初始化參數 */
        InitArgs(p);
        if(map!=null&&request!=null){
            map.put("cpage", Common.isEmpty(request.getParameter("cpage"))?1:request.getParameter("cpage"));
        }
        boolean isReturnMAV = p.getSignature().toLongString().contains("org.springframework.web.servlet.ModelAndView");
        boolean isAjax = methodName.startsWith("aj_");
        boolean video = methodName.equals("video");
        Map<String, Object> paramMap = new HashMap<String, Object>();
        /** 驗證登陸 */
        LoginUser loginUser = (LoginUser)session.getAttribute(Constant.SS_LOGIN_USER);
    //當用戶爲空 而且isNeedValidLogin這個方法爲true的時候才能走如下方法
if(loginUser == null && isNeedValidLogin(className, methodName)){ if(!isAjax){ if(video){ HttpSession session2 = request.getSession(); int id = Integer.parseInt(request.getParameter("id")); int equId = Integer.parseInt(request.getParameter("equId")); Equ equ = equManager.doGet(Equ.class, equId); List<Media> mlist = mediaManager.getListByequId(equId,1L); Media media = mediaManager.getById(id,1L); session2.setAttribute("melist",mlist); session2.setAttribute("mlist",media); session2.setAttribute("equ",equ); return "/equ/video3"; } return isReturnMAV ? new ModelAndView("redirect:/system/logout.htm") : "redirect:/system/logout.htm"; }else{ ControllerBase.responseJSONWrite(response, Common.JsonStrResult(-901, "會話超時!請從新登陸! ", "")); } } /** LoginUser */ paramMap.put("LoginUser", loginUser); paramMap.put("SYS_MENU_MAP", session.getAttribute("Meau")); if(SystemController.class.toString().contains(className) && !",aj_setting,dialog_set_wgt,home,index,".contains(","+methodName+",")){ if(loginUser != null && loginUser.IS_WGT && (loginUser.GROUP_ID == null || loginUser.WTIME_ID == null)){ if(!isAjax){ Object result = p.proceed(); return result; }else{ ControllerBase.responseJSONWrite(response, Common.JsonStrResult(-903, "請求超時! ", "")); } } } try { //執行方法 Object result = p.proceed(); //獲取頁面樣式標記 Object cssTip = RequestUtil.getSessionAttr(session, Constant.SS_PAGE_CSS); if(cssTip == null){ RequestUtil.setSessionAttr(session, Constant.SS_PAGE_CSS, "mcss/baitian.css"); } if(result != null && !result.toString().contains("redirect:")){ if(map!=null&&request!=null){ map.put("cpage", Common.isEmpty(request.getParameter("cpage"))?1:request.getParameter("cpage")); } paramMap.put("PAGE_TITLE", Constant.PAGE_TITLE); /*if(request!=null){ paramMap.put("PATH_", request.getContextPath()); }*/ //paramMap.put("REQ_URI", request.getRequestURI()); if(loginUser != null){ //System.out.println(loginUser.UNAME); //map.put("M_MENU_AUTH", ","+loginUser.MENU_AUTH+","); paramMap.put("M_ACTION_AUTH", Common.Base64EncodeStr(","+loginUser.ACTION_AUTH+",")); //paramMap.put("SYS_MENU_MAP", GlobalUtil.SysMenuMap); //paramMap.put("SYS_MENU_MAP", session.getAttribute("Meau")); paramMap.put("SYS_MENU_MAP_", GlobalUtil.SysMenuMap_); /** 記錄處理用戶當前正在操做的菜單ID,涉及菜單選中、當前位置 */ /*InitMenu_(paramMap);*/ } } //獲取args_參數 並放入map if(request!=null){ String args_ = RequestUtil.getStringParam(request, "args_", ""); if(!"".equals(args_)){ paramMap.put("args_", args_); } if(map != null){ map.putAll(paramMap); }else{ for (Iterator<String> keys = paramMap.keySet().iterator(); keys.hasNext();) { String key = keys.next(); request.setAttribute(key, paramMap.get(key)); } } } return result; } catch (Exception ex) { ex.printStackTrace(); if(!isAjax){ String exceptUrl_ = "redirect:/system/except.htm?id_="; return isReturnMAV ? new ModelAndView(exceptUrl_) : exceptUrl_; }else{ ControllerBase.responseJSONWrite(response, Common.JsonStrResult(-902, "操做失敗! 異常:"+ex.getMessage(), ex.getMessage())); } } return null; } /** * 後臺-- 是否須要驗證 登陸 * @param className * @param methodName * @return */ private static boolean isNeedValidLogin(String className, String methodName){ if(SystemController.class.toString().contains(className)){
      //當知足如下條件的時候isNeedValidLogin()方法爲false,aj_mbUser此方法即移動端訪問項目的方法
if(",gologin,dologin,logout,except,aj_mbUser,".contains(","+methodName+",")){ return false; } } if(MyHandlerExceptionResolver.class.toString().contains(className)){ return false; } if(MediaController.class.toString().contains(className)){ if(",doTime1,".contains(","+methodName+",")){ return false; } } return true; }

  步驟二:以上是爲了實現當移動端訪問項目時的免登錄功能,如下爲移動端訪問項目的方法。覺得,移動端訪問java項目,屬於跨域訪問,因此添加了ResponseBody屬性java

@RequestMapping("/sysuser/aj_mbuser.htm")
    @ResponseBody
    public String aj_mbUser(HttpServletRequest request,HttpServletResponse response,
            String callback,String userName,String passWord,ModelMap model) throws Exception{
        
        TSysUser user = sysUserManager.getSysUserByLogin(userName, passWord);
        String result = "false";

        if(user!=null&&user.getId()>0){
             result = "{'isOk':'true'}";
            
        }else{
             result = "{'isOk':'false'}";
        }
        result = callback+"("+result+")";
        return result;

    }

  步驟三:頁面中的方法以下,dataType切記,是jsonp格式,不是jeson格式,而且jsonp屬性後邊是callback。jquery

function submitForm(){
            var uname=$("#uname").val();
            var upass=$("#upass").val();
            var url="http://211.103.196.218:8083/yyhspx/sysuser/aj_mbuser.htm";
            $.ajax({
                type: "POST",//請求方式
                url: url,
                dataType: "jsonp",
                jsonp: "callback",
                data: {
                    "userName": uname,
                    "passWord": upass
                },
                success : function(data) {
                    if(data.isOk=='true'){
                        window.location.href="index.html";
                    }else{
                        alert("用戶名或者密碼錯誤");
                    }
            },
                error : function() {
                alert("用戶名或者密碼錯誤");
        }
    });
<input type="text" name="" class="userName" placeholder="admin" id="uname">
        <input type="password" name="" class="passWord"  value="admin" id="upass">
        <input type="button" name="" onclick="submitForm()" class="subBut" value="登陸">

 對於json和jsonp的區別,來自另一個博客,地址:http://www.cnblogs.com/sunxucool/p/3433992.html git

json格式:
{
    "message":"獲取成功", "state":"1", "result":{"name":"工做組1","id":1,"description":"11"} }
jsonp格式:
callback({
    "message":"獲取成功", "state":"1", "result":{"name":"工做組1","id":1,"description":"11"} })

看出來區別了吧,在url中callback傳到後臺的參數是神馬callback就是神馬,jsonp比json外面有多了一層,callback()。這樣就知道怎麼處理它了。因而修改後臺代碼。github

後臺java代碼最終以下:web

複製代碼
@RequestMapping(value = "/getGroupById") public String getGroupById(@RequestParam("id") Long id, HttpServletRequest request, HttpServletResponse response) throws IOException { String callback = request.getParameter("callback"); ReturnObject result = null; Group group = null; try { group = groupService.getGroupById(id); result = new ReturnObject(group, "獲取成功", Constants.RESULT_SUCCESS); } catch (BusinessException e) { e.printStackTrace(); result = new ReturnObject(group, "獲取失敗", Constants.RESULT_FAILED); } String json = JsonConverter.bean2Json(result); response.setContentType("text/html"); response.setCharacterEncoding("utf-8"); PrintWriter out = response.getWriter(); out.print(callback + "(" + json + ")"); return null; }
複製代碼

注意這裏須要先將查詢結果轉換我json格式,而後用參數callback在json外面再套一層,就變成了jsonp。指定數據類型爲jsonp的ajax就能夠作進一步處理了。ajax

追求永無止境,在google的過程當中,無心中發現了一個專門用來解決跨域問題的jQuery插件-jquery-jsonpspring

有第一種方式的基礎,使用jsonp插件也就比較簡單了,server端代碼無需任何改動。json

來看一下如何使用jquery-jsonp插件解決跨域問題吧。

複製代碼
var url="http://localhost:8080/WorkGroupManagment/open/getGroupById" +"?id=1&callback=?"; $.jsonp({ "url": url, "success": function(data) { $("#current-group").text("當前工做組:"+data.result.name); }, "error": function(d,msg) { alert("Could not find user "+msg); } });
複製代碼

 

至此兩種解決跨域問題的方式就所有介紹完畢。

相關文章
相關標籤/搜索