调用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. Method and apparatus for providing total and partial store ordering for a memory in multi-processor system

    An improved memory model and implementation is disclosed. The memory model includes a Total Store Or ...

  2. malloc和new的区别 end

    3. c++中new的几种用法 c++中,new的用法很灵活,这里进行了简单的总结: 1. new() 分配这种类型的一个大小的内存空间,并以括号中的值来初始化这个变量; 2. new[] 分配这种类 ...

  3. sql文格式替换

    SELECT COUNT(1)FROM TAB1 TWHERE T.IS_DEL <> 0 将以上SQL格式替换为代码中的格式 sql.AppendLine(" SELECT & ...

  4. golang中的反射

    反射操作普通变量 package main import ( "fmt" "reflect" ) func main(){ a := 1 //reflect.T ...

  5. golang的各种打印

    golang的打印方法太特么多了,下面就来区分一下之间的差异 package main import ( "fmt" "os" ) func main() { ...

  6. python unittest 快速入门

    import unittest def add(x, y): return x + y class TestLearning(unittest.TestCase): def setUp(self): ...

  7. IOS UITableViewUITableView小技巧--实现cell向左滑动删除,编辑等功能

    - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath { return Y ...

  8. 网关协议:CGI、FastCGI、WSGI

    CGI就像是一座桥,把网页和WEB服务器中的执行程序连接起来,它把HTML接收的指令传递给服务器的执行程序,再把服务器执行程序的结果返还给HTML页. CGI CGI即通用网关接口(Common Ga ...

  9. Servlet response原理

    首先web服务器 接受到http请求后转交给相应的servlet进行处理这个过程可以他通过配置web.xml来进行确定,然后web服务器将相应的信息封装到request和response对象,由相应的 ...

  10. 树链剖分【CF343D】Water Tree

    Description Mad scientist Mike has constructed a rooted tree, which consists of nnvertices. Each ver ...