Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UTF-8 encoding a servlet form submission with Tomcat

I'm attempting to post a simple form that includes unicode characters to a servlet action. On Jetty, everything works without a snag. On a Tomcat server, utf-8 characters get mangled.

The simplest case I've got:

Form:

<form action="action" method="post">
  <input type="text" name="data" value="It’s fine">`
</form>`

Action:

class MyAction extends ActionSupport {   
  public void setData(String data) {
    // data is already mangled here in Tomcat
  } 
}
  • I've got URIEncoding="UTF-8" on <Connector> in server.xml
  • The first filter on the action calls request.setCharacterEncoding("UTF-8");
  • The content type of the page that contains the form is "text/html; charset=UTF-8"
  • Adding "accept-charset" to the form makes no difference

The only two ways I can make it work are to use Jetty or to switch it to method="get". Both of those cause the characters to come through without a problem.

like image 958
Parker Avatar asked Dec 05 '11 20:12

Parker


1 Answers

I've got URIEncoding="UTF-8" on <Connector> in server.xml

That's only relevant for GET requests.


The first filter on the action calls request.setCharacterEncoding("UTF-8");

Fine, that should apply on POST requests. You only need to make sure that if you haven't called getParameter(), getReader(), getInputStream() or anything else which would trigger parsing the request body before calling setCharacterEncoding().


The content type of the page that contains the form is "text/html; charset=UTF-8"

How exactly are you setting it? If done in a <meta>, then you need to understand that this is ignored by the browser when the page is served over HTTP and the HTTP Content-Type response header is present. The average webserver namely already sets it by default. The <meta> content type will then only be used when the page is saved to local disk and viewed from there.

To set the response header charset properly, add the following to top of your JSP:

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

This will by the way also tell the server to send the response in the given charset.


Adding "accept-charset" to the form makes no difference

It only makes difference in MSIE, but even then it is using it wrongly. The whole attribute is worthless anyway. Forget it.

See also:

  • Unicode - How to get the characters right?
like image 102
BalusC Avatar answered Nov 07 '22 23:11

BalusC