Skip to content

Instantly share code, notes, and snippets.

@zonia3000
Last active August 23, 2016 07:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zonia3000/012c80542ee07697bec4 to your computer and use it in GitHub Desktop.
Save zonia3000/012c80542ee07697bec4 to your computer and use it in GitHub Desktop.
Various JSF tips

Various JSF tips

Get named bean by EL from FacesContext

ELContext elCtx = FacesContext.getCurrentInstance().getELContext();
MyBean bean = (MyBean) elCtx.getELResolver().getValue(elCtx, null, "myBean");

Send custom AJAX error response:

FacesContext ctx = FacesContext.getCurrentInstance();
PartialResponseWriter writer = ctx.getPartialViewContext().getPartialResponseWriter();

writer.startDocument();

writer.startError(errorName);
writer.write(errorMessage);
writer.endError();

writer.endDocument();

ctx.renderResponse();
ctx.responseComplete();

h:inputText validation

<h:inputText id="myinput" validator="#{myBean.validateMyInput}"
<h:message for="myinput" />
public void validateMyInput(FacesContext context, UIComponent inputComponent, Object value) {
  // ...
  if(!valid) {
    throw new ValidatorException(new FacesMessage("your message"));
  }
}

JSF error messages

FacesContext.getCurrentInstance().addMessage("main:password", new FacesMessage("Wrong username or password!"));

Get JSF Version

FacesContext.class.getPackage().getImplementationVersion();

Source: http://stackoverflow.com/a/13125869/771431

CSS and Resources

src: url("#{resource['fonts:glyphicons-halflings-regular.eot']}");

Conditional validate required

Use case: validate required only when pressing "Sumbit" button.

<h:inputText value="#{myBean.myValue}" required="#{param['validateRequired']}" />

<h:commandLink action="#{myBean.submitValue()}">
  Sumbit value
  <f:param name="validateRequired" value="true" />
</h:commandLink>

Add loading animation to each AJAX call

$(document).ready(function () {

  jsf.ajax.addOnEvent(function (data) {
      switch (data.status) {
          case "begin":
              $('.loading').removeClass('hide');
              break;
          case "complete":
              $('.loading').addClass('hide');
              break;
      }
  });

});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment