问题描述
我真的很抱歉,这是关于Cookie的第二个或第三个问题,但老实说,我不明白为什么会发生这种情况...
在登录页面上,我通过以下方式设置Cookie:
I''m truly sorry, this is the second or third question about cookies, but honestly I can''t understand why this happens...
On the login page I set the cookie this way:
Cookie cookie = new Cookie("username", user);
cookie.setMaxAge(365 * 24 * 60 * 60);
response.addCookie(cookie);
然后将用户重定向到其他页面.
除了以下内容,我删除了几乎所有代码(以确保没有冲突):
And then user is redirected to a different page.
I deleted almost all my code (to make sure there are no conflicts), except this:
<%@page import="javax.servlet.http.Cookie"%>
<html>
<%
Cookie cookies[] = request.getCookies();
Cookie nome = null;
Cookie aux_login = null;
int auxiliar = 0;
Cookie idaux = null;
String jog1="",jog2="";
if (cookies != null) {
for (int i = 0; i < cookies.length; i++) {
out.println("<br>"+cookies[i].getName()+" <br>");
if (cookies[i].getName().equals("username")) {
nome = cookies[i];
}
if (cookies[i].getName().equals("aux_login")) {
aux_login = cookies[i];
}
if (cookies[i].getName().equals("idsala")) {
idaux = cookies[i];
}
}
}
out.println("ARE NULL ??");
if (nome == null) {
out.println("Cookie ''username'' nao encontrada");
else
welcome nome.getValue()...
}
因此,在第一次加载时未找到Cookie(已验证nome == null),但是如果刷新页面,便会找到它们-因此它们存在,但在第一次加载时它们未被检测到...
我究竟做错了什么?考虑一下这件事,如果页面相同,那将是正常的(当然会显示信息),但是页面却是不同的...
So at the first load cookies are not found (that nome == null is verified), but if I refresh the page they are found - so they exist, but in a first load they are not being detected...
What am I doing wrong? Thinking about the matter this would be normal (the information displayed of course) if the page was the same, but it''s a different page...
推荐答案
if (nome == null) {
out.println("Cookie 'username' nao encontrada");
and with js script..
window.location.reload();
我被重定向到index.jsp.多数民众赞成在我登录成功(并转到default.jsp)时发现我的URL仍然是(出于某种动机!)index.jsp.
看起来像是因为这样进行重定向:
I was redirectedto index.jsp. Thats when I noticed when I do a sucessfull login (and go to default.jsp) my URL is still (for some motive!!) index.jsp.
Looks like its because doing the redirect this way:
<jsp:forward page="/default.jsp" />
<%
使用response.sendRedirect("default.jsp");
解决的问题
请注意,上一页的request.getParameter("t1")将不再起作用.
附注:使用会话进行身份验证总是更安全.
Problem solved with response.sendRedirect("default.jsp");
Be advised that request.getParameter("t1") from previous page will not work anymore.
P.S: It''s always safer use sessions for authentication.
这篇关于仅在刷新页面后加载Cookie的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!