Jersey前后端交互初體驗


一 get請求

  前端

  基本的GET請求

    $.ajax({
        type : "get",
        url : "../rest/api/account/delete",
        data : {
            accountUid : accountUid,
            tagRefId : accountTagRefId
        },
        dataType : "json",
        success : function(data) {
            if (0 != data.errCode) {
                if ("" == data.msg || null == data.msg
                        || 'undefined' == data.msg) {
                    $("#delAccountErr").html("系統錯誤,請稍后重試!");
                } else {
                    $("#delAccountErr").html(data.msg);
                }
            }else{
                $("#deleteModal").modal("hide");
            }
            queryAccount();    
        }
    });

  該get請求最終的Url為類似:http://192.168.2.126/vipmanager/rest/api/account/delete?accountUid=627EA55816B5427B86FBBE349C1E972E&tagRefId=4028822451d1a55d0151d1c0f9d50012

 后端

  //接收GET方式請求
  @GET
  //指定接收的請求路徑 @Path(
"/delete")
  //業務處理結束后返回的數據媒體類型,如果媒體類型錯誤,將返回405,Method not allow @Produces(MediaType.APPLICATION_JSON)
  //業務處理前,接收前端的請求數據的媒體類型,如果媒體類型錯誤,將返回405,Method not allow @Consumes({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_FORM_URLENCODED })
public String deleteAccount( @QueryParam("accountUid") final String refAccountUid, @QueryParam("tagRefId") final String tagRefId) { final BaseResponse baseResponse = new BaseResponse(); final String accountUid = (String) request.getSession().getAttribute( ACCOUNTUID); // 刪除邏輯實現,刪除關聯關系,賬戶不刪除 int errCode = 0; boolean flag = true; // 刪除用戶組關聯關系 if (!StringUtil.isNull(tagRefId)) { String[] tagRefIds = tagRefId.split(","); for (String id : tagRefIds) { final AccountTagRef accountTagRef = this.accountTagRefService .findById(id); if (null != accountTagRef) { errCode = this.accountTagRefService.delete(accountTagRef); if (0 != errCode) { LOG.info( "delete accounttagref by accounttagref.s id:{},errCode:{}", accountTagRef, errCode); flag = false; } } if (true != flag) { break; } } } if (true == flag ) { errCode = this.accountService.deleteAccount(accountUid, refAccountUid); } if(0 != errCode){ baseResponse.setErrCode(ErrorConstant.DELETE_ACCOUNT_FAIL); baseResponse.setMsg(ErrorConstant .getErrMsg(ErrorConstant.DELETE_ACCOUNT_FAIL)); LOG.error("error to deleteAccountTagRef for accountUid:{}",accountUid); } final JSONObject obj = JSONObject.fromObject(ResponseUtil.failed( BaseResponse.class, baseResponse.getErrCode())); return obj.toString(); }

  在Form元素的語法中,EncType表明提交數據的格式 用 Enctype 屬性指定將數據回發到服務器時瀏覽器使用的編碼類型。 下邊是說明: application/x-www-form-urlencoded: 窗體數據被編碼為名稱/值對。這是標准的編碼格式。 multipart/form-data: 窗體數據被編碼為一條消息,頁上的每個控件對應消息中的一個部分。 text/plain: 窗體數據以純文本形式進行編碼,其中不含任何控件或格式字符。補充

form的enctype屬性為編碼方式,常用有兩種:application/x-www-form-urlencoded和multipart/form-data,默認為application/x-www-form-urlencoded。 當action為get時候,瀏覽器用x-www-form-urlencoded的編碼方式把form數據轉換成一個字串(name1=value1&name2=value2...),然后把這個字串append到url后面,用?分割,加載這個新的url。 當action為post時候,瀏覽器把form數據封裝到http body中,然后發送到server。 如果沒有type=file的控件,用默認的application/x-www-form-urlencoded就可以了。 但是如果有type=file的話,就要用到multipart/form-data了。瀏覽器會把整個表單以控件為單位分割,並為每個部分加上Content-Disposition(form-data或者file),Content-Type(默認為text/plain),name(控件name)等信息,並加上分割符(boundary)。

二 POST請求

  前端

  請求參數需要使用JSON.stringify()進行請求參數的格式化,將json對象轉化為json字符串,需要提醒的是,最好指定請求的數據類型dataType,請求頭的類型contentType。dataType : "json", contentType : 'application/json'

  否則容易導致405,請求非法,無法訪問rest資源

if (perFormValidate()) {
    if(1 == num){
        $("#savePerContinueBtn").button('loading');
    }else{
        $("#savePerBtn").button('loading');
    }
    var person_name = $("#person_name").val();
    var person_mobile = $("#person_mobile").val();
    var person_code = $("#person_code").val();
    var person_email = $("#person_email").val();
    var person_company = $("#person_company").val();
    var person_usertag = $("#person_usertag").val();
    $.ajax({
        type : "POST",
        url : "../rest/api/account/add",
        dataType : "json",
        contentType : 'application/json',
        data : JSON.stringify({
            "account":
                {"mobile":person_mobile,"email":person_email,
                "person":
                    {"name":person_name,"idNo":person_code,
                    "organ":person_company}},
            "tagref":{"tag":{
                        "id":person_usertag}}
        }),
        success : function(data) {
            if(1 == num){
                $("#savePerContinueBtn").button('reset');
                $("#savePerBtn").button('reset');
            }else{
                $("#savePerContinueBtn").button('reset');
                $("#savePerBtn").button('reset');
            }
            if (0 != data.errCode) {
                if ("" == data.msg
                        || null == data.msg
                        || 'undefined' == data.msg) {
                    $("#addPersonErr").html("系統錯誤,請稍后重試!");
                } else {
                    $("#addPersonErr").html(data.msg);
                }
            } else {
                if(1 == data.possessive ){
                    //提示手機號已經被使用
                    $("#useredModual").modal("show");
                    $("#usered_content").html("您填寫的手機號已被用戶【" + data.name +","+data.idNoOrganCode  +"】使用,是否關聯已有的賬號?若不關聯已有賬號,請重新填寫手機號。");
                    $("#relatedAccountUid").val(data.accountUid);
                }else {
                    if(1 == num){
                        $("#personInfo").find(":input").not(":button,:submit,:reset,:hidden").val("");
                        $("#addPersonErr").html("個人用戶添加成功!");
                        queryAccount();
                    }else{
                        $("#personInfo").find(":input").not(":button,:submit,:reset,:hidden").val("");
                        $("#addPersonModual").modal('hide');
                        $("#useredModual").modal("hide");
                        queryAccount();
                    }
                }
            }
        },
        error:function(data){
            if(1 == num){
                $("#savePerContinueBtn").button('reset');
                $("#savePerBtn").button('reset');
            }else{
                $("#savePerContinueBtn").button('reset');
                $("#savePerBtn").button('reset');
            }
        }
    });
    }

  后端

    @POST
    @Path("/add")
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public AddAccountResponse addAccount(final AddAccountParam param) {
        AddAccountResponse addAccountResponse = new AddAccountResponse();
        /* 檢查參數有效性 */
        final int iRet = param.valid();
        if (ErrorConstant.SUCCESS != iRet) {
            LOG.error("error to addAccount .");
            return ResponseUtil.failed(AddAccountResponse.class, iRet);
        }
        final String projectId = (String) request.getSession().getAttribute(
                "projectId");
        final String accountUid = (String) request.getSession().getAttribute(
                ACCOUNTUID);
        addAccountResponse = this.accountService.addAccount(projectId,
                param.getAccount(), accountUid, null);
        if (0 == addAccountResponse.getErrCode()
                && !StringUtil.isNull(addAccountResponse.getAccountUid())) {
            final Tag tag = this.tagService.findById(param.getTagref().getTag()
                    .getId());
            final Account ac = this.accountService.findByUId(addAccountResponse
                    .getAccountUid());
            if ((null != tag) && (null != ac)) {
                final AccountTagRef tagRef = new AccountTagRef();
                tagRef.setCreateDate(new Date());
                tagRef.setAccount(ac);
                tagRef.setTag(tag);
                final int errCode = this.accountTagRefService.save(tagRef);
                if (errCode > 0) {
                    addAccountResponse
                            .setErrCode(ErrorConstant.ADDACCOUNT_SUCC_ADDTAGREF_ERR);
                }
            } else {
                addAccountResponse
                        .setErrCode(ErrorConstant.ADDACCOUNT_SUCC_ADDTAGREF_ERR);
            }
        } else {
            LOG.error("error to addAccount or null for accountUid of result`AddAccount addAccountResponse");
        }
        addAccountResponse.setMsg(ErrorConstant.getErrMsg(addAccountResponse
                .getErrCode()));
        return addAccountResponse;
    }

  jersey會將前端請求自動轉化為javabean對象接收請求參數,業務處理完成后,框架會將對象自動轉化為json字符串返回至前端。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM