UtF-8 format not working in servlet for tomcat ser

2019-09-21 14:48发布

问题:

I have a Java Servlet which accepts data from HTML through ajax javascript. Html receives hindi text from user and sends it through ajax into a servlet. I have specified UTF-8 format everywhere but it is not working.

I have set request and response encoding as utf-8 , still not working. The server is Tomcat.

If anyone can help.

回答1:

Follow the following steps to configure your Tomcat to serve your UTF-8 pages correctly either this is Persian, Arabic or any language that is written from right to left:

(1) Edit your server.xml as following

2) CharsetFilter force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:

package charsetFilter.classes;

 import java.io.IOException;
 import javax.servlet.Filter;
 import javax.servlet.FilterChain;
 import javax.servlet.FilterConfig;
 import javax.servlet.ServletException;
 import javax.servlet.ServletRequest;
 import javax.servlet.ServletResponse;

public class CharsetFilter implements Filter{
    private String encoding;

    public void init(FilterConfig config) throws ServletException{
            encoding = config.getInitParameter("requestEncoding");
            if( encoding==null ) encoding="UTF-8";
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain       next)
    throws IOException, ServletException{           
            if(null == request.getCharacterEncoding())
            request.setCharacterEncoding(encoding);             
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");
            next.doFilter(request, response);
    }

        public void destroy(){}
}   

This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8. The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application.

3) Then add this filter to the web.xml like:

CharsetFilter charsetFilter.classes.CharsetFilter requestEncoding UTF-8

<filter-mapping>
        <filter-name>CharsetFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>

Then write your servlet as:

request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.setCharacterEncoding("UTF-8");

and use whatever language you want to use in your servlet.

You can use this for getting parameters:

String input = new String(request.getParameter("foo").getBytes("iso-8859-1"), "utf-8");

Cheers!!