我正在使用 cookie。当您第一次打开页面时,我像这样设置 cookie
public class SessionTimeoutFilter implements Filter {
public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain)
throws IOException, ServletException {
Object isRegistered = session.getAttribute("logedin");
if (isRegistered != null) {
String isRegisteredUser = isRegistered.toString();
if (isRegisteredUser.equalsIgnoreCase(("1"))) {
sessionID = UUID.randomUUID().toString();
session.setMaxInactiveInterval(240); //4min
Cookie userCookie = getCookie(httpServletRequest, "userCookie");
if (userCookie != null) {
//Value not setting here
Cookie loginUserCookie = new Cookie("userCookie", "loginUser");
httpServletResponse.addCookie(loginUserCookie);
}
filterChain.doFilter(httpServletRequest, httpServletResponse);
}
} else {
sessionID = httpServletRequest.getRequestedSessionId();
sessionValid = httpServletRequest.isRequestedSessionIdValid();
//User open his browser
if (sessionID == null && !sessionValid) {
sessionID = UUID.randomUUID().toString();
Cookie browserCookie = new Cookie("browserCookie", sessionID);
httpServletResponse.addCookie(browserCookie);
Cookie userCookie = new Cookie("userCookie", "normal");
httpServletResponse.addCookie(userCookie);
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
//Session expires. Each time user close the tab and session expires automatically
} else if(sessionID != null && !sessionValid) {
if (httpServletRequest.isRequestedSessionIdFromCookie()) {
Cookie userCookie = getCookie(httpServletRequest, "userCookie");
String value = userCookie.getValue();
//Each time getting normal
if (value.equalsIgnoreCase("normal")) {
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else if (value.equalsIgnoreCase("loginUser")) {
}
} //end of if (httpServletRequest.isRequestedSessionIdFromCookie())
}
}
} //end of dofilter()
} //end of class SessionTimeoutFilter
当您第一次打开页面时,条件if (sessionID == null && !sessionValid)
变为 true,并且 userCookie 设置为正常值。现在,如果您关闭浏览器选项卡,则再次打开页面。cookie 值正常。好的。
但是现在,当您登录时,就会出现 condition if (isRegisteredUser.equalsIgnoreCase(("1")))
。在这里我试图替换 userCookie 值,比如
Cookie userCookie = getCookie(httpServletRequest, "userCookie");
if (userCookie != null) {
String value = userCookie.getValue();
//delete the cokie
//userCookie.setValue("loginUser");
//userCookie.setMaxAge(0);
Cookie loginUserCookie = new Cookie("userCookie", "loginUser");
httpServletResponse.addCookie(loginUserCookie);
}
但是这两种方法都不起作用。现在,如果我关闭浏览器,然后再次打开页面,然后在条件下
if (value.equalsIgnoreCase("normal")) {
session.setAttribute("logedin", "0");
filterChain.doFilter(httpServletRequest, httpServletResponse);
} else if (value.equalsIgnoreCase("loginUser")) {
}
作为 userCookie 值,我再次变得正常。这次它应该让我获得值“loginUser”,因为我已将 userCookie 的值更改为 loginUser。但是我在这里变得正常了。为什么我得到以前的值。我做错了什么?请告诉我。
谢谢