In a partner management, when partner number or name is entered, the partner info and photo are shown and input text to introduce partner number or name is hidden.
Then I want to execute a method in my backing bean when ESC or ENTER key are pressed
I catch the keyup event with with following javascript in the view:
<script type="text/javascript">
$(document).bind('keyup', function(e) {
debugger;
if (arguments[0].key == 'Esc') {
alert("YEAH");
}
});
</script>
How can i call my backing bean method???
public void listener() {
switch (keyCode) {
case(27):
// switch boolean attribute in bean to render view hidden panel
}
}
I've tryed with remote command or ajax listener:
<p:remoteCommand name="remote" actionListener="#{registerVisitBean.listener}" update="input_table"/>
<f:ajax event="keyup" execute="#this keyCode" listener="#{registerVisitBean.listener}" update="input_table" />
<h:inputHidden id="keyCode" binding="#{keyCode}" value="#{registerVisitBean.keyCode}" />
Both methods catch the keyup when input text is selected but when i hide it to show partner info, listener stop working.
Any ideas?
Thanks!
J
<script type="text/javascript">
$(document).bind('keyup', function(e) {
debugger;
if (arguments[0].key == 'Esc') {
alert("YEAH");
// suppose you want to call your listener here
remote([{name: 'key', value: arguments[0].key}]);
}
});
</script>
<p:remoteCommand name="remote" actionListener="#{registerVisitBean.listener}" update="input_table"/>
public void listener() {
Map<String, String> params = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String keyCode = params.get("key");
// your code
}
Related
I want to dynamically generate select box and on change event I want to call action class. getInvcId is generating select box dynamically and on change event of it, is not sending request to action.
<script type="text/javascript">
$(document).ready(function(){
$.post('getInvcId',function(res){
var id=res.split(",");
var newOptions=[];
newOptions.push("<option value=''>Select Invoice ID</option>");
$.each(id, function(key,value){
if(value!=="")
{
newOptions.push("<option value='"+value+"'>"+value+"</option>");
}
$("#invcnum").html(newOptions.join(''));
});
});
$.post('payBkid',function(res){
var id=res.split(",");
var newOptions=[];
newOptions.push("<option value=''>Select Booking ID</option>");
$.each(id, function(key,value){
if(value!=="")
{
newOptions.push("<option value='"+value+"'>"+value+"</option>");
}
$("#bkid").html(newOptions.join(''));
});
});
$("#invcnum").on('change',function(){
var invc=$("#invcnum").val();
var data={'invoice':invc};
$.post('searchPayment', data, function(res){
alert("hello");
});
});
});
</script>
This is my code
function sendMessage()
{
if(textMessage.value!=="close")
{
if(searchid==="John" && login_id==="Mary" || searchid==="Mary" && login_id==="John")
{
webSocket.send(textMessage.value);
textMessage.value="";
}
}
else
{
webSocket.close();
}
}
I am making a chat application and getting response from server.Firstly the server was sending response to all the clients connected to it.But now I am converting it into one to one client based chat but the problem is if john is chatting with mary these values are placed in database and I can only one time get the data from database via scriplet when page is loaded so how to implement it when user want to chat with say dave.Then I can't get the values from database.
I totally understand that you would like to write this by your self, but there are lots of frameworks out there that will help you with the complex stuff and let you focus on the actuall business issues to solve.
We use XSockets.NET most of the time since that is perfect for our needs.
Setting ap a one to one chat (or other scenarios) is very easy with XSockets since it is all about publish/subscribe... And you can also filter where to send messages on the server with powerful extension methods
A simple sample chat:
To save some time and keep it stupid and simple I will use two dropdowns where you select your name and the city you are in. So not actually 1-1, but it is so that you would get the concept.
JAVASCRIPT/MARKUP
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-2.1.0.js"></script>
<script src="Scripts/moment.js"></script>
<script src="Scripts/XSockets.latest.js"></script>
<script src="Scripts/knockout-3.1.0.js"></script>
<script>
//viewmodel for our messages
var vm = {
messages : ko.observableArray([])
}
//xsockets connection
var conn;
$(function() {
ko.applyBindings(vm);
//Connect to our controller (Chat)
conn = new XSockets.WebSocket('ws://127.0.0.1:4502/Chat');
conn.onopen = function() {
//open, set city and username (for demo only)
conn.setProperty("UserName", $('#username').val());
conn.setProperty("City", $('#cities').val());
//listen for chatmesages
conn.on('chatmessage', function (d) {
//Add message to viewmodel
vm.messages.push(d);
});
}
//When we hit enter, send a message
$('input').on('keydown', function (e) {
if (e.keyCode == 13) {
//Build message, we do not need to set From since the server know who I am
var message = { Text: $(this).val(), Time: moment().format('MMMM Do YYYY, h:mm:ss a') };
conn.publish('chatmessage', message);
}
});
//When City or Username is changed, tell the server
$('#cities').on('change', function(d) {
conn.setProperty("City", $(this).val());
});
$('#username').on('change', function (d) {
conn.setProperty("UserName", $(this).val());
});
});
</script>
</head>
<body>
<input type="text" placeholder="type here, enter to send"/>
<select id="username">
<option value="steve">steve</option>
<option value="ben">ben</option>
<option value="tomas">tomas</option>
</select>
<select id="cities">
<option value="london">london</option>
<option value="paris">paris</option>
<option value="tokyo">tokyo</option>
</select>
<div data-bind="foreach:messages">
<h5 data-bind="text:From + ' - ' + Time"></h5>
<div data-bind="text:Text"></div>
</div>
</body>
</html>
C#
using XSockets.Core.XSocket;
using XSockets.Core.XSocket.Helpers;
namespace SimpleChat
{
public class ChatMessage
{
public string From { get; set; }
public string Text { get; set; }
public string Time { get; set; }
}
public class Chat : XSocketController
{
/// <summary>
/// My name, we set this from javascript...
/// </summary>
public string UserName { get; set; }
/// <summary>
/// We only send to people being in the same city, we set it from javascript
/// </summary>
public string City { get; set; }
/// <summary>
/// A user sends a message
/// </summary>
/// <param name="chatMessage"></param>
public void ChatMessage(ChatMessage chatMessage)
{
chatMessage.From = this.UserName;
//Send only to the client(s) being in the same city, but you can ofcourse change ot to another user only etc
this.SendTo(p => p.City == this.City, chatMessage,"chatmessage");
}
}
}
Summary
The only thing I did except the code above was to create a new project and then
Install XSockets (to start a xsockets server)
Install XSockets.JsApi (for publish subscribe over websockets)
Install jQuery (becasue I am lazy)
Install Momoent.JS (for working wiht dates in javascript)
Install knockoutjs (for modelbinding)
Added a XSockets bootstrapper into App_Start (found under Add->NewItem->XSockets->XSockets.Web.Bootstrapper
I guess you simply need to add control functionality to your program:
Add two listboxes and two buttons for picking sender, receiver (search_id,log_id)
List <string> logins=new List<string>();
List <string> search=new List<string>();
........
logins.Add("John");
logins.Add("Mary");
.....
search.Add("Dave");
listBox1.Datasource=logins;
listBox2.Datasource=search;
private void button1_Click(object sender, EventArgs e) //pick login_id
{
login_id_to_Compare=listBox1.SelectedValue.ToString();
}
private void button2_Click(object sender, EventArgs e) //pick searcid
{
searchid_to_Compare=listBox2.SelectedValue.ToString();
}
function sendMessage()
{
if(textMessage.value!=="close")
{
if((searchid===searchid_to_Compare) && (login_id===login_id_to_Compare))
{
webSocket.send(textMessage.value);
textMessage.value="";
}
}
else
{
webSocket.close();
}
}
Your send message seems too simplistic. There is not enough info for the server to route the message to the correct destination.
You would need to send along with the message the destination so your server can route the message to the correct user.
In your db you then can save the "to" and "from" and display the correct messages for only the parties involved.
You would of course have to add the fields to your chat program to select the destination.
function sendMessage(from, to, msg)
{
webSocket.send("{'from':" + from + ", 'to':" + to + ", 'msg': " + msg + "}");
}
I want to pass textfield with id value pat to the getautocomplete.action in Struts 2. Here I am using TINY.box to pop up the next page.
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
T$('tiny_patient').onkeypress = function(){
TINY.box.show('getautocomplete.action',1,0,0,1)
}
</script>
You need to append the id pat and its value to the url that you pass to the show function. For example
var url = 'getautocomplete.action?pat=' + $("#pat").val();
You can then use the variable url in your show function.
You also need to add the following in your action class. This also depends on the java type of pat. I am using String,
private String pat;
public String getPat()
{
return pat;
}
public void setPat(final String value)
{
this.pat = value;
}
Note
It is recommended to get your url using the following instead of hard-coding the extension
<s:url id="url_variable" namespace="/namespace_of_action" action="action_name" />
var url = '<s:property value="url_variable" />?pat=' + $("#pat").val();
If you are trying to populate the box based on previous box selection or any server side process you have to use ajax.
In your action class , write a getter-setter for variable named "pat" like this:
private string pat;
public getPat()
{
.........
}
public setPat(String pat)
{
this.pat=pat;
}
and change
TINY.box.show('getautocomplete.action',1,0,0,1)
to
TINY.box.show('getautocomplete.action?pat="xyz"',1,0,0,1)
Hope this will solve your problem unless you have an idea about ajax.
Try
<s:textfield name="pat" id="pat"/>
<script type="text/javascript">
document.getElementById("tiny_patient").onkeypress = function(e){
TINY.box.show("<s:url action='getautocomplete'/>"+"?pat="+document.getElementById("pat").value,1,0,0,1)
}
</script>
I am new to Spring and web technology.
I have an table which contains a column with hyperlink. When I click on the hyperlink of a row, I need to display that rows data along with other details in a dialog. My controller method returns a ModelAndView which contains the data I need to show and the display page.
Problems:
How to show the dialog? and
How to pass the data to the dialog?
Table.jsp
<script type="text/javascript">
function showDialog(ref, date) {
$ajax({
type: "POST",
url: "/example/show.htm",
data: {
ref: ref,
date: date
}
success: function(data) {
},
error: function(data) {
}
});
}
</script>
Mapping
#RequestMapping(value = "show.htm", method=RequestMethod.POST)
public ModelAndView show(#RequestParam("ref") String ref, #RequestParam("date") String date,
HttpServletRequest request, HttpServletResponse response) {
ModelAndView modelAndView = new ModelAndView();
try {
SampleDTO SampleDTO = new SampleDTO();
sampleDTO.setDate(sdf.parse(date));
sampleDTO.setRef(ref);
SampleDTO billDto = // server call modelAndView.addObject("showBill", sampleDto);
modelAndView.setViewName("Dialog");
}
return modelAndView;
}
Your code is wrong, you are messing things, if you want to use jQuery and ajax calls then don't use ModelAndView in your Spring controller. Instead of that, use the following and return your bean or dto as a json using Jackson library from Java:
Include this jar in your lib project folder:
http://www.java2s.com/Code/JarDownload/jackson/jackson-all-1.9.9.jar.zip
Java code:
#RequestMapping(value = "businessBill.htm", method = RequestMethod.POST)
#ResponseBody
public String handleBusinessBillDetails(#RequestParam("reference") String billReference, #RequestParam("invoiceDate") String billDate,
HttpServletRequest request, HttpServletResponse response) {
String json = null;
try {
//1. Create 'jackson' object mapper
ObjectMapper objectMapper = new ObjectMapper();
BusinessBillDTO businessBillDTO = new BusinessBillDTO();
businessBillDTO.setBillDate(sdf.parse(billDate));
businessBillDTO.setBillReference(billReference);
BusinessBillDTO billDto = accountStatementBO.getBusinessBillDetails(businessBillDTO);
//2. Convert your 'bean' or 'dto' as 'json' string
json = objectMapper.writeValueAsString(billDto);
} catch (Exception ex) {
LOGGER.error(ex);
}
return json;
}
Then, in Table.jsp put the div used in Dialog.jsp as hidden, this will be your modal dialog in future (note that there are some changes in the span tags also):
<div id="BusinessBill" style="display:none;">
<h2>Bill Details</h2>
<em>Business Ltd</em>
<div class="row">
<span class="spanAsLabel">Account number</span>
<span id="dlg-account-number" class="spanAsLabel"></span>
</div>
<div class="row">
<span class="spanAsLabel">Bill date</span>
<span id="dlg-bill-date" class="spanAsLabel"></span>
</div>
</div>
Now fix your getBusinessBill(..) method like this:
You can also use $.ajax and maybe handle more states like onerror and others but this way is simpler (at least for me, you just need to evaluate if the returned data is null or not and let know the user - if null - that something happened at server side, maybe showing an alert with a generic message) - please read comments.
function getBusinessBill(billReference, billInvoiceDate) {
$.post("/AccountStatement/businessBill.htm", {
reference: billReference,
invoiceDate: billInvoiceDate
}, function (data) {
/* You can implement more validations for 'data', in my case I just used these 'if' conditionals but can vary. */
if(data != null) { //returned 'data' is not 'null'
/* parse 'data' as 'json' object
* will be good to console.log(data) and take a look. */
var obj = $.parseJSON(data);
if(obj != {}) { //check if 'data' is not an empty 'json' object once transformed
//set the 'data' in the dialog
$('#dlg-account-number').text(obj.accountNumber);
$('#dlg-bill-date').text(obj.billDate);
/* open modal dialog, you can simulate it this way (for this case)
* but the correct way is to use 'jquery-ui' dialog or any plugin you prefer.
* At this point you will see the hidden 'div' in a visible way with your 'data'.
*/
$('#BusinessBill').fadeIn();
} else {
//show 'generic' message
alert('No results found.');
}
} else {
//show 'generic' message
alert('An error occurred, try again.');
}
});
}
Finally, if everything is correct, you will see at the same page (Table.jsp) the modal dialog with your data, all made by an ajax call to avoid redirection pages like (Table.jsp to => Dialog.jsp).
I want to call java methods in javascript and Andrew Thompson suggested to use the deployJava.js library for this. I followed these instructions:
http://docs.oracle.com/javase/6/docs/technotes/guides/jweb/deployment_advice.html
Here is explained how to use the java class in javascript, but I would like to call the java methods from within the javascript. (This is because I want to import a .owl file in java en export the information in json-format to my code written in javascript.)
Does anybody know how to do this with the deployJava library?
This is my code to import the java file:
<noscript>A browser with JavaScript enabled is required for this page to operate properly.</noscript>
<h1>Sending Messages to Other Applets</h1>
<script>
function sendMsgToIncrementCounter() {
receiver.incrementCounter();
}
</script>
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'Sender.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'../Receiver.class', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
and this is are the sender and receiver java files:
import javax.swing.*;
public class Receiver extends JApplet {
private int ctr = 0;
private JLabel ctrLbl = null;
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
ctrLbl = new JLabel("");
add(ctrLbl);
}
});
} catch (Exception e) {
System.err.println("Could not create applet's GUI");
}
}
public void incrementCounter() {
ctr++;
String text = " Current Value Of Counter: " + (new Integer(ctr)).toString();
ctrLbl.setText(text);
}
}
import javax.swing.*;
import java.awt.event.;
import netscape.javascript.;
public class Sender extends JApplet implements ActionListener {
public void init() {
//Execute a job on the event-dispatching thread; creating this applet's GUI.
try {
final ActionListener al = this;
SwingUtilities.invokeAndWait(new Runnable() {
public void run() {
JButton btn = new JButton("Click To Increment Counter");
add(btn);
btn.addActionListener(al);
}
});
} catch (Exception e) {
System.err.println("createGUI didn't complete successfully");
}
}
public void actionPerformed(ActionEvent e) {
try {
JSObject window = JSObject.getWindow(this);
window.eval("sendMsgToIncrementCounter()");
} catch (JSException jse) {
jse.printStackTrace();
}
}
}
I just copy-paste this from the example given on this site:
http://docs.oracle.com/javase/tutorial/deployment/applet/iac.html
This example works perfect in my browser, so the way it is done is correct, but I suspect that I don't import the javafiles correct, since this are the errors from je java-console:
load: class Sender.class not found.
java.lang.ClassNotFoundException: Sender.class
at sun.plugin2.applet.Applet2ClassLoader.findClass(Applet2ClassLoader.java:195)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass0(Plugin2ClassLoader.java:249)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:179)
at sun.plugin2.applet.Plugin2ClassLoader.loadClass(Plugin2ClassLoader.java:160)
at java.lang.ClassLoader.loadClass(ClassLoader.java:247)
at sun.plugin2.applet.Plugin2ClassLoader.loadCode(Plugin2ClassLoader.java:690)
at sun.plugin2.applet.Plugin2Manager.createApplet(Plugin2Manager.java:3045)
at sun.plugin2.applet.Plugin2Manager$AppletExecutionRunnable.run(Plugin2Manager.java:1497)
at java.lang.Thread.run(Thread.java:680)
Exception: java.lang.ClassNotFoundException: Sender.class
Combining your original method, with the new JS snippet, and part of the accepted answer on your last question (tweaked), gives..
<html>
<head>
<script>
// dangerous to have a 0x0 applet! Some security plug-ins regard it
// as suspicious & automatically remove the element. Better to set it
// not visible using styles
var attributes = {
codebase:'../sesame',
code:'applet_test',
width:10,
height:10
};
var parameters = {fontSize:16} ;
var version = '1.6' ;
deployJava.runApplet(attributes, parameters, version);
function test() {
var app = document.applet_test;
alert("Screen Dimension\r\n width:" + app.getScreenWidth()
+ " height:" + app.getScreenHeight());
}
</script>
<body>
<FORM>
<INPUT
type="button"
value="call JAVA"
onClick = "test()">
</FORM>
<script>
deployJava.runApplet(attributes, parameters, version);
</script>
</body>
</html>
But I just wrote that up off the top of my head. Don't trust me, trust a validation service. ;)
I would advise setting up a simple webservice that your javascript code can use. It doesn't need to be very involved, personally I'd use a simple REST layout with JAX-RS (jersey is really nice to work with), especially if you want something simple with JSON support built-in (with the right plugin).
Trying to actually communicate with the applet on the page might be possible, but very browser dependent and IMHO not worth the hassle. If you're working on the web, might as well use a web service.
There was a problem with the directory of the .class files given in the attributes. Here is the correct code:
<p>Sender Applet</p>
<script>
var attributes = { id:'sender', code:'sesame/Sender.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>
<br/>
<br/>
<p>Receiver Applet</p>
<script>
var attributes = { id:'receiver', code:'sesame/Receiver.class', archive:'sesame/applet_SenderReceiver.jar', width:300, height:50} ;
var parameters = {} ;
deployJava.runApplet(attributes, parameters, '1.6');
</script>