miércoles, 21 de marzo de 2007

Display multiline strings with ADF

Some time you will want to display Strings that contain carriage returns and/or new lines in a web application, and format the output to display such new line characters.

If you use components like OutputText or OutputFormatted alone, you will not see the new lines displayed.

I have created a "Converter" that can be used for this purpose. A "Converter "is a class that implements the javax.faces.Converter interface.

This class converts carriage returns and new lines into
tags just for the
sake of displaying a multilined text through components like af:OutputText or
af:OutpputFormatted in a web app.

To use this class you only need to include it in your project, and register it in the file "faces-config.xml" of your application.

Here a sample for the registration:

<converter>
<converter-id>mypackage.StringParagraphConverter</converter-id>
<converter-class>mypackage.StringParagraphConverter</converter-class>
</converter>

Note that the value of the attribute "converter" in the formatted component is the value that you enter as "converter-id", and not the name of the class itself.

In the sample, for convenience, I just respected the name of the class as the identifier.

Check out the code:

import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import javax.faces.convert.Converter;

public class StringParagraphConverter implements Converter{
public StringParagraphConverter() {
}

public Object getAsObject(FacesContext facesContext,
UIComponent uiComponent, String string) {
return string;
}

public String getAsString(FacesContext facesContext,
UIComponent uiComponent, Object object) {
if(object==null) return null;
String theString = (String) object;
theString = theString.replaceAll("[\n\r]","
");
theString = theString.replaceAll("[\r\n]","
");
theString = theString.replaceAll("[\n]","
");
theString = theString.replaceAll("[\r]","
");
return theString;
}
}