zoukankan      html  css  js  c++  java
  • 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字符串返回至前端。

  • 相关阅读:
    mac登录界面的背景壁纸图片位置
    【转载】MAC系统修改帐号短名和个人文件夹名称
    ios 6.x系统UITextView 设置为密码输入无效的问题
    一个简单的果冻弹动动画
    ios中的自动释放池
    ios 静态库联合调试
    【转】IOS制作静态库
    objective-c中为什么不能实现多重继承及如何变通实现
    回调中释放自己会不会导致崩溃?
    【转载】Objective-C runtime 消息机制
  • 原文地址:https://www.cnblogs.com/HEWU10/p/5082780.html
Copyright © 2011-2022 走看看