Unable to change charset from ISO-8859-1 to UTF-8 in glassfish 3.1

前端 未结 4 1351
北恋
北恋 2020-12-01 13:12

I am having problems to change the charset in my web application response from ISO-8859-1 (default) to UTF-8. I already added the VM option -Dfile.encoding=UTF-8

4条回答
  •  没有蜡笔的小新
    2020-12-01 14:15

    In order to define a standard response charset other than the default ISO-8859-1 for GlassFish (or Tomcat, or any other Servlet container) you will need to put a filter that calls response.setCharacterEncoding. Here is how:
    1. In your web.xml define the filter:

    
      Set Response Character Encoding
      com.omrispector.util.SetCharacterEncodingFilter
      
        encoding
        UTF-8
      
    
    
    
      Set Response Character Encoding
      /*
    
    

    2. Here is the filter implementation:

    package com.omrispector.util;
    
    import javax.servlet.*;
    import java.io.IOException;
    import java.nio.charset.Charset;
    import java.util.logging.Logger;
    
    /**
     * Created by Omri at 03/12/13 10:39
     * Sets the character encoding to be used for all sources returned
     * (Unless they override it later)
     * This is free for use - no license whatsoever.
     */
    public class SetCharacterEncodingFilter implements Filter {
    
      private String encoding = null;
      private boolean active = false;
    
      private static final Logger logger =
          Logger.getLogger(SetCharacterEncodingFilter.class.getName());
    
      /**
       * Take this filter out of service.
       */
      @Override
      public void destroy() {
        this.encoding = null;
      }
    
      /**
       * Select and set (if specified) the character encoding to be used to
       * interpret request parameters for this request.
       */
      @Override
      public void doFilter(ServletRequest request, ServletResponse response,
                           FilterChain chain)
          throws IOException, ServletException {
        if (active) response.setCharacterEncoding(encoding);
        chain.doFilter(request, response);
      }
    
      /**
       * Place this filter into service.
       */
      @Override
      public void init(FilterConfig filterConfig) throws ServletException {
        this.encoding = filterConfig.getInitParameter("encoding");
        try {
          Charset testCS = Charset.forName(this.encoding);
          this.active = true;
        } catch (Exception e) {
          this.active = false;
          logger.warning(encoding + " character set not supported ("+e.getMessage()+"). SetCharacterEncodingFilter de-activated.");
        }
      }
    }
    

提交回复
热议问题