调用Rest Service可以基于两种方式:

一种是oj.Collection.extend

一种是$.ajax

  • CORS问题

但在调用之前,首先需要解决rest service的CORS问题.(跨域调用不允许),方法如下:

  • 首先下载jar包:

http://software.dzhuvinov.com/cors-filter-installation.html

<filter>
<filter-name>CORS</filter-name>
<filter-class>com.thetransactioncompany.cors.CORSFilter</filter-class>
<init-param>
<param-name>cors.supportedMethods</param-name>
<param-value>GET, POST, HEAD, PUT, PATCH, DELETE</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>CORS</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

然后重新部署rest service.

  • AJAX调用

通过ajax调用的代码如下:

login.js

/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/

/**
* login module
*/
define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojknockout', 'ojs/ojinputtext','ojs/ojbutton'],

function (oj, ko, $)
{

function LoginModel()
{
var self = this;
self.username = ko.observable("eric");
self.password = ko.observable();

self.tracker = ko.observable();

self.login = function (data, event) {

alert(self.username() +" - " +self.password());

$.ajax({
url: "http://127.0.0.1:7001/RestfulApplication-RestfulProject-context-root/resources/restfulproject/login",
data: JSON.stringify({ "loginname": self.username(), "password": self.password() }),
type: "POST",
contentType: "application/json",
success: function (data, textStatus, jqXHR) {
alert("Success");

//var response = $.parseJSON(data);

self.username(null);
self.password(null);

self.router = oj.Router.rootInstance;
self.router.configure({
'dashboard': {label: 'Dashboard', isDefault: true},
'incidents': {label: 'Incidents'},
'customers': {label: 'Customers'},
'about': {label: 'About'}
});

var data = [
{name: 'Dashboard', id: 'dashboard',
iconClass: 'oj-navigationlist-item-icon demo-icon-font-24 demo-chart-icon-24'},
{name: 'Incidents', id: 'incidents',
iconClass: 'oj-navigationlist-item-icon demo-icon-font-24 demo-fire-icon-24'},
{name: 'Customers', id: 'customers',
iconClass: 'oj-navigationlist-item-icon demo-icon-font-24 demo-people-icon-24'},
{name: 'About', id: 'about',
iconClass: 'oj-navigationlist-item-icon demo-icon-font-24 demo-info-icon-24'}
];

// self.navDataSource = new oj.ArrayTableDataSource(data, {idAttribute: 'id'});

//
//
var rootViewModel = ko.dataFor(document.getElementById('mainContent'));
rootViewModel.navDataSource.reset(data, {idAttribute: 'id'});
//rootViewModel.userLogin('redsam');
//rootViewModel.isLoggedIn('true');
//rootViewModel.restSessionId(jqXHR.getResponseHeader('REST_SESSIONID'));

oj.Router.sync();
},
error: function (jqXHR, textStatus, errorThrown) {
alert("401 Unauthorized");
alert("jqXHR",jqXHR.toString());
alert('something went wrong', textStatus.toString());
alert('something ', errorThrown.toString());
}
});
return true;
};

}

return LoginModel();

});

  • oj.Collection: customer.js

/**
* Copyright (c) 2014, 2016, Oracle and/or its affiliates.
* The Universal Permissive License (UPL), Version 1.0
*/
/**
* Main content module
*/
define(['ojs/ojcore', 'knockout', 'jquery', 'ojs/ojknockout', 'ojs/ojmodel', 'ojs/ojcollectiontabledatasource',
'ojs/ojtable', 'ojs/ojpagingcontrol'],
function(oj, ko, $) {
/**
* The view model for the main content view template. Please note that since
* this example uses ojModule binding, you do not need to call ko.applyBindings
* like the JET Cookbook examples. ojModule handles applying bindings for its
* associated view.
*/
function peopleContentViewModel() {
var self = this;
self.serviceURL = 'http://127.0.0.1:7001/RestfulApplication-RestfulProject-context-root/resources/restfulproject/Persons';
self.collectionEmployees = ko.observable();
self.pagingDatasource = ko.observable();

parseEmpl = function (response) {

return {
FirstName: response['firstname'],
HireDate: response['hiredate'],
Id:response['id'],
LastName: response['lastname']
};
};

function getURL(operation, collection, options) {
return self.serviceURL;
};

var collEmpls = new oj.Collection.extend({
customURL: getURL,
fetchSize: 5,
model: new oj.Model.extend({
idAttribute: 'Id',
parse: parseEmpl
})
});

self.collectionEmployees(new collEmpls());
self.pagingDatasource = new oj.PagingTableDataSource(new oj.CollectionTableDataSource(self.collectionEmployees()));
}

/**
* This example returns a view model instance, but can instead return a constructor function
* which will be invoked to create a view model instance for each module reference.
* This instance example will be used as a singleton whenever this module is referenced.
* Please see the 'ViewModel's Lifecycle' section of the ojModule doc for more info.
*/
return new peopleContentViewModel();
});

  • 调试工具:

脚本可以通过alert进行信息的输出.

Rest服务的调试:

下载chrome Advanced Rest client,然后通过chrome://apps/,选择ARC后启动测试Rest Service。

应用调试

通过chrome带的developer tools,选择network,可以看到每个请求及响应

  • 结果:

JET 调用后端Rest Service的更多相关文章

  1. SpringCloud微服务之跨服务调用后端接口

    SpringCloud微服务系列博客: SpringCloud微服务之快速搭建EurekaServer:https://blog.csdn.net/egg1996911/article/details ...

  2. 翻译-使用Spring调用SOAP Web Service

    原文链接: http://spring.io/guides/gs/consuming-web-service/ 调用SOAP web service 本指南将指导你使用Spring调用一个基于SOAP ...

  3. express:webpack dev-server开发中如何调用后端服务器的接口?

    开发环境:     前端:webpack + vue + vue-resource,基于如下模板创建的开发环境: https://github.com/vuejs-templates/webpack  ...

  4. ASP.Net:Javascript 通过PageMethods 调用后端WebMethod方法 + 多线程数据处理 示例

    ASP.Net:Javascript 通过PageMethods 调用后端WebMethod方法 + 多线程数据处理 示例 2012年04月27日 16:59:16 奋斗的小壁虎 阅读数:4500   ...

  5. 关于controller中调用多个service方法的问题

    一般service方法是有事务的,把所有操作封装在一个service方法中是比较安全的. 如果在controller中调用多个service方法,只有查询的情况下是可以这样的.

  6. 在js内生成PDF文件并下载的功能实现(不调用后端),以及生成pdf时换行的格式不被渲染,word-break:break-all

    在js内生成PDF文件并下载的功能实现(不调用后端),以及生成pdf时换行的格式不被渲染,word-break:break-all 前天来了个新需求, 有一个授权书的文件要点击下载, 需要在前端生成, ...

  7. Spring Boot发布和调用RESTful web service

    Spring Boot可以非常简单的发布和调用RESTful web service,下面参考官方指导体验一下 1.首先访问 http://start.spring.io/ 生成Spring Boot ...

  8. 前端https调用后端http

    昨晚发生了一个,很........的事 我前端的域名  和后端的域名 都没有做认证,前端的访问的80 调用的后端80 然后我给前端的域名做了认证ssl,但是调用后端的时候报错 原因是  https 调 ...

  9. 关于jpa的Specification自定义函数,实现oracle的decode;以及如何在静态方法中调用注入的service

    如何在静态方法中调用注入的service Public class ClassA{ public static ClassA classA; @Resource private Service ser ...

随机推荐

  1. Ubuntu 15.10 安装比特币客户端

    下载 git clone https://github.com/bitcoin/bitcoin.git cd bitcoin ./autogen.sh 安装依赖包: ++-dev sudo apt-g ...

  2. 【转】针对Android上的ROP攻击剖析

    引言       ROP(Return-oriented programming),即“返回导向编程技术”.其核心思想是在整个进程空间内现存的函数中寻找适合指令片断(gadget),并通过精心设计返回 ...

  3. 无界面运行Jmeter压测脚本

    今天在针对单一接口压测时出现了从未遇到的问题,设好并发量后用调度器控制脚本的开始和结束,但在脚本应该自动结束时间,脚本却停不下来,手动stop报告就会有error率,卡了我很久很久不能解决,网络上也基 ...

  4. 生产环境安装centos时的磁盘规划

    一般来说,分区要按照公司领导的要求来执行.但是如果没有要求,一般按照下面的方法进行磁盘规划. /boot分区200M: swap分区分内存的2倍.如果内存大于等于8G,那么swap分8G即可: /分区 ...

  5. 使用chardet模块判断网页编码

    import chardet import urllib.request url='http://stock.sohu.com/news/' html = urllib.request.urlopen ...

  6. Python 进阶 之 yield

    .转载自:https://www.ibm.com/developerworks/cn/opensource/os-cn-python-yield/ Python yield 使用浅析: 您可能听说过, ...

  7. sublime text3下使用TAG快捷键ctrl+alt+f失效的解决方法

    系统环境:WIN7 版本: sublime text3 问题:为了方便格式化html,下的TAG插件.在package control中在线安装能够安装成功,功能正常使用,就是ctrl+alt+f(A ...

  8. BZOJ 1008: [HNOI2008]越狱-快速幂/取模

    1008: [HNOI2008]越狱 Time Limit: 1 Sec  Memory Limit: 162 MBSubmit: 8689  Solved: 3748 Description 监狱有 ...

  9. Codeforces 608 B. Hamming Distance Sum-前缀和

      B. Hamming Distance Sum   time limit per test 2 seconds memory limit per test 256 megabytes input ...

  10. (1)java版本

    jdk9新增 jshell工具, 类似python的命令行界面.