Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
632 views
in Technique[技术] by (71.8m points)

servlets - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...