If you need the code of the pressed key then here is an example. It assign an event handler to the inText
input control. Here gets the code of the pressed key from the event object and call the onKeyPressed
method of the controller by <p:remoteCommand>
. The key code passed as a request parameter. The key code displayed in the outText
output control as a test.
The facelet:
<?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://xmlns.jcp.org/jsf/html"
xmlns:p="http://primefaces.org/ui"
xmlns:f="http://xmlns.jcp.org/jsf/core">
<h:head>
<title>Facelet Title</title>
<script type="text/javascript">
function jsKeyPressedHandler(event)
{
var kc = event.which || event.keyCode;
rc( [{ name : 'keyCode', value : Number( kc ) }] );
}
</script>
</h:head>
<h:body>
<h:form id="myForm">
<p:remoteCommand name="rc" update="outText" actionListener="#{myBean.onKeyPressed}" />
<p:inputText id="inText" value="#{myBean.text1}" onkeypress="jsKeyPressedHandler( event )"/>
<h:outputText id="outText" value="#{myBean.text2}"/>
</h:form>
</h:body>
</h:body>
</html>
The controller:
package x;
import java.io.Serializable;
import java.util.Map;
import javax.faces.context.FacesContext;
import javax.faces.view.ViewScoped;
import javax.inject.Named;
@Named( value = "myBean" )
@ViewScoped
public class MyBean implements Serializable
{
private String text1;
private String text2;
public String getText1() { return text1; }
public void setText1( String text1_ ) { text1 = text1_; }
public String getText2() { return text2; }
public void setText2( String text2_ ) { text2 = text2_; }
public void onKeyPressed()
{
Map<String,String> reqParams = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap();
String c = (String) reqParams.get( "keyCode" );
if ( text2 != null )
text2 += c;
else
text2 = c;
}
}