使用cookie发送随机令牌

时间:2015-09-26 11:01:19

标签: javascript jsf cookies

托管bean:

@Named
@ViewScoped
public class Bean implements Serializable {

    private static final long serialVersionUID = 1L;

    public Bean() {}

    @PostConstruct
    public void init() {
        Cookie cookie = new Cookie("token", UUID.randomUUID().toString());
        cookie.setMaxAge(-1);
        ((HttpServletResponse) FacesContext.getCurrentInstance().getExternalContext().getResponse()).addCookie(cookie);
    }
}

名为token的Cookie以@PostConstruct方法添加到响应中。

JavaScript试图通过以下方式访问此cookie。

<h:head>
    <script type="text/javascript">
        var cookie = getCookie("token");
        console.log(cookie);

        function getCookie(name) {
            var matched = document.cookie.match(RegExp(name + "=.[^;]*"));

            if (matched) {
                return matched[0].split('=')[1];
            }

            return false;
        }
    </script>
</h:head>

<h:body>
    <h:form>
        #{bean}
    <h:form>
</h:body>

除非在不同的标签和/或窗口中几乎同时打开相同的页面,否则它会正常工作,当按住 ctrl 键多次单击与页面对应的链接时令牌在不同的标签之间共享,预计在标签和/或窗口之间是唯一的。

使用<f:event type="preRenderView" listener="#{bean.init}"><f:viewAction action="#{bean.init}">或Servlet文件管理器稍早设置cookie没有任何区别。

如果经常请求并在不同的标签和/或窗口中打开同一页面,如何确保cookie值始终根据托管bean中的新生成值而不会发生冲突?

0 个答案:

没有答案
相关问题