February 1, 2009

Various small how-tos for the JSF beginner

A - Changing the locale of the current running session

1. Set up a managed session bean for storing the locale.

2. Intialize the locale from the browser settings:
public SessionBean() {
   FacesContext context = FacesContext.getCurrentInstance();
   HttpServletRequest request =
      (HttpServletRequest)context.getExternalContext().getRequest();
   sessionLocale = request.getLocale();

   if (!Locale.GERMAN.equals(sessionLocale) &&
       !Locale.ENGLISH.equals(sessionLocale)) {
      sessionLocale = Locale.ENGLISH;
   }
}
Make sure to fall back to your default locale in case of unknown locales.


3. Implement a simple getter and setter for the locale:
public Locale getLocale() {
   return sessionLocale;
}

public void setLocale(Locale sessionLocale) {
   this.sessionLocale = sessionLocale;
}
4. In every JSF page, ask for the current locale:
<f:view locale="#{sessionBean.locale}">

5. For switching the locale, add flag buttons or a user profile form.


B - Redirect to another place
void redirect(String url) {
   FacesContext context = FacesContext.getCurrentInstance();
   HttpServletResponse response = (HttpServletResponse)context.getExternalContext().getResponse();
   String path = context.getExternalContext().getRequestContextPath();
   response.sendRedirect(path + url);
}
The url given does not contain the application's context as prefix

C - Get a resource text for the current locale:
String getResourceText(String key) {
   String text = null;

   String bundleName = FacesContext.getCurrentInstance().getApplication().getMessageBundle();
   Locale loc = FacesContext.getCurrentInstance().getViewRoot().getLocale();
   ResourceBundle bundle = ResourceBundle.getBundle(bundleName, loc);

   try {
      text = bundle.getString(key);
   }
   catch (MissingResourceException e) {
      log.error(e);
      text = "! " + key + " !";
   }

   return text;
}

D - Get current session id
public String getSessionId() {
   FacesContext context = FacesContext.getCurrentInstance();
   return ((HttpSession)context.getExternalContext().getSession(false)).getId();
}

E - Get a request parameter
Object param = FacesContext.getCurrentInstance().getExternalContext().getRequestParameterMap().get("theParam");

F - Clear input of text fields and selected drop-down-lists
public void clearFields() {
   UIViewRoot uiRoot = FacesContext.getCurrentInstance().getViewRoot();
   recurseChildren(uiRoot);
}

protected void recurseChildren(UIComponentBase comp) {
   for (int i = 0; i < comp.getChildren().size(); i++) {
      UIComponentBase child = (UIComponentBase)comp.getChildren().get(i);
      recurseChildren(child);
   }

   if (comp instanceof HtmlInputText || comp instanceof HtmlInputTextarea || comp instanceof HtmlSelectOneMenu) {
      ((UIInput)comp).setValue("");
   }
}

G - Clean up expired sessions

1. Write a session listener:
public class CleanupListener implements HttpSessionListener {
   public void sessionCreated(HttpSessionEvent event) {
   }

   public void sessionDestroyed(HttpSessionEvent event) { 
      // clean up right here ... 
   }
}
2. Register the listener in the web.xml:
<listener>
   <listener-class>
      the.full.package.name.CleanupListener
   </listener-class>
</listener>

H - Fix the character encoding
If you get wrong page encodings for JSF post requests although you specified the content in every single page, setting up a servlet filter helps. Example to force UTF-8:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) {
   response.setCharacterEncoding("UTF-8");
   request.setCharacterEncoding("UTF-8");

No comments:

Post a Comment