- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
注意:尽管这个问题涵盖了带有大量 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));
@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>
如上图所示。
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。
<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 应用程序)打开时调用。
oncomplete
中完成。例程(或
onsuccess
)。这就是它存在的原因。
msg
window[msg]()
的一些不同之处.如果您不能完全信任推送的消息,这会被认为有点危险。
window[msg]()
基本上运行任何以变量
msg
的内容命名的函数.例如,如果
msg
碰巧是
close
然后
window.close()
将运行,这可能不是您想要的。
msg
是一个预期的词,拒绝所有其他词。示例代码:
var validmsg = { updateModel:1, rc:1 }
[..]
if (validmsg[msg] && window[msg])
window[msg]();
remoteCommand
中处理,这将覆盖之前的消息。所以
notifyAll()
将看到两次较新的消息,旧的已丢失。
notifyAll()
告诉,哪些注册的消息将被处理。
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 };
nr
至
NotifyAll()
需要将附加参数传递给 Bean。我们叫它
msgNr
:
// Following might look a bit different on older PrimeFaces
window[msg]([{name:'msgNr', value:nr}]);
}
}
}
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
, andpfArgs
. 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 injsonMessages
or want to parse thejson
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.
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);
}
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.
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
来自
false
至
true
您需要触发
runRemote
曾经最低
nr
, 当然。
关于javascript - 从 p :remoteCommand - simulating the same using some JavaScript code 的 oncomplete 处理程序调用 JavaScript 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28793083/
我在优化 JOIN 以使用复合索引时遇到问题。我的查询是: SELECT p1.id, p1.category_id, p1.tag_id, i.rating FROM products p1
我有一个简单的 SQL 查询,我正在尝试对其进行优化以删除“使用位置;使用临时;使用文件排序”。 这是表格: CREATE TABLE `special_offers` ( `so_id` int
我有一个具有以下结构的应用程序表 app_id VARCHAR(32) NOT NULL, dormant VARCHAR(6) NOT NULL, user_id INT(10) NOT NULL
此查询的正确索引是什么。 我尝试为此查询提供不同的索引组合,但它仍在使用临时文件、文件排序等。 总表数据 - 7,60,346 产品= '连衣裙' - 总行数 = 122 554 CREATE TAB
为什么额外的是“使用where;使用索引”而不是“使用索引”。 CREATE TABLE `pre_count` ( `count_id`
我有一个包含大量记录的数据库,当我使用以下 SQL 加载页面时,速度非常慢。 SELECT goal.title, max(updates.date_updated) as update_sort F
我想知道 Using index condition 和 Using where 之间的区别;使用索引。我认为这两种方法都使用索引来获取第一个结果记录集,并使用 WHERE 条件进行过滤。 Q1。有什
I am using TypeScript 5.2 version, I have following setup:我使用的是TypeScript 5.2版本,我有以下设置: { "
I am using TypeScript 5.2 version, I have following setup:我使用的是TypeScript 5.2版本,我有以下设置: { "
I am using TypeScript 5.2 version, I have following setup:我使用的是TypeScript 5.2版本,我有以下设置: { "
mysql Ver 14.14 Distrib 5.1.58,用于使用 readline 5.1 的 redhat-linux-gnu (x86_64) 我正在接手一个旧项目。我被要求加快速度。我通过
在过去 10 多年左右的时间里,我一直打开数据库 (mysql) 的连接并保持打开状态,直到应用程序关闭。所有查询都在连接上执行。 现在,当我在 Servicestack 网页上看到示例时,我总是看到
我使用 MySQL 为我的站点构建了一个自定义论坛。列表页面本质上是一个包含以下列的表格:主题、上次更新和# Replies。 数据库表有以下列: id name body date topic_id
在mysql中解释的额外字段中你可以得到: 使用索引 使用where;使用索引 两者有什么区别? 为了更好地解释我的问题,我将使用下表: CREATE TABLE `test` ( `id` bi
我经常看到人们在其Haxe代码中使用关键字using。它似乎在import语句之后。 例如,我发现这是一个代码片段: import haxe.macro.Context; import haxe.ma
这个问题在这里已经有了答案: "reduce" or "apply" using logical functions in Clojure (2 个答案) 关闭 8 年前。 “and”似乎是一个宏,
这个问题在这里已经有了答案: "reduce" or "apply" using logical functions in Clojure (2 个答案) 关闭 8 年前。 “and”似乎是一个宏,
我正在考虑在我的应用程序中使用注册表模式来存储指向某些应用程序窗口和 Pane 的弱指针。应用程序的一般结构如下所示。 该应用程序有一个 MainFrame 顶层窗口,其中有几个子 Pane 。可以有
奇怪的是:。似乎a是b或多或少被定义为id(A)==id(B)。用这种方式制造错误很容易:。有些名字出人意料地出现在Else块中。解决方法很简单,我们应该使用ext==‘.mp3’,但是如果ext表面
我遇到了一个我似乎无法解决的 MySQL 问题。为了能够快速执行用于报告目的的 GROUP BY 查询,我已经将几个表非规范化为以下内容(该表由其他表上的触发器维护,我已经同意了与此): DROP T
我是一名优秀的程序员,十分优秀!