JDev

jstl, javaAugust 31, 2006 7:50 pm

There is a problem with using JSTL to show text data that was previously saved from a textarea. If you show such text data in a table, the line-breaks from the textarea will be ignored and the text will be hard to read. A possible solution is to use a Java bean to process such data and replace line-breaks with BR tags before showing it on the page. Such a bean may look as follows:

package beans;
public class HTMLBreaker {
   
    private String text;  
    public HTMLBreaker() {               
    } 
   
    private  String insertBreaks(String text){      
        int len = text.length();      
        StringBuffer sb = new StringBuffer(len+16);          
        for(int i=0; i<text.length();i++){       
            if(text.charAt(i)==’\n’)           
                sb.append("<br>");           
            else       
                sb.append(text.charAt(i));   
        }           
        return sb.toString();       
    }   
   
   
    public String getText() {
        return text;
    }

    public void setText(String string) {
         text="";
        if(string != null)
            text = insertBreaks(string);         
    }
}

 

Then, on a JSP page create  the bean instance:

    <jsp:useBean id=’hbreaker’ class=’beans.HTMLBreaker’>

Set the bean property with the value of a database field: 

     <c:set target=’${hbreaker}’ property=’text’ value=’${row.text}’/>

Display the modified value of the bean property on the page:  

   <jsp:getProperty name=’hbreaker’ property=’text’/>          

If you use the JSTL c:out tag:

<c:out value=’${hbreaker.text}’/>

the BR tags surrounding symbols will be replaced with HTML characters, and show up as such on the screen.                                       

Don’t forget to close the bean tag:

  </jsp:useBean> 

A couple of other solutions using the JSTL fn:replace function and the Jakarta String Tag Library are offered at this weblog.

 

Code, jstl 2:03 pm

This web page has a concise description of how to set and access java bean properties from JSTL.

Briefly, to initialize a bean and set its properties, use the following example:

<jsp:useBean id=’beanIdclass=’className’>
    <c:set target=’${beanId}’ property=’propName’ value=’${someValue}’/>
</jsp:useBean>

To get a bean property value:

    <c:out value=’${beanId.propName}’/>