Hoffmann
Hoffmann

Reputation: 14729

Servlet response.sendRedirect encoding problems

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'.

Upvotes: 3

Views: 11356

Answers (2)

Sudhakar
Sudhakar

Reputation: 3180

Thanks you ... When i am using the response.sendRedirect("/path/index.jsp?type=" + URLEncoder.encode(e.getType(), "UTF-8"), My problem got fixed...

When we are using the response.sendRedirect(): We should encode the URL by the URLEncoder.encode() function then only.. it will be encoded correctly..

Thanks again...

Upvotes: 0

BalusC
BalusC

Reputation: 1108842

The sendRedirect() method doesn't encode the query string for you. You've to do it yourself.

response.sendRedirect("/path/index.jsp?type=" + URLEncoder.encode(e.getType(), "UTF-8")
    + "&message=" + URLEncoder.encode(e.getMessage(), "UTF-8"));

You might want to refactor the boilerplate to an utility method taking a Map or 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. The contentType="text/html; charset=UTF-8" is also the default already when using JSP with pageEncoding="UTF-8", just omit it. All you really need is <%@ page pageEncoding="UTF-8"%>. Note that this does effectively the same as response.setCharacterEncoding("UTF-8"), so that explains why it didn't have effect. The request.getCharacterEncoding() only concerns the POST request body, not the GET request URI, so it is irrelevant in case of GET requests.

Upvotes: 9

Related Questions