1

I have a property which can possibly contain \n characters. I would like to check in the rendered attribute of a JSF component if the property contains \n and if so, then don't render the component. How can I achieve this?

BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
M.M.RAM KUMAR
  • 115
  • 1
  • 2
  • 10
  • 1
    What's the functional requirement for which you thought that this is the right solution? What exactly do you want to do with this information? – BalusC Nov 15 '13 at 13:12
  • Okay, I clarified the question. How exactly does your current attempt fail? Seems it should work fine. Still, it would be interesting to know why exactly you don't want to render. I can't think of real world appliances for this check so perhaps you're still looking in the wrong direction for the solution. – BalusC Nov 15 '13 at 13:20
  • its not working. its giving a null pointer exception error.. – M.M.RAM KUMAR Nov 15 '13 at 13:23
  • Apparently `#{arg.csops}` is `null`. Wouldn't it make sense to just check `not empty arg.csops` beforehand? – BalusC Nov 15 '13 at 13:25
  • actually the values is saved as null in database, but its coming as "\n\n" value in the service side. – M.M.RAM KUMAR Nov 15 '13 at 13:26
  • Ah, you're redisplaying input retrieved from a ` – BalusC Nov 15 '13 at 13:28

1 Answers1

1

actually the values is saved as null in database, but its coming as "\n\n" value in the service side.

Provided that you mean that the \n represents the sole value, then you can use fn:trim() for that.

<h:outputText value="#{bean.value}" rendered="#{not empty fn:trim(bean.value)}" />

Alternatively, create a converter which immediately trims the submitted value before the model get polluted with unwanted characters:

<h:inputTextarea value="#{bean.value}" converter="trimConverter" />
@FacesConverter("trimConverter")
public class TrimConverter implements Converter {

    @Override
    public Object getAsObject(FacesContext context, UIComponent component, String submittedValue) {
        String trimmed = (submittedValue != null) ? submittedValue.trim() : null;
        return (trimmed == null || trimmed.isEmpty()) ? null : trimmed;
    }

    @Override
    public String getAsString(FacesContext context, UIComponent component, Object modelValue) {
        return (modelValue != null) ? modelValue.toString() : "";
    }

}

and then just do

<h:outputText value="#{bean.value}" rendered="#{not empty bean.value}" />

By the way, in the comments you specified escape="false". If this input is coming from an enduser via <textarea>, be aware that you're opening a huge XSS attack hole here. See also How to implement a possibility for user to post some html-formatted data in a safe way?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555