Sunday, December 16, 2012

Reading and Decoding Browser Cookie Content in ADF


Below written Java code gets content of cookie from browser and decodes its content. 'UTF-8' encoding standard being used in below code. In some cases, you might need to choose different encoding standard, if you are storing native content in Cookie.

************************************************************************
import java.net.URLDecoder;
import javax.servlet.http.HttpServletRequest;
import javax.faces.context.FacesContext;
import javax.servlet.http.Cookie;


private void readLocaleCookie() {
        FacesContext ctx = FacesContext.getCurrentInstance();
        if (ctx != null) {
            HttpServletRequest request =
                (HttpServletRequest)ctx.getExternalContext().getRequest();
            if (request != null) {
                Cookie[] cookiesArray = request.getCookies();
                if (cookiesArray == null) {
                    return;
                }
                for (int i = 0; i < cookiesArray.length; i++) {
                if("COUNTRY_LOCALE".equals(cookiesArray[i].getName())){
                        try {
                            String cookieVal =
                            URLDecoder.decode(cookiesArray[i].getValue(),"UTF-8");
                            int indexof_ = cookieVal.indexOf("-");
                         
                            if(indexof_ > 0){
                                 setCountry = cookieVal.substring(0, indexof_);

                                 setLanguage = cookieVal.substring(indexof_+1, cookieVal.length());
                            }                        } catch (UnsupportedEncodingException uee) {
                            uee.printStackTrace();
                            } catch(Exception e){
                                e.printStackTrace();
                            }
                    }
                }
            }
        }
    }

**************************************************************************

Content of Cookie before decode:


After decode :

No comments:

Post a Comment

Provide your thoughts !