0

I have a filter where I'm setting request.setCharacterEncoding("UTF-8") after fetching the parameters, for which the encoding is not set. In the process method I'm just checking if request contains any special chars which are removed.

public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    getParams(request);
    chain.doFilter(new RequestWrapper((HttpServletRequest) request), response);
}

private void getParams(ServletRequest request)
{

    HttpServletRequest httpRequest = (HttpServletRequest) request;
    Map paramMap = httpRequest.getParameterMap();

    Set entrySet = paramMap.entrySet();

    for (Iterator iterator = entrySet.iterator(); iterator.hasNext();)
    {
        Map.Entry entry = (Map.Entry) iterator.next();  

        String s = process(entry.getValue().toString());
        //entry.setValue(s);

    }
}

In the givencode I'm setting CharacterEncoding in the next filter in the chain.

 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
    request.setCharacterEncoding("UTF-8");
    chain.doFilter(request, response);
}

However, if I'm setting it in first filter before fetching parameters its working fine.

So is it necessary to set CharacterEncoding before fetching the params. I'm not clear with how things are working.

Bala
  • 11
  • 2
  • @BalusC the question that i have asked is the reason why setCharacterEncoding doesnt work after fetching params – Bala Apr 30 '18 at 13:28

1 Answers1

0

By default, if the encoding is not specified into the HTTP request, the server considers that the encoding is ISO-8859-1 (latin 1). This is the case at least for Tomcat and JBoss which embedding Tomcat as a web container.

If you call the setCharacterEncoding method before retrieving the request parameters you override this default behavior so it works as you expect.

Conversely, if you call the setCharacterEncoding method after retrieving the request parameters, they will be retrieved using the default ISO-8859-1 encoding. Next you override it but it's too late.

See this post for more details about UTF-8 encoding in webapps : How to get UTF-8 working in Java webapps?

Sébastien Helbert
  • 2,185
  • 13
  • 22
  • I'm using JBoss – Bala Apr 26 '18 at 06:13
  • 1
    JBoss web container is Tomcat (tomcat is embedded) – Sébastien Helbert Apr 26 '18 at 06:27
  • Thanks @Sebastien, but the document says "The setContentType or setLocale method must be called before getWriter for the charset to affect the construction of the writer.". However, in my example I'm using it on filter and checking the params. – Bala Apr 26 '18 at 06:46