Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java String Encoding to UTF-8

I have some HTML code that I store in a Java.lang.String variable. I write that variable to a file and set the encoding to UTF-8 when writing the contents of the string variable to the file on the filesystem. I open up that file and everything looks great e.g. → shows up as a right arrow.

However, if the same String (containing the same content) is used by a jsp page to render content in a browser, characters such as → show up as a question mark (?)

When storing content in the String variable, I make sure that I use:

String myStr = new String(bytes[], charset)  

instead of just:

String myStr = "<html><head/><body>&rarr;</body></html>";

Can someone please tell me why the String content gets written to the filesystem perfectly but does not render in the jsp/browser?

Thanks.

like image 902
m_a_khan Avatar asked Feb 05 '26 06:02

m_a_khan


2 Answers

but does not render in the jsp/browser?

You need to set the response encoding as well. In a JSP you can do this using

<%@ page pageEncoding="UTF-8" %>

This has actually the same effect as setting the following meta tag in HTML <head>:

<meta http-equiv="content-type" content="text/html; charset=utf-8">
like image 115
BalusC Avatar answered Feb 08 '26 03:02

BalusC


Possibilities:

  1. The browser does not support UTF-8
  2. You don't have Content-Type: text/html; charset=utf-8 in your HTTP Headers.
like image 43
Dylan Lacey Avatar answered Feb 08 '26 03:02

Dylan Lacey