一 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字符串返回至前端。

Jersey前后端交互初体验的更多相关文章

  1. 2、前端--初见前后端交互、CSS简介、基本选择器、组合选择器、属性选择器、分组与嵌套、伪类选择器

    今日内容概要 初窥后端框架 css简介 css选择器 今日内容详细 初次体验前后端交互 # 代码无需掌握 只看效果即可 """后端框架:可以简单的理解为别人写好的一个非常 ...

  2. Node之简单的前后端交互

    node是前端必学的一门技能,我们都知道node是用的js做后端,在学习node之前我们有必要明白node是如何实现前后端交互的. 这里写了一个简单的通过原生ajax与node实现的一个交互,刚刚学n ...

  3. Django之META与前后端交互

    Django之META与前后端交互 1 提交表单之GET 前端提交数据与发送 1)提交表单数据 2)提交JSON数据 后端的数据接收与响应 1)接收GET请求数据 2)接收POST请求数据 3)响应请 ...

  4. 前后端交互实现(nginx,json,以及datatable的问题相关)

    1.同源问题解决 首先,在同一个域下搭建网络域名访问,需要nginx软件,下载之后修改部分配置 然后再终端下cmd  nginx.exe命令,或者打开nginx.exe文件,会运行nginx一闪而过, ...

  5. springboot+mybatis+thymeleaf项目搭建及前后端交互

    前言 spring boot简化了spring的开发, 开发人员在开发过程中省去了大量的配置, 方便开发人员后期维护. 使用spring boot可以快速的开发出restful风格微服务架构. 本文将 ...

  6. 百度ueditor的图片上传,前后端交互使用

    百度ueditor的使用 一个文本编辑器,看了网上很多文档写的很乱,这里拾人牙慧,整理下怎么使用. 这个东西如果不涉及到图片附件上传,其实很简单,就是几个前端文件,直接引用,然后配置下ueditor. ...

  7. SSM-网站后台管理系统制作(4)---Ajax前后端交互

    前提:Ajax本身就为前后端交互服务的,实现功能:用户输入信息,实时判断用户的情况,这也是现在登录界面普遍流行的做法.前端js通过注释识别Controller层,该层查询返回,和之前Google验证码 ...

  8. 【开源.NET】 轻量级内容管理框架Grissom.CMS(第二篇前后端交互数据结构分析)

    这是 CMS 框架系列文章的第二篇,第一篇开源了该框架的代码和简要介绍了框架的目的.作用和思想,这篇主要解析如何把sql 转成标准 xml 配置文件和把前端post的增删改数据规范成方便后台解析的结构 ...

  9. thinkphp+jquery+ajax前后端交互注册验证

    thinkphp+jquery+ajax前后端交互注册验证,界面如下 register.html <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1. ...

随机推荐

  1. github基本命令

    https://github.com/explore 使用github网站搜索资源 具体搜索 Git教程 - 廖雪峰的官方网站 一. git配置命令 1.设置用户名 git config --glob ...

  2. mvvm模式下在WPF项目中动态加载项目的程序集和类

    在mvvm模式的wpf项目中有个需求需要去加载解决方案的程序集,并且根据程序集去动态加载当前程序集的类,做成下拉框形式. 效果: //全局定义 private ComboBox abList= nul ...

  3. 通过pip3安装virtualenvwrapper

    pip3 install virtualenvwrapper 配置virtualenvwrapper创建虚拟环境的目录和指定python3版本 环境编辑当前用户配置变量 mkdir ~/.virtua ...

  4. Binder学习笔记(七)—— ServiceManager如何响应addService请求

    有了<ServiceManager如何响应checkService请求>的探索,研究addService就轻车熟路了,中间过程不再多说,仅把关键节点列出: frameworks/nativ ...

  5. 787. Cheapest Flights Within K Stops

    There are n cities connected by m flights. Each fight starts from city u and arrives at v with a pri ...

  6. thinkphp 连接数据库 & 实例化模型操作 (下接thinkphp CURD 操作)/慕课

    7.1 连接数据库 (06:15) 1 7.2实例化模型 1 1.实例化基础模型 2 2. 实例化用户自定义模型 2 问题 2 3. 实例化公共模型 4 4. 实例化空模型 7    7.1 连接数据 ...

  7. DP【洛谷P2295】 MICE

    P2295 MICE S国的动物园是一个N*M的网格图,左上角的坐标是(1,1),右下角的坐标是(N,M). 小象在动物园的左上角,它想回到右下角的家里去睡觉,但是动物园中有一些老鼠,而小象又很害怕老 ...

  8. pf4j实例 插件框架

    实现整个过程需要三个部分,第一就是根接口,第二是插件,第三是应用程序.这是3个java项目. 首先要下载jar包,百度搜索maven repository,然后搜索pf4j,如下图,下载第一个的相应版 ...

  9. kuangbin专题十六 KMP&&扩展KMP HDU3068 最长回文

    给出一个只由小写英文字符a,b,c...y,z组成的字符串S,求S中最长回文串的长度. 回文就是正反读都是一样的字符串,如aba, abba等 Input输入有多组case,不超过120组,每组输入为 ...

  10. Qt 学习之路 2(16):深入 Qt5 信号槽新语法

    Qt 学习之路 2(16):深入 Qt5 信号槽新语法  豆子  2012年9月19日  Qt 学习之路 2  53条评论 在前面的章节(信号槽和自定义信号槽)中,我们详细介绍了有关 Qt 5 的信号 ...