gpt4 book ai didi

javascript - 从 p :remoteCommand - simulating the same using some JavaScript code 的 oncomplete 处理程序调用 JavaScript 函数

转载 作者:行者123 更新时间:2023-12-03 22:34:01 29 4
gpt4 key购买 nike

注意:尽管这个问题涵盖了带有大量 Java 代码片段的长文本信息,但它仅针对 JavaScript/jQuery 和一些 PrimeFaces 内容(仅 <p:remoteCommand> ),如开头的介绍部分所述。

我收到来自 WebSockets(Java EE 7/JSR 356 WebSocket API)的 JSON 消息,如下所示。

if (window.WebSocket) {
var ws = new WebSocket("wss://localhost:8181/ContextPath/AdminPush");

ws.onmessage = function (event) {
jsonMsg=event.data;
var json = JSON.parse(jsonMsg);
var msg=json["jsonMessage"];

if (window[msg]) {
window[msg](); //It is literally interpreted as a function - updateModel();
}
};
}

在上面的代码中, event.data包含一个 JSON 字符串 {"jsonMessage":"updateModel"} .因此, msg将包含一个字符串值,它是 updateModel .

在以下代码段中,

if (window[msg]) {
window[msg](); //It is literally interpreted as a JavaScript function - updateModel();
}
window[msg]();导致与 <p:remoteCommand> 关联的 JavaScript 函数被调用(依次调用与 actionListener="#{bean.remoteAction}" 关联的 <p:remoteCommand> )。
<p:remoteCommand name="updateModel"
actionListener="#{bean.remoteAction}"
oncomplete="notifyAll()"
process="@this"
update="@none"/>
update="@none"不一定需要。

收到此消息后,我需要将此更新通知所有关联的客户端。我使用以下与 oncomplete 相关联的 JavaScript 函数来执行此操作。上述处理程序 <p:remoteCommand> .

var jsonMsg;

function notifyAll() {
if(jsonMsg) {
sendMessage(jsonMsg);
}
}

注意变量 jsonMsg已经在第一个片段中分配了一个值 - 它是一个全局变量。 sendMessage()是另一个 JavaScript 函数,它实际上通过 WebSockets 向所有关联的客户端发送有关此更新的通知,这在本问题中是不需要的。

这很有效,但有没有办法在以下条件下做一些魔术

if (window[msg]) {
window[msg]();

//Do something to call notifyAll() on oncomplete of remote command.
}

使 notifyAll()函数可以通过一些 JavaScript 代码直接调用(当前附加到 oncomplete of <p:remoteCommand> 并且预期的 JavaScript 代码(甚至其他东西)应该模拟这个 oncomplete )基本上消除了依赖全局 JavaScript 的需要变量( jsonMSg )?

编辑:我试图解决的问题(它可能被认为是附加信息)。

例如,当管理员对名为 Category 的 JPA 实体进行一些更改(通过 DML 操作)时,实体监听器被触发,进而导致 CDI 事件按如下方式引发。
@ApplicationScoped
public class CategoryListener {

@PostPersist
@PostUpdate
@PostRemove
public void onChange(Category category) throws NamingException {
BeanManager beanManager = (BeanManager) InitialContext.doLookup("java:comp/BeanManager");
beanManager.fireEvent(new CategoryChangeEvent(category));
}
}

不用说实体 Category用注释 @EntityListeners(CategoryListener.class) 指定.

只是一个旁注( 完全偏离主题 ):获取 BeanManager 的实例在前面的代码片段中通过 JNDI 查找是临时的。具有 Weld 版本 2.2.2 final 的 GlassFish Server 4.1 无法注入(inject) CDI 事件 javax.enterprise.event.Event<T>应该按如下方式注入(inject)。
@Inject
private Event<CategoryChangeEvent> event;

然后,可以引用上面的相关代码片段按如下方式触发事件。
event.fire(new CategoryChangeEvent(category));



在 web 项目中观察到此事件如下。
@ApplicationScoped
public class RealTimeUpdate {

public void onCategoryChange(@Observes CategoryChangeEvent event) {
AdminPush.sendAll("updateModel");
}
}

管理员使用他自己的端点如下( AdminPush.sendAll("updateModel"); 在其中手动调用)。
@ServerEndpoint(value = "/AdminPush", configurator = ServletAwareConfig.class)
public final class AdminPush {

private static final Set<Session> sessions = new LinkedHashSet<Session>();

@OnOpen
public void onOpen(Session session, EndpointConfig config) {
if (Boolean.valueOf((String) config.getUserProperties().get("isAdmin"))) {
sessions.add(session);
}
}

@OnClose
public void onClose(Session session) {
sessions.remove(session);
}

private static JsonObject createJsonMessage(String message) {
return JsonProvider.provider().createObjectBuilder().add("jsonMessage", message).build();
}

public static void sendAll(String text) {
synchronized (sessions) {
String message = createJsonMessage(text).toString();
for (Session session : sessions) {
if (session.isOpen()) {
session.getAsyncRemote().sendText(message);
}
}
}
}
}

此处仅允许管理员使用此端点。使用 onOpen() 中的条件检查阻止所有其他用户创建 WebSocket session 。方法。
session.getAsyncRemote().sendText(message);foreach loop 向管理员发送通知(以 JSON 消息的形式)关于实体 Category 中所做的这些更改。 .

如第一个代码片段所示, window[msg]();调用与应用程序作用域 bean - <p:remoteCommand> 关联的操作方法(通过前面所示的 actionListener="#{realTimeMenuManagedBean.remoteAction}") .
@Named
@ApplicationScoped
public class RealTimeMenuManagedBean {

@Inject
private ParentMenuBeanLocal service;

private List<Category> category;
private final Map<Long, List<SubCategory>> categoryMap = new LinkedHashMap<Long, List<SubCategory>>();
// Other lists and maps as and when required for a dynamic CSS menu.

public RealTimeMenuManagedBean() {}

@PostConstruct
private void init() {
populate();
}

private void populate() {
categoryMap.clear();
category = service.getCategoryList();

for (Category c : category) {
Long catId = c.getCatId();
categoryMap.put(catId, service.getSubCategoryList(catId));
}
}

// This method is invoked through the above-mentioned <p:remoteCommand>.
public void remoteAction() {
populate();
}

// Necessary accessor methods only.
}

只有在 actionListener="#{realTimeMenuManagedBean.remoteAction}" 时才应通知所有其他用户/客户端(位于不同面板上 - 除了管理面板)完全完成 - 不能在操作方法完成之前发生 - 应该通过 oncomplate 通知<p:remoteCommand> 的事件处理程序. 这就是采用两个不同终点的原因。

那些其他用户使用他们自己的端点:
@ServerEndpoint("/Push")
public final class Push {

private static final Set<Session> sessions = new LinkedHashSet<Session>();

@OnOpen
public void onOpen(Session session) {
sessions.add(session);
}

@OnClose
public void onClose(Session session) {
sessions.remove(session);
}

@OnMessage
public void onMessage(String text) {
synchronized (sessions) {
for (Session session : sessions) {
if (session.isOpen()) {
session.getAsyncRemote().sendText(text);
}
}
}
}
}

@OnMessage 注释的方法开始播放,当通过 oncomplete 发送消息时的 <p:remoteCommand>如上图所示。

这些客户端使用以下 JavaScript 代码从上述应用程序作用域 bean 中获取新值(该 bean 已经由管理员从数据库中充分查询。因此,没有必要由每个人再次荒谬地查询它单独的客户端(除了管理员)。因此,它是一个应用程序范围的 bean)。

if (window.WebSocket) {
var ws = new WebSocket("wss://localhost:8181/ContextPath/Push");
ws.onmessage = function (event) {
var json = JSON.parse(event.data);
var msg = json["jsonMessage"];

if (window[msg]) {
window[msg]();
}
};

$(window).on('beforeunload', function () {
ws.close();
});
}

结合以下 <p:remoteCommand> .
<p:remoteCommand name="updateModel"
process="@this"
update="parentMenu"/>

哪里 parentMenu - 此组件要更新 <p:remoteCommand>id容器 JSF 组件 <h:panelGroup>它包含一个简单的 CSS 菜单和一堆 <ui:repeat> s。

希望这能让场景更清晰。

更新 :

这个问题已经准确回答 here基于 <p:remoteCommand> (至于具体问题,唯一的问题是消除对全局 JavaScript 变量的依赖,如本问题介绍部分所述)。

最佳答案

我不认为我理解你问题的方方面面,但无论如何我都会尝试提供一些帮助。请注意,我不知道 PrimeFaces,所以我所做的只是阅读文档。

我的理解是,您试图摆脱全局变量。但恐怕,我不认为这是可能的。

这里的问题是,PrimeFaces 不允许您将远程调用的调用透明地传递给 oncomplete。调用(除非您将其传递给 Bean 的 Java 代码,然后返回到 UI,这通常不是您想要的)。

但是,我希望,您可以非常接近它。

Part 1, JS 提前返回

另请注意,可能对 Java 和 JavaScript 存在一些误解。

Java 是多线程的并并行运行多个命令,而 JavaScript 是单线程的,通常从不等待某事完成。异步操作是获得响应式 Web-UI 所必需的。

因此您的 remoteCommand调用(从 JS 端看)将(通常是异步情况)早于 oncomplete 返回将调用处理程序。这意味着,如果 window[msg]()返回,您还没有完成 remoteCommand然而。

那么你想用以下代码管理什么

if (window[msg]) {
window[msg]();

//Do something to call notifyAll() on oncomplete of remote command.
dosomethinghere();
}

将失败。 dosomethinghere() remoteCommand 时不会被调用返回(因为 JS 不想等待某些可能永远不会发生的事件)。这意味着, dosomethinghere()将在 Ajax 请求刚刚向远程(Java 应用程序)打开时调用。

要在 Ajax 调用完成后运行一些东西,这必须在 oncomplete 中完成。例程(或 onsuccess)。这就是它存在的原因。

第 2 部分,验证 msg
请注意关于 window[msg]() 的一些不同之处.如果您不能完全信任推送的消息,这会被认为有点危险。 window[msg]()基本上运行任何以变量 msg 的内容命名的函数.例如,如果 msg碰巧是 close然后 window.close()将运行,这可能不是您想要的。

你应该确保, msg是一个预期的词,拒绝所有其他词。示例代码:
var validmsg = { updateModel:1, rc:1 }

[..]

if (validmsg[msg] && window[msg])
window[msg]();

第 3 部分:如何并行处理多个 JSON 消息

全局变量有一些缺点。只有一个。如果您碰巧在 WebSocket 上收到另一条 JSON 消息,而前一条消息仍在 remoteCommand 中处理,这将覆盖之前的消息。所以 notifyAll()将看到两次较新的消息,旧的已丢失。

一个经典的竞争条件。你必须做的是,创建一个类似于注册表的东西来注册所有的消息,然后将一些值传递给 notifyAll()告诉,哪些注册的消息将被处理。

只需稍加改动,您就可以并行(此处)或串行(第 4 部分)处理消息。

首先,创建一个计数器以区分消息。也是一个存储所有消息的对象。并且我们声明我们期望的所有有效消息(参见第 2 部分):
var jsonMsgNr = 0;
var jsonMessages = {};
var validmsg = { updateModel:1 }

现在每次我们收到一条消息时添加一条消息:
if (window.WebSocket) {
var ws = new WebSocket("wss://localhost:8181/ContextPath/AdminPush");

ws.onmessage = function (event) {
var jsonMsg = event.data;
var json = JSON.parse(jsonMsg);
var msg=json["jsonMessage"];

if (validmsg[msg] && window[msg]) {
var nr = ++jsonMsgNr;
jsonMessages[nr] = { jsonMsg:jsonMsg, json:json };

为了能够通过 nrNotifyAll()需要将附加参数传递给 Bean。我们叫它 msgNr :
            // Following might look a bit different on older PrimeFaces
window[msg]([{name:'msgNr', value:nr}]);
}
}
}

也许看看 https://stackoverflow.com/a/7221579/490291有关以这种方式传递值的更多信息。
remoteAction bean 现在获得一个附加参数 msgNr通过,必须通过 Ajax 传回。

Unfortunately I have no idea (sorry) how this looks in Java. So make sure, your answer to the AjaxCall copies the msgNr out again.

Also, as the documentation is quiet about this subject, I am not sure how the parameters are passed back to the oncomplete handler. According to the JavaScript debugger, notifyAll() gets 3 parameters: xhdr, payload, and pfArgs. Unfortunately I was not able to setup a test case to find out how things look like.



因此该函数看起来有点像(请耐心等待):
function notifyAll(x, data, pfArgs) {
var nr = ???; // find out how to extract msgNr from data

var jsonMsg = jsonMessages[nr].jsonMsg;
var json = jsonMessages[nr].json;
jsonMessages[nr] = null; // free memory

sendMessage(jsonMsg);

dosomething(json);
}

如果将其拆分为两个函数,则可以调用 notifyAll()来自应用程序中的其他部分:
function notifyAll(x, data, unk) {
var nr = ???; // find out how to extract msgNr from data

realNotifyAll(nr);
}

function realNotifyAll(nr) {
if (!(nr in jsonMessages)) return;

var jsonMsg = jsonMessages[nr].jsonMsg;
var json = jsonMessages[nr].json;
delete jsonMessages[nr]; // free memory

sendMessage(jsonMsg);

dosomething(json);
}

Some things here are a bit redundant. For example you perhaps do not need the json element in jsonMessages or want to parse the json again to spare some memory in case the json is very big. However the code is meant not to be optimal but to be easy to adjust to your needs.



第 4 部分:序列化请求

现在更改以序列化事物。通过添加一些信号量,这很容易。 JavaScript 中的信号量只是变量。这是因为只有一个全局线程。
var jsonMsgNr = 0;
var jsonMessages = {};
var validmsg = { updateModel:1 }
var jsonMsgNrLast = 0; // ADDED

if (window.WebSocket) {
var ws = new WebSocket("wss://localhost:8181/ContextPath/AdminPush");

ws.onmessage = function (event) {
var jsonMsg = event.data;
var json = JSON.parse(jsonMsg);
var msg=json["jsonMessage"];

if (validmsg[msg] && window[msg]) {
var nr = ++jsonMsgNr;
jsonMessages[nr] = { jsonMsg:jsonMsg, json:json };

if (!jsonMsgNrLast) { // ADDED
jsonMsgNrLast = nr; // ADDED
window[msg]([{name:'msgNr', value:nr}]);
}
}
}
}

function realNotifyAll(nr) {
if (!(nr in jsonMessages)) return;

var jsonMsg = jsonMessages[nr].jsonMsg;
var json = jsonMessages[nr].json;
delete jsonMessages[nr]; // free memory

sendMessage(jsonMsg);

dosomething(json);

// Following ADDED
nr++;
jsonMsgNrLast = 0;
if (nr in jsonMessages)
{
jsonMsgNrLast = nr;
window[jsonMessages[nr].json.msg]([{name:'msgNr', value:nr}]);
}
}

注: jsonMsgNrLast可能只是一个标志(真/假)。然而,将当前处理的数字放在一个变量中可能会在其他地方有所帮助。

话虽如此,如果在 sendMessage 中出现故障,则存在饥饿问题。或 dosomething .所以也许你可以稍微交错一下:
function realNotifyAll(nr) {
if (!(nr in jsonMessages)) return;

var jsonMsg = jsonMessages[nr].jsonMsg;
var json = jsonMessages[nr].json;
delete jsonMessages[nr]; // free memory

nr++;
jsonMsgNrLast = 0;
if (nr in jsonMessages)
{
jsonMsgNrLast = nr;
// Be sure you are async here!
window[jsonMessages[nr].json.msg]([{name:'msgNr', value:nr}]);
}

// Moved, but now must not rely on jsonMsgNrLast:
sendMessage(jsonMsg);
dosomething(json);
}

这样,AJAX 请求就已经在 sendMessage 发出了。在跑。如果现在 dosomething有 JavaScript 错误或类似错误,消息仍能正确处理。

Please note: All this was typed in without any tests. There might be syntax errors or worse. Sorry, I tried my best. If you find a bug, edit is your friend.



第 5 部分:从 JS 直接调用

现在,有了所有这些和序列化的运行,您可以随时调用之前的 notifyAll()使用 realNotifyAll(jsonMsgNrLast) .或者您可以显示 jsonMessages在列表中并选择任意数字。

通过跳过对 window[jsonMessages[nr].json.msg]([{name:'msgNr', value:nr}]); 的调用(以及高于 window[msg]([{name:'msgNr', value:nr}]); )您还可以停止 Bean 处理并使用通常的 JQuery 回调按需运行它。为此,创建一个函数并再次更改代码:
var jsonMsgNr = 0;
var jsonMessages = {};
var validmsg = { updateModel:1 }
var jsonMsgNrLast = 0;
var autoRun = true; // ADDED, set false control through GUI

if (window.WebSocket) {
var ws = new WebSocket("wss://localhost:8181/ContextPath/AdminPush");

ws.onmessage = function (event) {
var jsonMsg = event.data;
var json = JSON.parse(jsonMsg);

if (validmsg[msg] && window[msg]) {
var nr = ++jsonMsgNr;
jsonMessages[nr] = { jsonMsg:jsonMsg, json:json };

updateGuiPushList(nr, 1);

if (autoRun && !jsonMsgNrLast) {
runRemote(nr);
}
}
}
}

function realNotifyAll(nr) {
if (!(nr in jsonMessages)) return;

var jsonMsg = jsonMessages[nr].jsonMsg;
var json = jsonMessages[nr].json;
delete jsonMessages[nr]; // free memory

updateGuiPushList(nr, 0);

jsonMsgNrLast = 0;
if (autoRun)
runRemote(nr+1);

// Moved, but now must not rely on jsonMsgNrLast:
sendMessage(jsonMsg);
dosomething(json);
}

function runRemote(nr) {
if (nr==jsonMsgNrLast) return;
if (nr in jsonMessages)
{
if (jsonMsgNrLast) { alert("Whoopsie! Please wait until processing finished"); return; }
jsonMsgNrLast = nr;

updateGuiPushList(nr, 2);

// Be sure you are async here!
window[jsonMessages[nr].json.msg]([{name:'msgNr', value:nr}]);
}
}

现在您可以开始处理 runRemote(nr)并使用 realNotifyAll(nr) 调用完成函数.

函数 updateGuiPushList(nr, state)state=0:finished 1=added 2=running是对 GUI 代码的回调,它更新屏幕上等待处理的推送列表。套装 autoRun=false停止自动处理和 autoRun=true用于自动处理。

注意:设置后 autoRun来自 falsetrue您需要触发 runRemote曾经最低 nr , 当然。

关于javascript - 从 p :remoteCommand - simulating the same using some JavaScript code 的 oncomplete 处理程序调用 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28793083/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com