JetCracker

Life-time learner's blog

[Java] [Glassfish 3] Wrong character encoding in multipart servlet request

Hello!

It’s been a long time since I posted here, but I’m currently very busy with my study, work and projects.
Recently we had a problem with processing multipart HTTP requests in Java servlet. We are using Glassfish 3.1.1 as application server. The thing is despite of the fact that HTTP request had UTF-8 encoding, all string data actually were in ISO-8859-1 (a.k.a. ISO-LATIN-1).

I tried several different approaches to set encoding to UTF-8… until I came across the following: http://java.net/jira/browse/GLASSFISH-18516. As I understood, It says that there is a known issue in Glassfish 3.1.2 with incorrect interpretation of character encoding of multipart HTTP request parameters. Instead of UTF-8 it applies ISO-8859-1 ignoring settings in configuration files (web.xml, glassfish-web.xml) and in HTTP request. Turns out, this issue also affects Glassfish 3.1.1, which is used in our project.

A simple work around is to convert all request parameters from ISO to UTF manually.

public static String decode(String value, String charsetName) {
    Charset charset = Charset.forName(charsetName);
    if(value == null) {
        return null;
    }
    return new String(value.getBytes(charset));
}

This method converts the string to UTF-8. The example how to use it follows:

private String getValidParameter(HttpServletRequest request, String name) {
    String param = request.getParameter(name);
    return param == null ? "" : StringUtils.decode(param, "ISO-8859-1");
}

In the example above, StringUtils is my class with some static methods for working with strings.

It worked for me.
That’s all for now. 🙂

Have a nice day!

Advertisements

3 responses to “[Java] [Glassfish 3] Wrong character encoding in multipart servlet request

  1. Pingback: [Java Web] [QapTcha] How to add captcha to JSF page « JetCracker

  2. Valeriy Ovchinnikov October 29, 2013 at 17:02

    Or,
    Open project_name/source_packages/default_package/Filter.java and add to doFilter() method:
    request.setCharacterEncoding(“UTF-8”);
    response.setCharacterEncoding(“UTF-8”);

    • jetcracker October 29, 2013 at 18:14

      This is a more universal approach 🙂
      In my situation the problem reproduced only for multipart requests and in my project I had only one servlet that this type of requests. That’s why in my case my approach was easier (we didn’t have to create filters).

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: