第五篇:移动APP开发- ajax请求以及服务端编写_手机app是用的ajax数据链接吗-程序员宅基地

技术标签: 移动APP开发  

前面把页面结构以及页面跳转做完以后,接下来就是数据获取。

首先就是列表数据获取,其次是详情页数据获取。

在前端中我们通过ajax请求java编写的接口获取数据,而今天要记录的就是前端请求接口的方式以及后端服务端数据接口的编写。

一.前端获取数据方式

我们都知道在传统的单例项目中,前端使用JSP,通过ajax以及表单提交,后端通过Struts2或者springMVC的dispatcher拦截这些请求从而返回数据,以往调用接口也是使用java调用远程接口,然后将数据返回到前端,现在问题来了:我们直接在前端中使用ajax去调用远程接口就有跨域问题,因为Ajax是不支持跨域问题的,因此我们是访问不到远程服务接口的。

关于跨域问题有一篇很好的博客推荐:https://segmentfault.com/a/1190000012469713

其实对于一个对前端不太了解的人来说跨域我是真的不太懂的,网上关于HBuilder开发APP解决ajax的跨域问题方案很多,不过许多都不行,你可以写个服务端简单的servlet,然后用官网那个ajax页面调用你的远程servlet,我当初解决方法说一下(我也不知道原理)

将页面引入的mui.js中大概3155行的setHeader('X-Requested-With', 'XMLHttpRequest');这句话注释掉。

当然可如果在真机运行时一般不会出现这个问题的。

请注意:跨域问题报错为:

XMLHttpRequest cannot load http://avst.tv/webAPP/web/index.php.
No 'Access-Control-Allow-Origin' header is present on the 
requested resource. Origin 'http://127.0.0.1:8020' 
is therefore not allowed access

其他可能就是你的请求与返回的数据格式有问题了。

因为是请求的json数据,所以直接使用mui封装的mui.getJSON()。

mui.getJSON(
"http://qcph5j.natappfree.cc/YSJ/cxf/rest/product/List",
 data, 
function(rsp) {});

由于在官网中有一个列表获取数据的例子,所以我将请求地址以及字段修改后就可以了

<script>
var lastId = ''; //最新列表的id
//初始化中包括列表初始数据的获取,采用下拉更新
mui.init({
//下拉初始化
pullRefresh: {
//取得ul容器
    container: '#list',
    down: {
        style: 'circle',
        offset: '0px',
        auto: true,//首次计入自动刷新
        callback: function() {
            //下拉后的回调函数:检查是否联网,若未连接网络不执行下面操作了
            if(window.plus && plus.networkinfo.getCurrentType() ===             plus.networkinfo.CONNECTION_NONE) {
            plus.nativeUI.toast('似乎已断开与互联网的连接', {
            verticalAlign: 'top'
        });
            return;
    }

    //定义需要请求获取的字段名
    var data = {
        column: "id,post_id,title,author_name,cover,published_at"
    }

    if(lastId) { //说明已有数据,目前处于下拉刷新,增加时间戳,触发服务端立即刷新,返回最新数据
        data.lastId = lastId;
        data.time = new Date().getTime() + "";
    }

    //ajax远程调用:请求列表信息流。
        mui.getJSON("http://qcph5j.natappfree.cc/YSJ/cxf/rest/product/List", data,     function(rsp) {
    //调用成功后,下拉容器结束刷新(必须调用)
    mui('#list').pullRefresh().endPulldown();

    //如果返回有数据
    if(rsp && rsp.length > 0) {
        lastId = rsp[0].id; //保存最新消息的id,方便下拉刷新时使用
        news.items = news.items.concat(convert(rsp));
    }
    });
  }
}
}
});

//创建vue对象
var news = new Vue({
    el: '#product_list',
    data: {
    banner: {}, //顶部banner数据
    items: [] //列表信息流数据
    }
});

/**
* 1、将服务端返回数据,转换成前端需要的格式
* 2、若服务端返回格式和前端所需格式相同,则不需要改功能
*
* @param {Array} items 
*/
function convert(items) {
    var newItems = [];
    items.forEach(function(item) {
    newItems.push({
    guid: item.post_id,
    title: item.title,
    author: item.author_name,
    cover: item.cover,
    time:dateUtils.format(item.published_at)
    });
    });
    return newItems;
}




/********************************************工具方法***********************************/
/**
* 格式化时间的辅助类,将一个时间转换成x小时前、y天前等
*/
var dateUtils = {
    UNITS: {
        '年': 31557600000,
        '月': 2629800000,
        '天': 86400000,
        '小时': 3600000,
        '分钟': 60000,
        '秒': 1000
},
humanize: function(milliseconds) {
    var humanize = '';
    mui.each(this.UNITS, function(unit, value) {
        if(milliseconds >= value) {
        humanize = Math.floor(milliseconds / value) + unit + '前';
        return false;
    }
    return true;
});
    return humanize || '刚刚';
},
format: function(dateStr) {
    var date = this.parse(dateStr)
    var diff = Date.now() - date.getTime();
    if(diff < this.UNITS['天']) {
        return this.humanize(diff);
    }

var _format = function(number) {
    return(number < 10 ? ('0' + number) : number);
};
return date.getFullYear() + '/' + _format(date.getMonth() + 1) + '/' + _format(date.getDay()) + '-' + _format(date.getHours()) + ':' + _format(date.getMinutes());
},
parse:function (str) {//将"yyyy-mm-dd HH:MM:ss"格式的字符串,转化为一个Date对象
var a = str.split(/[^0-9]/);
return new Date (a[0],a[1]-1,a[2],a[3],a[4],a[5] );
}
};
</script>

同样的详情页请求数据也是如此。

这里面有vue的影子,它用来将请求数据写入到html的元素中去,如果不喜欢使用它,完全可以使用jquery进行循环插入数据。

下面就是列表打开详情页:

首先在列表中预加载详情页,同时将部分数据传到详情页:

mui.plusReady(function() {
    //预加载详情页
    webview_detail = mui.preload({
	                url: 'product_info.html',
			id: 'news_detail',
			styles: {
				"render": "always",
				"popGesture": "hide",
				"bounce": "vertical",
				"bounceBackground": "#efeff4",
				}
			});
		});

		//打开详情
		function open_detail(item) {
				//触发子窗口变更新闻详情
				mui.fire(webview_detail, 'get_detail', {
					guid: item.guid,
					title:item.title,
					author:item.author,
					time:item.time,
					cover:item.cover
				});
				setTimeout(function () {
					webview_detail.show("slide-in-right", 300);
				},150);
			}

这样打开详情页之后就可以将传入过来的数据直接使用例如:{ {guid}}来将guid数据写道html组件中。

之后剩余数据可以再次使用ajax去服务端请求。

二.服务端开发接口

客户端能够请求了,服务端接口就要进行开发了。

这里不讲解和数据库的交互了,主要简单的列出自己开发接口的方式。

采用rest风格的webservice进行接口开发,没错就是使用基于jax-rs风格

首先maven依赖

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <maven.compiler.source>1.8</maven.compiler.source>
    <maven.compiler.target>1.8</maven.compiler.target>
    <cxf.version>3.0.0</cxf.version>
    <spring.version>4.1.6.RELEASE</spring.version>
    <mybatis.version>3.4.0</mybatis.version>
  </properties>

  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

    <!--cxf-->
      <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-rt-frontend-jaxws</artifactId>
          <version>${cxf.version}</version>
    </dependency>
    <dependency>
      <groupId>org.apache.cxf</groupId>
      <artifactId>cxf-rt-frontend-jaxrs</artifactId>
      <version>${cxf.version}</version>
    </dependency>
      <dependency>
          <groupId>org.apache.cxf</groupId>
          <artifactId>cxf-rt-transports-http</artifactId>
          <version>${cxf.version}</version>
      </dependency>
    <dependency>
      <groupId>com.fasterxml.jackson.jaxrs</groupId>
      <artifactId>jackson-jaxrs-json-provider</artifactId>
      <version>2.4.1</version>
    </dependency>




    <!-- spring核心包 -->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-oxm</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-tx</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-jdbc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context-support</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-test</artifactId>
      <version>${spring.version}</version>
    </dependency>

    <!--mybatis包-->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis</artifactId>
      <version>${mybatis.version}</version>
    </dependency>

    <!-- mybatis/spring包 -->
    <dependency>
      <groupId>org.mybatis</groupId>
      <artifactId>mybatis-spring</artifactId>
      <version>1.3.0</version>
    </dependency>

    <dependency>
      <groupId>javax.mail</groupId>
      <artifactId>mail</artifactId>
      <version>1.4</version>
    </dependency>

    <!--fastjson-->
    <dependency>
      <groupId>com.alibaba</groupId>
      <artifactId>fastjson</artifactId>
      <version>1.2.49</version>
    </dependency>

    <!--servlet-->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>javax.servlet-api</artifactId>
      <version>3.1.0</version>
    </dependency>
  </dependencies>

然后是编写接口:

package com.sjyang.webservice.serve;

/**
 * @Author:Yangsaijun
 * @Description:商品管理接口
 * @Date Created in 16:55 2018/9/11
 */

import com.alibaba.fastjson.JSONObject;

import javax.ws.rs.Consumes;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

/***
 * @Produces注释用来指定将要返回给client端的数据标识类型(MIME)。
 * @Produces可以作为class注释,也可以作为方法注释,方法的@Produces注释将会覆盖class的注释。
 * @Consumes与@Produces相反,用来指定可以接受client发送过来的MIME类型,同样可以用于class或者method,也可以指定多个MIME类型,一般用于@PUT,@POST
 * @Path获取url中指定参数名称,例如@Path("{username"})
 * @QueryParam 获取get请求中的查询参数
 * @FormParam获取post请求中表单中的数据
 * @BeanParam获取请求参数中的数据,用实体Bean进行封装
 *
 */
@Path("/product")
@Produces({MediaType.APPLICATION_JSON})
@Consumes({MediaType.APPLICATION_JSON})
public interface Product {

    //获取商品列表
    @GET
    @Path(value="/List")
    public String getList();

    @GET
    @Path(value="/res1")
    public Response getResponse();

    @GET
    @Path(value="/string/{name}")
    public String getJson(@PathParam("name")String name);

    @POST
    @Path(value="/user")
    public String postJson();
}

其中的注解如果规定Get请求则必须使用get请求,否则不通。然后编写实现类:

package com.sjyang.webservice.serve.impl;

import com.alibaba.fastjson.JSONObject;
import com.sjyang.webservice.serve.Product;

import javax.ws.rs.core.Response;
import javax.ws.rs.core.Response.Status;

/**
 * @Author:Yangsaijun
 * @Description
 * @Date Created in 17:13 2018/9/11
 */
public class ProductImp implements Product {

    /**
     * 获取商品列表
     * @return
     */
    @Override
    public String getList() {
        String json = "[{\"id\":69729,\"from_id\":\"36kr\",\"title\":\"自定义标题\",\"summary\":\"不知道\",\"column_id\":\"208\",\"column_name\":\"列明\",\"author_name\":\"作者名\",\"author_email\":\"邮箱\",\"author_avatar\":\"\",\"post_id\":\"5152966\",\"cover\":\"https:\\/\\/pic.36krcnd.com\\/201809\\/12085419\\/1ffhy23bq6acvfxm!heading\",\"content\":\"\",\"views_count\":48,\"comments_count\":0,\"published_at\":\"2018-09-12 17:01:28\",\"store_at\":\"0000-00-00 00:00:00\",\"type\":\"news\",\"created_at\":\"2018-09-12 17:12:05\",\"updated_at\":\"2018-09-12 17:12:05\"}]";
        return json;
    }

    @Override
    public Response getResponse() {
        Response.ResponseBuilder rb = Response.status(Status.OK);
        return rb.entity("Hello").build();
    }

    @Override
    public String getJson(String name) {
        JSONObject json = new JSONObject();
        json.put("name","ysj");
        return json.toJSONString();
    }

    @Override
    public String postJson() {
        JSONObject json = new JSONObject();
        json.put("name","ysj");
        return json.toJSONString();
    }
}

然后就是spring的配置文件配合CXF进行发布服务了:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:jaxrs="http://cxf.apache.org/jaxrs"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
                           http://cxf.apache.org/jaxrs
						   http://cxf.apache.org/schemas/jaxrs.xsd">


    <import resource="classpath:META-INF/cxf/cxf.xml" />
    <import resource="classpath:META-INF/cxf/cxf-servlet.xml" />

    <!-- 描述相关服务 -->
    <bean id="demoImpl" class="com.sjyang.webservice.serve.impl.ProductImp"></bean>
    <bean id="repertoryImp" class="com.sjyang.webservice.serve.impl.RepertoryImp"></bean>

    <!--发布第一个类型的服务-->
    <jaxrs:server address="/rest">
        <jaxrs:serviceBeans>
            <ref bean="demoImpl" />
        </jaxrs:serviceBeans>
        <jaxrs:providers>
            <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />
        </jaxrs:providers>
    </jaxrs:server>

    <!--发布第二个类型的服务-->
    <jaxrs:server address="/newserve">
        <jaxrs:serviceBeans>
            <ref bean="repertoryImp" />
        </jaxrs:serviceBeans>
        <jaxrs:providers>
            <bean class="com.fasterxml.jackson.jaxrs.json.JacksonJsonProvider" />
        </jaxrs:providers>
    </jaxrs:server>

</beans>

这里因为我自己写了两个接口类,所以发布了两个,里面一共10个接口。

最后就是项目启动web.xml该做的事情了:

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>


  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
  <!-- 容器创建<listener>中的类实例,创建监听器。  -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
  <!-- 用来声明一个servlet,CXFServlet是 -->
  <servlet>
    <servlet-name>cxf</servlet-name>
    <servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
    <servlet-name>cxf</servlet-name>
    <url-pattern>/cxf/*</url-pattern>
  </servlet-mapping>

  <session-config>
    <session-timeout>60</session-timeout>
  </session-config>

  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

启动项目,测试一下吧,访问地址是这样的几个部分组成:

http://IP:端口号/项目名/web.xml中cxf应该拦截的名/发布的地址/接口类定义的地址/方法前的地址

以我的为例:

http://localhost:8080/YSJ/cxf/rest/product/List就可以在浏览器里直接获取json数据啦

组合下:

 

 

 

 

 

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/ysj4428/article/details/82732377

智能推荐

海康威视网络摄像头开发流程(五)------- 直播页面测试_ezuikit 测试的url-程序员宅基地

文章浏览阅读3.8k次。1、将下载好的萤石js插件,添加到SoringBoot项目中。位置可参考下图所示。(容易出错的地方,在将js插件在html页面引入时,发生路径错误的问题)所以如果对页面中引入js的路径不清楚,可参考下图所示存放路径。2、将ezuikit.js引入到demo-live.html中。(可直接将如下代码复制到你创建的html页面中)<!DOCTYPE html><html lan..._ezuikit 测试的url

如何确定组态王与多动能RTU的通信方式_组态王ua-程序员宅基地

文章浏览阅读322次。第二步,在弹出的对话框选择,设备驱动—>PLC—>莫迪康—>ModbusRTU—>COM,根据配置软件选择的协议选期期,这里以此为例,然后点击“下一步”。第四步,把使用虚拟串口打勾(GPRS设备),根据需要选择要生成虚拟口,这里以选择KVCOM1为例,然后点击“下一步”设备ID即Modbus地址(1-255) 使用DTU时,为下485接口上的设备地址。第六步,Modbus的从机地址,与配置软件相同,这里以1为例,点击“下一步“第五步,Modbus的从机地址,与配置软件相同,这里以1为例,点击“下一步“_组态王ua

npm超详细安装(包括配置环境变量)!!!npm安装教程(node.js安装教程)_npm安装配置-程序员宅基地

文章浏览阅读9.4k次,点赞22次,收藏19次。安装npm相当于安装node.js,Node.js已自带npm,安装Node.js时会一起安装,npm的作用就是对Node.js依赖的包进行管理,也可以理解为用来安装/卸载Node.js需要装的东西_npm安装配置

火车头采集器AI伪原创【php源码】-程序员宅基地

文章浏览阅读748次,点赞21次,收藏26次。大家好,小编来为大家解答以下问题,python基础训练100题,python入门100例题,现在让我们一起来看看吧!宝子们还在新手村练级的时候,不单要吸入基础知识,夯实自己的理论基础,还要去实际操作练练手啊!由于文章篇幅限制,不可能将100道题全部呈现在此除了这些,下面还有我整理好的基础入门学习资料,视频和讲解文案都很齐全,用来入门绝对靠谱,需要的自提。保证100%免费这不,贴心的我爆肝给大家整理了这份今天给大家分享100道Python练习题。大家一定要给我三连啊~

Linux Ubuntu 安装 Sublime Text (无法使用 wget 命令,使用安装包下载)_ubuntu 安装sumlime text打不开-程序员宅基地

文章浏览阅读1k次。 为了在 Linux ( Ubuntu) 上安装sublime,一般大家都会选择常见的教程或是 sublime 官网教程,然而在国内这种方法可能失效。为此,需要用安装包安装。以下就是使用官网安装包安装的教程。打开 sublime 官网后,点击右上角 download, 或是直接访问点击打开链接,即可看到各个平台上的安装包。选择 Linux 64 位版并下载。下载后,打开终端,进入安装..._ubuntu 安装sumlime text打不开

CrossOver for Mac 2024无需安装 Windows 即可以在 Mac 上运行游戏 Mac运行exe程序和游戏 CrossOver虚拟机 crossover运行免安装游戏包-程序员宅基地

文章浏览阅读563次,点赞13次,收藏6次。CrossOver24是一款类虚拟机软件,专为macOS和Linux用户设计。它的核心技术是Wine,这是一种在Linux和macOS等非Windows操作系统上运行Windows应用程序的开源软件。通过CrossOver24,用户可以在不购买Windows授权或使用传统虚拟机的情况下,直接在Mac或Linux系统上运行Windows软件和游戏。该软件还提供了丰富的功能,如自动配置、无缝集成和实时传输等,以实现高效的跨平台操作体验。

随便推点

一个用聊天的方式让ChatGPT写的线程安全的环形List_为什么gpt一写list就卡-程序员宅基地

文章浏览阅读1.7k次。一个用聊天的方式让ChatGPT帮我写的线程安全的环形List_为什么gpt一写list就卡

Tomcat自带的设置编码Filter-程序员宅基地

文章浏览阅读336次。我们在前面的文章里曾写过Web应用中乱码产生的原因和处理方式,旧文回顾:深度揭秘乱码问题背后的原因及解决方式其中我们提到可以通过Filter的方式来设置请求和响应的encoding,来解..._filterconfig selectencoding

javascript中encodeURI和decodeURI方法使用介绍_js encodeur decodeurl-程序员宅基地

文章浏览阅读651次。转自:http://www.jb51.net/article/36480.htmencodeURI和decodeURI是成对来使用的,因为浏览器的地址栏有中文字符的话,可以会出现不可预期的错误,所以可以encodeURI把非英文字符转化为英文编码,decodeURI可以用来把字符还原回来_js encodeur decodeurl

Android开发——打包apk遇到The destination folder does not exist or is not writeable-程序员宅基地

文章浏览阅读1.9w次,点赞6次,收藏3次。前言在日常的Android开发当中,我们肯定要打包apk。但是今天我打包的时候遇到一个很奇怪的问题Android The destination folder does not exist or is not writeable,大意是目标文件夹不存在或不可写。出现问题的原因以及解决办法上面有说报错的中文大意是:目标文件夹不存在或不可写。其实问题就在我们的打包界面当中图中标红的Desti..._the destination folder does not exist or is not writeable

Eclipse配置高大上环境-程序员宅基地

文章浏览阅读94次。一、配置代码编辑区的样式 <1>打开Eclipse,Help —> Install NewSoftware,界面如下: <2>点击add...,按下图所示操作: name:随意填写,Location:http://eclipse-color-th..._ecplise高大上设置

Linux安装MySQL-5.6.24-1.linux_glibc2.5.x86_64.rpm-bundle.tar_linux mysql 安装 mysql-5.6.24-1.linux_glibc2.5.x86_6-程序员宅基地

文章浏览阅读2.8k次。一,下载mysql:http://dev.mysql.com/downloads/mysql/; 打开页面之后,在Select Platform:下选择linux Generic,如果没有出现Linux的选项,请换一个浏览器试试。我用的谷歌版本不可以,换一个别的浏览器就行了,如果还是不行,需要换一个翻墙的浏览器。 二,下载完后解压缩并放到安装文件夹下: 1、MySQL-client-5.6.2_linux mysql 安装 mysql-5.6.24-1.linux_glibc2.5.x86_64.rpm-bundle