handling line breaks in primefaces textarea submitted value
I have a primefaces textarea. User simply enters multiple lines in it and submits the form. In my backing bean, value is split at line-breaks. Each line is validated. The valid lines are removed from the string and invalid lines are kept, and again sent to the user.
Split code:
StringTokenizer tokens=new StringTokenizer(value,"\n\r");
Re-fill value with invalid lines:
valueStrBldr.append(invalidLine).append("\n\r");
开发者_JAVA百科
The problem is that when value is reloaded to text area it has a lot of unwanted line breaks and empty lines. Does it have to do something with platform dependent line breaks?
When I remove \r , the problem is solved, but then the value is not split correctly -- I mean why inconsistency?
I suggest to use BufferedReader#readLine()
instead to read lines on linebreaks. This covers all possible platform specific linebreaks such as \r\n
, \r
and \n
without that you need to worry about (please note that \n\r
is not a valid linebreak sequence).
BufferedReader reader = new BufferedReader(new StringReader(value));
String line = null;
while ((line = reader.readLine()) != null) {
// ...
}
When writing lines, I suggest to use \r\n
. It should work fine in all clients (webbrowsers).
valueStrBldr.append(invalidLine).append("\r\n");
I think it should be '\r\n' (reversed order). If I remember it right \r is the end of a line, and \n is a new line.
anyway, try just printing out the ascii code of the input, and look at it. try recognizing the pattern. This sound brute force, but you will see that after 3-4 lines you have an idea of what is happening.
精彩评论