So I’m redirecting my user using GET in a naive way:
response.sendRedirect("/path/index.jsp?type="+ e.getType()
+"&message="+ e.getMessage());
And this was working fine until I had to send messages, as actual text to be shown to users. The problem is if the message has non-ASCII characters in it. My .jsp files are encoded in UTF-8:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
So all non-ASCII characters in ‘message’ gets garbled. I don’t want to set my JVM default encoding to UTF-8, so how do I solve this? I tried to use
response.setCharacterEncoding("UTF-8");
on the Servlet before redirecting, but it doesn’t work. when I try to execute:
out.print(request.getCharacterEncoding());
on my .jsp file it prints ‘null’.
The
sendRedirect()method doesn’t encode the query string for you. You’ve to do it yourself.You might want to refactor the boilerplate to an utility method taking a
Mapor so.Note that I assume that the server is configured to decode the GET request URI using UTF-8 as well. You didn’t tell which one you’re using, but in case of for example Tomcat it’s a matter of adding
URIEncoding="UTF-8"attribute to the<Context>element.See also:
Unrelated to the concrete problem, the
language="java"is the default already, just omit it. ThecontentType="text/html; charset=UTF-8"is also the default already when using JSP withpageEncoding="UTF-8", just omit it. All you really need is<%@ page pageEncoding="UTF-8"%>. Note that this does effectively the same asresponse.setCharacterEncoding("UTF-8"), so that explains why it didn’t have effect. Therequest.getCharacterEncoding()only concerns the POST request body, not the GET request URI, so it is irrelevant in case of GET requests.