1

我正在为我公司的所有内部应用程序创建一个 facelets 模板。它的外观基于用户选择的皮肤(如 gmail 主题)。

将用户喜欢的皮肤存储在 cookie 中是有意义的。

我的“用户首选项”WAR 可以看到这个 cookie。但是,我的其他应用程序无法找到 cookie。它们与用户首选项 WAR 位于同一域/子域中。

这有什么原因吗?

这是我的 bean,用于创建/查找首选皮肤。所有项目都使用相同的文件:

// BackingBeanBase is just a class with convenience methods. Doesn't 
// really affect anything here.
public class UserSkinBean extends BackingBeanBase {

    private final static String SKIN_COOKIE_NAME = "preferredSkin";

    private final static String DEFAULT_SKIN_NAME = "classic";


    /**
     * Get the name of the user's preferred skin. If this value wasn't set previously, 
     * it will return a default value.
     * 
     * @return
     */
    public String getSkinName() {

        Cookie skinNameCookie = findSkinCookie();

        if (skinNameCookie == null) {
            skinNameCookie = initializeSkinNameCookie(DEFAULT_SKIN_NAME);
            addCookie(skinNameCookie);
        }

        return skinNameCookie.getValue();

    }


    /**
     * Set the skin to the given name. Must be the name of a valid richFaces skin.
     *     
     * @param skinName
     */
    public void setSkinName(String skinName) {

        if (skinName == null) {
            skinName = DEFAULT_SKIN_NAME;
        }

        Cookie skinNameCookie = findSkinCookie();

        if (skinNameCookie == null) {
            skinNameCookie = initializeSkinNameCookie(skinName);
        }
        else {
            skinNameCookie.setValue(skinName);    
        }

        addCookie(skinNameCookie);
    }

    private void addCookie(Cookie skinNameCookie) {
        ((HttpServletResponse)getFacesContext().getExternalContext().getResponse()).addCookie(skinNameCookie);
    }

    private Cookie initializeSkinNameCookie(String skinName) {

        Cookie ret = new Cookie(SKIN_COOKIE_NAME, skinName);
        ret.setComment("The purpose of this cookie is to hold the name of the user's preferred richFaces skin.");

        //set the max age to one year.
        ret.setMaxAge(60 * 60 * 24 * 365);
        ret.setPath("/");
        return ret;
    }


    private Cookie findSkinCookie() {
        Cookie[] cookies = ((HttpServletRequest)getFacesContext().getExternalContext().getRequest()).getCookies();

        Cookie ret = null;
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals(SKIN_COOKIE_NAME)) {
                ret = cookie;
                break;
            }
        }

        return ret;
    }
}

谁能看到我做错了什么?

更新:我已经把它缩小了一点......它在 FF 中运行良好,但 IE 仍然不喜欢它(当然)。

谢谢,扎克

4

2 回答 2

0

我找到了解决方案。

我只是在客户端使用 javascript 来创建 cookie。

这工作得很好。

于 2009-09-17T20:57:36.397 回答
0

我认为您需要将域/子域分配给 cookie。

像,(注意域应该以点开头)

ret.setDomain(".test.com");
ret.setDomain(".test.co.uk");

http://www.apl.jhu.edu/~hall/java/Servlet-Tutorial/Servlet-Tutorial-Cookies.html

于 2009-08-25T13:54:33.500 回答