How to pass Unicode characters as JSP/Servlet request.getParameter?

后端 未结 4 1287
情话喂你
情话喂你 2020-11-22 04:01

After a lot of trial and error I still can\'t figure out the problem. The JSP, servlet, and database are all set to accept UTF-8 encoding, but even still whenever I use requ

4条回答
  •  爱一瞬间的悲伤
    2020-11-22 04:28

    BalusC's answer is correct but I just want to add it is important (for POST method of course) that

    request.setCharacterEncoding("UTF-8");
    

    is called before you read any parameter. This is how reading parameter is implemented:

    @Override
    public String getParameter(String name) {
        if (!parametersParsed) {
            parseParameters();
        }
        return coyoteRequest.getParameters().getParameter(name);
    }
    

    As you can see there is a flag parametersParsed that is set when you read any parameter for the first time, parseParameters() method with parse all the request's parameters and set the encoding. Calling:

    request.setCharacterEncoding("UTF-8");
    

    after the parameters were parsed will have no effect! That is why some people are complaining that setting the request's encoding is not working. Most answers here suggest to use servlet filter and set the character encoding there. This is correct but also be aware that some security libraries can read request parameters before your filter (this was my case) so if your filter is executed after that the character encoding of request parameters are already set and setting UTF-8 or any other will have no effect.

提交回复
热议问题