Sunday, January 13, 2008

Pesky URLEncoder, JSP and UTF-8

Seems like request.getParameter in JSP doesn't like dealing with UTF-8 encoded strings much. Here's what I did to solve it:


Call from Java:
sURL += "?myparam="+URLEncoder.encode(sMyUTF8String, "UTF-8");



Necessary Code in JSP:
<%@ page contentType='text/html; charset=UTF-8' %>

request.setCharacterEncoding("UTF-8");
String sMyParam = new String(request.getParameter("myparam").getBytes("ISO8859_1"),"UTF8");



2 comments:

  1. I just had a similar problem. This is what I found out:

    It looks like you called request.setCharacterEncoding("UTF-8");
    too late (i.e. after doing a request.getParameter() call).

    Simply implement a ServletFilter which sets the characterEncoding of the Request and assure that this Filter is the first Filter which gets called (the first filter-mapping inside web.xml). If you implement a Filter you also do not have to set the characterEncoding in every single JSP, which saves a lot of coding...

    Regards,
    Stephan

    ReplyDelete
  2. i like the idea. cheers!

    ReplyDelete