• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

Question on ServletResponse CharacterEncoding

 
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I have a question about sending a text response from a servlet. One way to do this would be



Now I was reading about the PrintWriter you get with response.getWriter() to send text data. I think it would look something like this:



I am not sure a) what length I would need to set for ContentLength, and b) I wonder if the Writer automatically uses the encoding I set with setCharacterEncoding(). It seems to me the method using the OutputStream is safer than the Writer, because you explicitely state the encoding you want to use, and the length of the content..
 
D. Ogranos
Ranch Hand
Posts: 214
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
I can at least answer my second question now. The PrintWriter obtained with getWriter() has no methods to set an encoding, and uses the default platform encoding (which is defined in java.nio.charsets.Charset.defaultCharset() and apparently cannot be easily changed either). So it seems that its only safe to use getWriter() if you're sure that the text to write doesn't contain any special characters.

I still don't see what value I should use with setContentLength() however.
 
Ranch Hand
Posts: 282
Eclipse IDE PHP Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
It automatically sets the Content-Length header to whatever the size of your output is. You don't have to manully set it as far as I know.

I was going to say that you can set the encoding with PrintWriter...but you can only do this in the constructor, which you obviously never call, since you get the PrintWriter by calling getWriter().

EDIT: Also, you don't need to call flush()...it flushes the response automatically.
 
reply
    Bookmark Topic Watch Topic
  • New Topic