Pages

Monday, December 17, 2012

Solving character encoding issues in JSF

When developing a non-english webapp, you'll probably encounter some issues with special characters as "ñ", "á", etc, ie, when you input some of this characters in a text input field, you get those characters back from the server rendered as "Ö" or something similar.

The best approach is to use UTF-8 enconding all over the application so the response is not encoded differently depending of the place that handles that response.

This approach applies to:

  • Tomcat 6
  • Java 1.6
  • MyFaces 2.1.10
  • RichFaces 4.2.3-Final


The places to configure the encoding are:

  • server.xml in Tomcat

    It's neccesary to get Tomcat to encode GET parameters. This is done by adding the URIEncoding attribute to the HTTP connector.

          <Connector port="8080" protocol="HTTP/1.1" URIEncoding="UTF-8"
           .... />


  • Servlet Filter

    Implement a servlet filter to do the UTF-8 encoding of  the requests and responses:

    public class SetCharacterEncodingFilter implements Filter {
    
        protected String encoding = null;
        protected FilterConfig filterConfig = null;
        protected boolean ignore = true;
    
        /**
         * Take this filter out of service.
         */
        public void destroy() {
            this.encoding = null;
            this.filterConfig = null;
        }
    
        /**
         * Select and set (if specified) the character encoding to be used to
         * interpret request parameters for this request.
         * @param request The servlet request we are processing
         * @param result The servlet response we are creating
         * @param chain The filter chain we are processing
         * @exception IOException if an input/output error occurs
         * @exception ServletException if a servlet error occurs
         */
        public void doFilter(ServletRequest request, ServletResponse response,
                             FilterChain chain)
     throws IOException, ServletException {
    
            // Conditionally select and set the character encoding to be used
            if (ignore || (request.getCharacterEncoding() == null)) {
                String encoding = selectEncoding(request);
                if (encoding != null)
                    request.setCharacterEncoding(encoding);
            }
    
            response.setContentType("text/html; charset=UTF-8");
            response.setCharacterEncoding("UTF-8");
            // Pass control on to the next filter
            chain.doFilter(request, response);
        }
    
        /**
         * Place this filter into service.
         * @param filterConfig The filter configuration object
         */
        public void init(FilterConfig filterConfig) throws ServletException {
     this.filterConfig = filterConfig;
            this.encoding = filterConfig.getInitParameter("encoding");
            String value = filterConfig.getInitParameter("ignore");
            if (value == null)
                this.ignore = true;
            else if (value.equalsIgnoreCase("true"))
                this.ignore = true;
            else if (value.equalsIgnoreCase("yes"))
                this.ignore = true;
            else
                this.ignore = false;
        }
    
        /**
         * Select an appropriate character encoding to be used, based on the
         * characteristics of the current request and/or filter initialization
         * parameters.  If no character encoding should be set, return
         * null.
         * * The default implementation unconditionally returns the value configured
         * by the encoding initialization parameter for this
         * filter.
         *
         * @param request The servlet request we are processing
         */
        protected String selectEncoding(ServletRequest request) {
            return (this.encoding);
        }
    
    }
    
    

    Then you have to reference and map that filter in web.xml:

    <filter>
       <filter-name>SetCharacterEncodingFilter</filter-name>
       <filter-class>com.foo.filters.SetCharacterEncodingFilter</filter-class>
       <init-param>
          <param-name>encoding</param-name>
          <param-value>UTF-8</param-value>
       </init-param>
    </filter>
    <filter-mapping>
       <filter-name>SetCharacterEncodingFilter</filter-name>
       <url-pattern>*.xhtml</url-pattern>
    </filter-mapping>


    Here I mapped only xhtml files because I'm also encoding the responses to UTF-8, so mapping images and other resources as UTF-8 will probably generate an encoding error.

  • .xhtml Files

    One final step is neccesary to ensure we have coherent encoding all across the webapp.

    The first line in the xhtml files must be:
    <?xml version="1.0" encoding="UTF-8"?>

         Then, inside the head tag of the xhtml, add the following meta tag:
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    This is a lot less painful if you are using facelet templating technique; if that is the case, you'd only have to add the line mentioned above in the master template instead of in every .xhtml file.





Hope this helps, comment if you have any problem using this aproach.



47 comments:

  1. Briliant! Thank you very much. I spend two days for finding solution.

    ReplyDelete
  2. Thank you!!! You saved me!!

    ReplyDelete
  3. Perfect answer, because of this issue is trugled for 1 week.

    Thank you very much

    ReplyDelete
  4. Great...Thanks a lot ;-)

    ReplyDelete
  5. Thank you very much sir!
    Fast, clean and simple solution. It worked flaweless.

    ReplyDelete
  6. I found your blog while searching for the updates, I am happy to be here. Very useful content and also easily understandable providing..
    Believe me I did wrote an post about tutorials for beginners with reference of your blog. 




    Selenium training in bangalore
    Selenium training in Chennai
    Selenium training in Bangalore
    Selenium training in Pune
    Selenium Online training

    ReplyDelete
  7. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.
    Selenium Training in Electronic City

    ReplyDelete
  8. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging.

    Looking for Cloud Computing Training in Bangalore , learn from eTechno Soft Solutions Cloud Computing Training on online training and classroom training. Join today!

    ReplyDelete
  9. This excellent website certainly has all the info I needed concerning this subject and didn’t know who to ask.
    Tech geek

    ReplyDelete
  10. Inspiring writings and I greatly admired what you have to say , I hope you continue to provide new ideas for us all and greetings success always for you..Keep update more information..

    Selenium Training in Electronic City

    ReplyDelete
  11. Nice content very helpful, It has a very important point which should be noted down. All points mentioned and very well written. Keep Posting & writing such content

    AWS Online Training

    ReplyDelete
  12. UEFA BET , or UFABET, is a comprehensive online betting service website without any agents or agents. Which has a wide variety of games and sports to choose from Including many types of online casinos, UFABET can be considered as an online gambling site that most people prefer to use. Because with a website design that is easy to use and does not need to understand a lot In addition, this website also supports many languages, including Chinese, Hong Kong, Thai, English, so most users, both new and old, choose to switch to the service with สมัคร ufa Bet more. The best online gambling sites in Asia.

    ReplyDelete
  13. Internet slots (Slot Online) is actually the launch of a gambling machine. Slot machine As said before above Used to make electronic games called web based slots, due to the development era, people have left turned to gamble with one another by computers. Will draw slot games to make web based gambling games Via the web network system Which players are able to play through the slot plan or will perform Slots through the service provider's website Which online slots games are on hand in the kind of playing guidelines. It is similar to playing on a slot machine. Both realistic pictures as well as sounds are at the same time thrilling as they go to lounge in the casino ever.บาคาร่า
    ufa
    ufabet
    แทงบอล
    แทงบอล
    แทงบอล

    ReplyDelete
  14. Great post, really helpful with tons of great insight!
    Definitely a must-read for everyone
    by cloudi5 is the digital marketing company in coimbatore

    ReplyDelete
  15. Above all, write files from the hard drive, SSD, or Windows and you need Microsoft NTFS for Mac from Paragon Software. NTFS Mac Crack

    ReplyDelete
  16. Get more from all your devices. When you upgrade your Office 2010 download to Microsoft 365, you'll get familiar apps that are always up to date. Office 2010 Activation Crack

    ReplyDelete
  17. Thank you so much for sharing such amazing information, it’s really unique and valuable also. Ziyyara Edutech’s experienced tutors provide targeted support, helping you navigate through intricate subjects and conquer the complexities of the curriculum.
    Book A Free Demo Today visit private tuition classes for class 12

    ReplyDelete