Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
235 views
Welcome To Ask or Share your Answers For Others

1 Answer

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...