Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

request.getQueryString() seems to need some encoding

I have some problem with UTF-8. My client (realized in GWT) make a request to my servlet, with some parametres in the URL, as follow:

http://localhost:8080/servlet?param=value 

When in the servlet I retrieve the URL, I have some problem with UTF-8 characters. I use this code:

protected void service(HttpServletRequest request, HttpServletResponse response)                      throws ServletException, IOException {          request.setCharacterEncoding("UTF-8");          String reqUrl = request.getRequestURL().toString();          String queryString = request.getQueryString();         System.out.println("Request: "+reqUrl + "?" + queryString);         ... 

So, if I call this url:

http://localhost:8080/servlet?param=così 

the result is like this:

Request: http://localhost:8080/servlet?param=cos%C3%AC 

What can I do to set up properly the character encoding?

like image 697
Gabriele Avatar asked Jun 12 '10 16:06

Gabriele


1 Answers

From the HttpServletRequest#getQueryString() javadoc:

Returns: a String containing the query string or null if the URL contains no query string. The value is not decoded by the container.

Note the last statement. So you need to URL-decode it youself using java.net.URLDecoder.

String queryString = URLDecoder.decode(request.getQueryString(), "UTF-8"); 

However, the normal way to gather parameters is just using HttpServletRequest#getParameter().

String param = request.getParameter("param"); // così 

The servletcontainer has already URL-decoded it for you then if you have configured it to use the correct encoding. The request.setCharacterEncoding() has only effect on the request body (POST) not on the request URI (GET). Also see Mirage's answer.

like image 199
BalusC Avatar answered Sep 21 '22 00:09

BalusC