gpt4 book ai didi

java - 使用过滤器向用户 session 添加 cookie

转载 作者:太空宇宙 更新时间:2023-11-04 08:29:18 26 4
gpt4 key购买 nike

更新:问题在于 MaxAge 使用的设置。将其设置为零将导致 cookie 被删除,因此它会显示在响应 header 中,但随后被删除并且不会显示在请求中。设置为-1,这样就不会持久存储

我正在一个过滤器上做一些工作,我希望它设置一个 cookie 来指示用户有资格参加调查,并且下次他返回网站时将显示一个调查弹出窗口。

我在日志中没有看到任何错误,但 cookie 从未被设置。

可以通过这种方式使用过滤器来添加 cookie 吗? HttpServletResponseWrapper 是否可以发挥作用?

这里的想法是,当用户访问该站点时,会检查 cookie 是否存在。如果不是,则会创建 cookie 并将其添加到响应中。当用户浏览站点时,将调用 cookie 检查方法以确保该给定用户的点击计数器不会增加。

cookie 检查方法永远不会看到 cookie。使用 Firefox 的 Web 开发人员插件,有问题的 cookie 不存在。

下面是过滤器类及其相关方法。

public class HitCounterFilter extends TemplateFilter {
public void doMainProcessing(ServletRequest pRequest, ServletResponse pResponse, FilterChain pChain) {
HttpServletRequest httpRequest = (HttpServletRequest) pRequest;
HttpServletResponse httpResponse = (HttpServletResponse) pResponse;

// prevent thread interference and memory consistency errors
synchronized (lock) {
int hitCounter = this.readFile(localFile);

// if user has not been counted
if (!this.checkForCookie(httpRequest, "gtgo_visitor")) {
this.writeFile(localFile, ++hitCounter);
this.createCookie(httpRequest, httpResponse, String.valueOf(hitCounter), "gtgo_visitor");
}
}
}

private void createCookie(HttpServletRequest pHttpRequest, HttpServletResponse pHttpResponse, String pCookieValue, String pCookieName) {
try {
Cookie cookie = new Cookie(pCookieName, pCookieValue);
URL url = new URL(pHttpRequest.getRequestURL().toString());
cookie.setDomain(url.getHost());
cookie.setPath(this.getCookiePath(pHttpRequest));
cookie.setComment("user is not eligible to take the survey this time");
cookie.setMaxAge(0);

pHttpResponse.addCookie(cookie);
} catch (MalformedURLException e) {
e.printStackTrace();
}
}

private boolean checkForCookie(HttpServletRequest pHttpRequest, String pCookieName) {
for (Cookie cookie : pHttpRequest.getCookies()) {
if (StringUtils.equalsIgnoreCase(cookie.getName(), pCookieName)) {
return true;
}
}
return false;
}
}

最佳答案

问题出在 MaxAge 使用的设置上。将其设置为零将导致 cookie 被删除,因此它会显示在响应 header 中,但随后被删除并且不会显示在请求中。将其设置为 -1,以便它不会被持久存储 - 只要 session 处于 Activity 状态,它就会存在( session 关闭后将被删除)

关于java - 使用过滤器向用户 session 添加 cookie,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7845137/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com