|
 |
pro_jsp thread: cookie problems
Message #1 by "Dima" <difrad76@y...> on Fri, 14 Feb 2003 23:32:54
|
|
I think your problem is here:
String currentSession=session.getId();
There is no session until you create one. (Assuming you don't have that
above this code) If this is the entry page, you should create the session
thus:
HttpSession session = request.getSession(false);
'false' tells the server to create a new session object only if one does not
exist.
Also look into setting up a filter to redirect requests without a session to
a JSP or servlet that creates one.
Also keep in mind that the response is generated as a whole on the server
and then sent to the client, so the cookie isn't set on the client until
after this code is processed. You can't set and use a cookie on the same
JSP.
Greg
-----Original Message-----
From: Dima [mailto:difrad76@y...]
Sent: Friday, February 14, 2003 11:33 PM
To: Pro_JavaServer_Pages
Subject: [pro_jsp] cookie problems
Hello
I have some problems with the cookies. I need to make sure that error pages
is displayed when there is no cookie or session Id stored in cookie doesn't
match current session. it seems that when someone hits the protected page
the first time Tomcat displays error "null pointer exception" but when the
page is reloaded it redirects to the proper error page that I have created.
This is the jsp code
<%@ page import="java.sql.*" %>
<%@ page import="java.io.*"%>
<%
Cookie [] readCookie=request.getCookies(); //array of cookies
Cookie cookie; //individual cookie
String cookieName=new String(); // stores name of the cookie
String userId=new String(); // stores user id retrieved from cookie
String user_session=new String(); // stores user's session if doesn't
match current session //will give an error.
String currentSession=session.getId(); // current session
String URL="lgError.jsp"; // Destination URL. That's where error page is
located
int ec=0; // error flag if 0 no error. if 1 error
if (readCookie.length<=1) //There is always at least 1 cookie placed by
the jsp
{
//if it is less then then there is no appropriate cookie.
ec=1;
out.print("<p align=\"right\"> Error:No Cookies ");
}
else
{
for (int i=0; i<readCookie.length;i++) // loops through array searching
for cookie
{
cookie=readCookie[i]; //reading cookie out of the array
cookieName=cookie.getName(); // gets cookie name
if (cookieName.equals("user")) //finds appropriate cookie
userId=cookie.getValue(); // gets cookie value
if (cookieName.equals("session")) //finds appropriate cookie
{
user_session=cookie.getValue(); // gets cookie value
if (!user_session.equals(currentSession)) // checks if session is
the same
ec=1; // error flag raised
}
}
}
if (ec==1) // if matches error code 1
response.sendRedirect(URL); // redirects to the error page
else
//else
%>
here goes regular HTML
|
|
 |