grails javax.websocket issues - grails

Grails 2.3.7 - Java 1.7
I have seen the following example used in core java and working as a demo, trying to achieve the same in Grails, I know there are a few plugins around websockets but I was trying to figure this out on my own :
Controller 1
package chat
class TestController {
def index() { }
}
index.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main">
<g:set var="entityName" value="${message(code: 'admin.label', default: 'Admin')}" />
<title><g:message code="default.create.label" args="[entityName,BAH,BAH]" /></title>
</head>
<body>
<form>
<input id="textMessage" type="text">
<input type="button" value="send" onClick="sendMessage();">
</form>
<br>
<textarea id="messagesTextarea" rows="10" cols="50">
</textarea>
<script type="text/javascript">
var webSocket=new WebSocket("ws://localhost:8080/chat/testing");
var messagesTextarea=document.getElementById("messagesTextarea");
var textMessage=document.getElementById("textMessage");
webSocket.onopen=function(message) {processOpen(message);};
webSocket.onmessage=function(message) {processMessage(message);};
webSocket.onclose=function(message) {processClose(message);};
webSocket.onerror=function(message) {processError(message);};
function processOpen(message) {
messagesTextarea.value +=" Server Connect.... "+"\n";
}
function processMessage(message) {
messagesTextarea.value +=" Receive from Server ===> "+ message.data +"\n";
}
function sendMessage() {
if (textMssage.value!="close") {
webSocket.send(textMessage.value);
messagesTextarea.value +=" Send to Server ===> "+ textMessage.value +"\n";
textMessage.value="";
}else {
websocket.close();
}
}
function processClose(message) {
webSocket.send("Client disconnected......");
messagesTextarea.value +="Server Disconnected... "+"\n";
}
function processError(message) {
messagesTextarea.value +=" Error.... \n";
}
</script>
</body>
</html>
Controller 2:
package chat
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/testing")
class TestingController {
#OnOpen
public void handleOpen() {
System.out.println("Client is now connected.");
}
#OnMessage
public String handleMessage(String message) {
System.out.println("Client sent: " + message);
String replyMessage = "echo "+message;
System.out.println("Send to Client: " + replyMessage);
return replyMessage;
}
#OnClose
public void handeClose() {
System.out.println("Client is now disconnected.");
}
#OnError
public void handleError(Throwable t) {
t.printStackTrace();
}
}
With this as is when I run app
I get the following error in chrome:
WebSocket connection to 'ws://localhost:8080/chat/testing' failed: Error during WebSocket handshake: Unexpected response code: 404 index:37
WebSocket is already in CLOSING or CLOSED state.
and in textArea
Error....
Server Disconnected...
on ggts console I see:
Client sent: null
Send to Client: echo null
Initially I attempted controller this way:
package chat
class TestingController extends TestingEndpoint {
}
and in src/java/chat
package chat;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerEndpoint;
#ServerEndpoint("/testing")
class TestingEndpoint {
#OnOpen
public void handleOpen() {
System.out.println("Client is now connected.");
}
#OnMessage
public String handleMessage(String message) {
System.out.println("Client sent: " + message);
String replyMessage = "echo "+message;
System.out.println("Send to Client: " + replyMessage);
return replyMessage;
}
#OnClose
public void handeClose() {
System.out.println("Client is now disconnected.");
}
#OnError
public void handleError(Throwable t) {
t.printStackTrace();
}
}
This method produced same result except nothing in ggts console
Wondering if anyone has got javax.websocket to work in Grails..

ok got it working - was not that bad after all
here is the fix:
a few typos in the gsp :
index.gsp
<!DOCTYPE html>
<html>
<head>
<meta name="layout" content="main">
<g:set var="entityName" value="${message(code: 'admin.label', default: 'Admin')}" />
<title><g:message code="default.create.label" args="[entityName,BAH,BAH]" /></title>
</head>
<body>
<form>
<input id="textMessage" type="text">
<input type="button" value="send" onClick="sendMessage();">
</form>
<br>
<textarea id="messagesTextarea" rows="10" cols="50">
</textarea>
<script type="text/javascript">
var webSocket=new WebSocket("ws://localhost:8080/chat/annotated");
var messagesTextarea=document.getElementById("messagesTextarea");
webSocket.onopen=function(message) {processOpen(message);};
webSocket.onmessage=function(message) {processMessage(message);};
webSocket.onclose=function(message) {processClose(message);};
webSocket.onerror=function(message) {processError(message);};
function processOpen(message) {
messagesTextarea.value +=" Server Connect.... "+"\n";
}
function processMessage(message) {
messagesTextarea.value +=" Receive from Server ===> "+ message.data +"\n";
}
function sendMessage() {
if (textMessage.value!="close") {
webSocket.send(textMessage.value);
messagesTextarea.value +=" Send to Server ===> "+ textMessage.value +"\n";
textMessage.value="";
}else {
websocket.close();
}
}
function processClose(message) {
webSocket.send("Client disconnected......");
messagesTextarea.value +="Server Disconnected... "+"\n";
}
function processError(message) {
messagesTextarea.value +=" Error.... \n";
}
</script>
</body>
</html>
Now the actual fix for the end point, I stumbled across it from here:
https://tyrus.java.net/documentation/1.7/index/deployment.html
Example 3.2. Deployment of Annotated Endpoint Using ServerContainer
So the fix was to add a src/java/MyServletContextListenerAnnotated.java
package chat;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import javax.websocket.DeploymentException;
import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.server.ServerContainer;
import javax.websocket.server.ServerEndpoint;
#WebListener
#ServerEndpoint("/annotated")
public class MyServletContextListenerAnnotated implements ServletContextListener {
#Override
public void contextInitialized(ServletContextEvent servletContextEvent) {
final ServerContainer serverContainer = (ServerContainer) servletContextEvent.getServletContext()
.getAttribute("javax.websocket.server.ServerContainer");
try {
serverContainer.addEndpoint(MyServletContextListenerAnnotated.class);
} catch (DeploymentException e) {
e.printStackTrace();
}
}
/* #OnMessage
public String onMessage(String message) {
return message;
}
*/
#Override
public void contextDestroyed(ServletContextEvent servletContextEvent) {
}
#OnOpen
public void handleOpen() {
System.out.println("Client is now connected.");
}
#OnMessage
public String handleMessage(String message) {
System.out.println("Client sent: " + message);
String replyMessage = "echo "+message;
System.out.println("Send to Client: " + replyMessage);
return replyMessage;
}
#OnClose
public void handeClose() {
System.out.println("Client is now disconnected.");
}
#OnError
public void handleError(Throwable t) {
t.printStackTrace();
}
}
Since the endpoint in gsp already updated to use new endpoint the final touch was to add _Events.groovy to scripts:
import groovy.xml.StreamingMarkupBuilder
eventWebXmlEnd = {String tmpfile ->
def root = new XmlSlurper().parse(webXmlFile)
root.appendNode {
'listener' {
'listener-class' (
'chat.MyServletContextListenerAnnotated'
)
}
}
webXmlFile.text = new StreamingMarkupBuilder().bind {
mkp.declareNamespace(
"": "http://java.sun.com/xml/ns/javaee")
mkp.yield(root)
}
}
and booom there it is - server connected client send blah

Related

mvc signalr how to display all connected users

I need to build a chat using signalr and I am new in this.
So far I got only the chat by reading some others codes and tutorials and this is what I got:
on my ChatApp.Hubs I got the following code
public static class UserHandler
{
public static HashSet<string> ConnectedIds = new HashSet<string>();
}
public class ChatHub : Hub
{
public void Send(string name, string message)
{
// Call the addNewMessageToPage method to update clients.
Clients.All.addNewMessageToPage(name, message);
}
public override Task OnConnected()
{
UserHandler.ConnectedIds.Add(Context.ConnectionId);
return base.OnConnected();
}
public override Task OnDisconnected(bool stopCalled)
{
UserHandler.ConnectedIds.Remove(Context.ConnectionId);
return base.OnDisconnected(stopCalled);
}
}
and my view I copy past from a tutorial
#{
ViewBag.Title = "Chat";
}
<h2>Chat</h2>
<div class="container">
<input type="text" id="message" />
<input type="button" id="sendmessage" value="Send" />
<input type="hidden" id="displayname" />
<ul id="discussion">
</ul>
</div>
#section scripts {
<!--Script references. -->
<!--The jQuery library is required and is referenced by default in _Layout.cshtml. -->
<!--Reference the SignalR library. -->
<script src="~/Scripts/jquery.signalR-2.1.0.min.js"></script>
<!--Reference the autogenerated SignalR hub script. -->
<script src="~/signalr/hubs"></script>
<!--SignalR script to update the chat page and send messages.-->
<script>
$(function () {
// Reference the auto-generated proxy for the hub.
var chat = $.connection.chatHub;
// Create a function that the hub can call back to display messages.
chat.client.addNewMessageToPage = function (name, message) {
// Add the message to the page.
$('#discussion').append('<li><strong>' + htmlEncode(name)
+ '</strong>: ' + htmlEncode(message) + '</li>');
};
// Get the user name and store it to prepend to messages.
$('#displayname').val(prompt('Enter your name:', ''));
// Set initial focus to message input box.
$('#message').focus();
// Start the connection.
$.connection.hub.start().done(function () {
$('#sendmessage').click(function () {
// Call the Send method on the hub.
chat.server.send($('#displayname').val(), $('#message').val());
// Clear text box and reset focus for next comment.
$('#message').val('').focus();
});
});
});
// This optional function html-encodes messages for display in the page.
function htmlEncode(value) {
var encodedValue = $('<div />').text(value).html();
return encodedValue;
}
</script>
}
what I need now is to display all the connected users in the view
Appriciate your help
Thanks in advance
So, you pretty much either want to just store all 'Active' connections in some kind of database/storage or a static hashset/dictionary.
You save the ConnectionIds when the user connects and remove them when they disconnect :
Hub
public class ChatHub : Hub
{
static HashSet<string> CurrentConnections = new HashSet<string>();
public override Task OnConnected()
{
var id = Context.ConnectionId;
CurrentConnections.Add(id);
return base.OnConnected();
}
public override System.Threading.Tasks.Task OnDisconnected()
{
var connection = CurrentConnections.FirstOrDefault(x => x == Context.ConnectionId);
if (connection != null)
{
CurrentConnections.Remove(connection);
}
return base.OnDisconnected();
}
//return list of all active connections
public List<string> GetAllActiveConnections()
{
return CurrentConnections.ToList();
}
}
Client
I added a button and an unordered list.
HTML
<button id="show-all-connections">Show Connections</button>
<ul id="user-list">
</ul>
And added this javascript (using jQuery)
$("#show-all-connections").on("click", function () {
debugger;
chatHub.server.getAllActiveConnections().done(function (connections) {
$.map(connections, function (item) {
$("#user-list").append("<li>Connection ID : " + item + "</li>");
});
});
});
Hope this helps.
Update
In your scenario, I don't see any hooks into using a custom UserId Provider or anything, so you're going to have to ask the User for a User Name and save the Connection ID with that.
HTML
JavaScript
$("#add-connection").click(function () {
var name = $("#user-name").val();
if (name.length > 0) {
chatHub.server.connect(name);
}
else {
alert("Please enter your user name");
}
});
Hub
static List<Users> SignalRUsers = new List<Users>();
public void Connect(string userName)
{
var id = Context.ConnectionId;
if (SignalRUsers .Count(x => x.ConnectionId == id) == 0)
{
SignalRUsers .Add(new Users{ ConnectionId = id, UserName = userName });
}
}
public override System.Threading.Tasks.Task OnDisconnected()
{
var item = SignalRUsers.FirstOrDefault(x => x.ConnectionId == Context.ConnectionId);
if (item != null)
{
SignalRUsers.Remove(item);
}
return base.OnDisconnected();
}
Users.cs
public class Users
{
public string ConnectionId { get; set; }
public string UserName { get; set; }
}
This is psuedo code since I am not able to run this code at the moment. Hope it helps and gives you a clear enough direction.

Display a simple AngularDart component

I'am starting to learn Dart/AngularDart and i'am trying to display a simple component following the tutorial in https://angulardart.org/ , my problem is that i got a blank page nothing is displayed.
Here is my code:
web/nasiha.dart
import 'dart:html';
import 'package:angular/angular.dart';
import 'components/post/post.dart';
import 'dart:mirrors';
class MyAppModule extends Module {
MyAppModule() {
type(PostComponent);
}
}
void main() {
ngBootstrap(module: new MyAppModule());
}
web/nasiha.html
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="utf-8">
<title>Nasiha</title>
<link rel="stylesheet" href="css/nasiha.css">
</head>
<body>
<post></post>
<script src="packages/shadow_dom/shadow_dom.min.js"></script>
<script type="application/dart" src="nasiha.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
web/components/post/post.dart
import 'package:angular/angular.dart';
#NgComponent(
selector: 'post',
templateUrl:'components/post/post.html',
cssUrl: 'components/post/post.css',
publishAs: 'cmp_post'
)
class PostComponent {
String text= "This is a simple text to show";
String userName = "test";
DateTime date= new DateTime.now();
PostComponent(String text, String userName, DateTime date){
this.text = text;
this.userName = userName;
this.date = date;
}
String getText(){
return this.text;
}
void setText(String text){
this.text = text;
}
DateTime getDate(){
return this.date;
}
void setDate(DateTime date){
this.date = date;
}
String getUserName(){
return this.userName;
}
void setUserName(String userName){
this.userName = userName;
}
}
web/components/post/post.html
<div>
<p ng-model="cmp_post.post_text">
{{cmp_post.text}}
</p>
<div ng-model="cmp_post.post_date">
{{cmp_post.date}}
</div>
<div ng-model="cmp_post.post_username">
{{cmp_post.userName}}
</div>
</div>
You should execute pub upgrade from the context menu on pubspec.yaml.
The ng-model attributes in web/components/post/post.html are redundant.
PostComponent(String text, String userName, DateTime date){
this code is invalid.
Either you register a class in your module that can be injected to
the constructor or you use annotations to be able to inject primitive
types like String, int, double, ... (If you want to know how inject primitive types or using annotations for injection see How can I Dependency Inject based on type and name, with AngularDart?

How to trigger a function inside NgComponent from outside of the component?

I have the following component
#NgComponent(selector: 'foo',
template: '<div>foo component</div>')
class FooComponent {
void doSomething();
}
it's used as follows:
<html>
<head></head>
<body>
<foo ng-click="ctrl.doSomething()"></foo> // This is wrong
</body>
</html>
How do I actually execute a function inside an NgComponent?
Good question
What I come up with (probably not exactly what you are looking for):
#NgController(
selector: '[do-something]',
publishAs: 'ctrl'
)
class DoSomething {
FooComponent _foo;
DoSomething(this._foo);
void clickHandler(e) {
_foo.doSomething();
}
}
.
<foo do-something ng-click="ctrl.doSomething()"></foo>
Here is a one poor solution, but if there is no other solution, then you can use this.
EDIT: I updated this solution completely. With this example one can define what event component recognizes and to what function each event is attached.
html:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="utf-8">
<title>Foo</title>
<link rel="stylesheet" href="ok_comp.css">
</head>
<body>
<foo click="test()" doubleclick="test2()"></foo>
<foo click="test2()"></foo>
<script type="application/dart" src="ok_comp.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
comp.dart:
import 'dart:html';
import 'package:angular/angular.dart';
#NgComponent(
selector: 'foo',
template: '<div>foo</div>'
)
class FooComp extends NgAttachAware {
#NgAttr('click')
var click;
#NgAttr('doubleclick')
var doubleclick;
Element element;
var func;
FooComp(this.element){
}
attach(){
attachFunc("click", click);
attachFunc("doubleclick", doubleclick);
}
void attachFunc(String listener, String funcName){
switch (funcName) {
case 'test()':
func = test;
break;
case 'test2()':
func = test2;
break;
}
switch (listener) {
case 'click':
element.onClick.listen(func);
break;
case 'doubleclick':
element.onDoubleClick.listen(func);
break;
}
}
test(MouseEvent event){
print ("test");
}
test2(MouseEvent event){
print ("test2");
}
}
class MyAppModule extends Module {
MyAppModule() {
type(FooComp);
}
}
void main() {
ngBootstrap(module: new MyAppModule());
}
You can add an event listener to component. Here is an example:
html:
<foo></foo>
comp.dart:
#NgComponent(selector: 'foo',
template: '<div>foo component</div>')
class FooComponent {
FooComponent(Element elem){
elem.onClick.listen(doSomething);
}
void doSomething(MouseEvent event){
print("click");
}
}
This question keeps bothering me and I had to test it a little bit more. In the following example a component has multiple functions and multiple build-in ng-directives. You can define which functions are related to which ng-directives through component's attributes.
html:
<!DOCTYPE html>
<html ng-app>
<head>
<meta charset="utf-8">
<title>Foo</title>
<link rel="stylesheet" href="ok_comp.css">
</head>
<body>
<foo2 click="test" doubleclick="test2"></foo2>
<foo2 click="test2"></foo2>
<script type="application/dart" src="ok_comp.dart"></script>
<script src="packages/browser/dart.js"></script>
</body>
</html>
comp.dart:
import 'dart:html';
import 'package:angular/angular.dart';
#NgComponent(
selector: 'foo2',
template: '<div ng-click="cmp.ngClick()" ng-doubleclick="cmp.ngDoubleClick()">foo2</div>',
publishAs: 'cmp'
)
class Foo2Comp extends NgAttachAware {
#NgAttr('click')
var strClick;
#NgAttr('doubleclick')
var strDoubleclick;
var ngClick;
var ngDoubleClick;
Foo2Comp(){
}
attach(){
ngClick = redirectFunc(strClick);
ngDoubleClick = redirectFunc(strDoubleclick);
}
redirectFunc(String funcName){
var ng;
switch (funcName) {
case 'test':
ng = test;
break;
case 'test2':
ng = test2;
break;
default:
ng = empty;
break;
}
return ng;
}
empty(){
print ("empty");
}
test(){
print ("test");
}
test2(){
print ("test2");
}
}
class MyAppModule extends Module {
MyAppModule() {
type(Foo2Comp);
}
}
void main() {
ngBootstrap(module: new MyAppModule());
}

SignalR echo/negotiate not found?

Index.cshtml
#{
ViewBag.Title = "Index";
}
<script src="~/Scripts/jquery.signalR-2.0.0.min.js"></script>
<script>
$(function () {
var connection = $.connection('/echo');
connection.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
connection.start().done(function () {
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
});
});
</script>
<input type="text" id="msg" />
<input type="button" id="broadcast" value="broadcast" />
<ul id="messages">
</ul>
startup.cs
using Microsoft.Owin;
using Owin;
using UI;
namespace UI
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR();
}
}
}
MyConnection.cs
public class MyConnection : PersistentConnection
{
protected override Task OnConnected(IRequest request, string connectionId)
{
return Connection.Send(connectionId, "Welcome!");
}
protected override Task OnReceived(IRequest request, string connectionId, string data)
{
return Connection.Broadcast(data);
}
}
I m new to signalR. When I start the project I get following error:
http://localhost:49820/echo/negotiate?clientProtocol=1.3&_=1383403303981 404 (Not Found)
What is the reason of this and how can I fix it? I cant find any solution about this problem. (.net framework 4.5 and signalR 2.0)
I can not debug your code at the moment, but I think you should consider two possible problems.
1) You missed "$.connection.hub" in your start hub function. And when you call received method from server side to client side, you need to add 'connection.client.received'. It should be like below:
$(function () {
var connection = $.connection('/echo');
connection.client.received(function (data) {
$('#messages').append('<li>' + data + '</li>');
});
$.connection.hub.start().done(function () {
$("#broadcast").click(function () {
connection.send($('#msg').val());
});
});
});
2) You need to map your persistent connection. I believe in signalR 1.x should be something like:
RouteTable.Routes.MapConnection<MyConnection>("echo", "/echo");
But in SignalR 2.0 you need to do the following in your hub Startup class. Below is just an example.
public class Startup
{
public void Configuration(IAppBuilder app)
{
app.MapSignalR<MyConnection>("/echo");
}

Ajax jsf two values

I am working on a project where Administrator selects a movie from a list. Then the data of the movie are displayed in inputTexts, so the admin can change it and onblur with ajax updates the database.
I created a bean in order to select the right data and display them in the inputTexts.
Thats ok. Now, I dont know how to allow the inputText to refer to the second bean where i have the update queries..
UPDATED
The Select Bean.
package Beans;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Select {
Connection con;
Statement statement;
String query;
private List perInfoAll = new ArrayList();
public List getperInfoAll() {
int i = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "Bill", "1989");
statement = con.createStatement();
query = "SELECT NAME,SURNAME FROM AJAX";
ResultSet resultset = statement.executeQuery(query);
while (resultset.next()) {
perInfoAll.add(i, new Select.perInfo(resultset.getString(1), resultset.getString(2)));
i++;
}
} catch (Exception e) {
System.out.println("Error Data : " + e.getMessage());
}
return perInfoAll;
}
public class perInfo {
String NAME;
String SURNAME;
public perInfo(String NAME, String SURNAME) {
this.NAME = NAME;
this.SURNAME = SURNAME;
}
public String getNAME() {
return NAME;
}
public String getSURNAME() {
return SURNAME;
}
}
}
The Update Bean
package Beans;
import java.sql.*;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Update {
Statement statement;
Connection con;
String query1;
String query2;
ResultSet resultset1;
ResultSet resultset2;
String NewName;
String NewSurname;
public void setNewSurname(String NewSurname) {
this.NewSurname = NewSurname;
}
public void setNewName(String NewName) {
this.NewName = NewName;
}
public String getNewSurname() {
return NewSurname;
}
public String getNewName() {
return NewName;
}
public void DatabaseConnection(String NewName) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query1 = "UPDATE AJAX SET NAME = ('" + NewName + "')";
resultset1 = statement.executeQuery(query1);
resultset1.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit() {
DatabaseConnection(NewName);
return "ok";
}
public void DatabaseConnection1(String NewSurname) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query2 = "UPDATE AJAX SET SURNAME = ('" + NewSurname + "')";
resultset2 = statement.executeQuery(query2);
resultset2.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit1() {
DatabaseConnection1(NewSurname);
return "ok";
}
}
The index.xhtml
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" type="text/css" href="my.css" />
</h:head>
<h:body>
<h:form>
<h:inputText value="#{update.newName}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit}" />
</h:inputText>
<h:inputText value="#{update.newSurname}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit1}" />
</h:inputText>
</h:form>
</h:body>
So i want in index.xhtml to get the values from the select bean and when updated the value will sent to update bean
You should do something like this...
assign the inputText to a variable name in the bean class as -
private String myData;
//getters and setters.
public void updateData(ActionEvent e)
{
//put your query here to update to the database.
}
and in your web file do like this -
<h:inputText value="#{bean.myData}">
<a4j:support event="onblur" actionListener="#{bean.updateData}"/>
</h:inputText>
Show your list as you were showing, and after onblur it will directly update this value to the database by calling a function described above.
Hope it clears your doubt.

Resources