Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

http session event

Hi,

I am going thorugh below example



http://www.javatpoint.com/HttpSessionEvent

I wonder when below method getting called
 public void sessionDestroyed(HttpSessionEvent e) {  
21.        current--;  
22.        ctx.setAttribute("currentusers",current);  
23.    }  


please advise
Any links resources ideas highly appreciated. Thanks in advance
SOLUTION
Avatar of Ken Butters
Ken Butters
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

A session will persist across potentially multiple connections and so is not tied to any one particular connection.

I am not clear how session can be maintained across multiple connections. I thought session is specific to let us say one online user say John while he is accessing shopping cart let us say in amazon for his particular internet connection. Please advise.
>I am not clear how session can be maintained across multiple connections .
The Servlet container uses an id to identify  the user's session. When a request is received by the container, it checks for a session id. If the container finds a session id in the request, then it checks to see if there is a valid session associated with that id. Let's suppose that you browsed to a site and have created a session. You can use that same browser to open a second window(tab in browser) and make a new request to the same site. If you are using cookies, then the browser will send the session cookie that was made for the first window. Both windows will be in the same session but will have made separate connections.
You can use the following demonstration  JSP.
<%
  String path = request.getServletPath() + request.getContextPath();
  String encodedPath = response.encodeURL(path);
  Integer count = (Integer)session.getAttribute("count");
  if(count==null)count = new Integer(0);
  session.setAttribute("count",new Integer(count.intValue() + 1));
%>
The session id is ${pageContext.session.id}<br/>
Is the session new? ${pageContext.session['new']}<br/>
Did the client send the session id in the url? ${pageContext.request.requestedSessionIdFromURL}<br/>
Did the client send the session id in a cookie? ${pageContext.request.requestedSessionIdFromCookie}<br/>
path is <%=path%><br/>
encodedPath is <%=encodedPath%> <br/>
count=<%=count%><br/><br/>
<a href="<%=path%>">Not encoded request</a><br/><br/>
<a href="<%=encodedPath%>">Encoded request</a><br/>

Open in new window


You can use that code to see how the session tracking mechanisms work. If you have questions about it,then ask us here.
As for your question at the top,  the sessionDestroyed method is called when the session is timed out  or when you use  
session.invalidate();

Open in new window

in your code. Connections have nothing to do with it
Avatar of gudii9

ASKER

You can use that same browser to open a second window(tab in browser) and make a new request to the same site. If you are using cookies, then the browser will send the session cookie that was made for the first window. Both windows will be in the same session but will have made separate connections.


I opened my bank account in one tab of chrome browser and it asked me to login. I gave usernmae and password and logged in. I opened other tab in same chrome browser. It is again asking me to enter user name and password. If i enter then it will link to old session object that i logged earlier. please advise
>I opened other tab in same chrome browser. It is again asking me to enter user name and password.    
What page did you browse to  ? What did you type(or paste) into the address bar?
Did you go to login page? The log-in page doesn't look for the cookie.  Or did you copy the address from the first tab after you were logged in?  That second thing  is what I would try.   The browser should send the  cookie that you already obtained in first tab.
Avatar of gudii9

ASKER

i typed
https://www.bankofamerica.com/

It said welcome back, xyz
then xy*** with sign In button. I clicked sign in buttom.

It went to next page where there is Your SiteKey with password. I entered my password. i successfully logged in and lead to next page with account details etc.
I copied the url at this instace like
https://secure.bankofamerica.com/myaccounts/signin/signIn.go?isSecureMobile=false&returnSiteIndicator=GC&langPref=en-us&request_locale=en-us&capturemode=N&newuser=false&callOM=Y&bP=F

Opened new chrome browser tab and pasted above url

It said welcome back, xyz
then xy*** with sign In button. I clicked sign in buttom.

It went to next page where there is Your SiteKey with password. I re-entered my password. successfully logged in and lead to next page with account details etc.

I tried pasting url===>https://www.bankofamerica.com/ again in other tab that also
It said welcome back, xyz
then xy*** with sign In button. I clicked sign in buttom.

It went to next page where there is Your SiteKey with password. I re-entered my password. successfully logged in and lead to next page with account details etc.

Please advise why i need to enter password details in new tab even though i logged in previous tab to the bank.
>Please advise why i need to enter password details in new tab even though i logged in previous tab to the bank  
I don't know.  Maybe an expert can explain it.
@gudii9,

This sounds like it is just the way that "bankofamerica" have setup their website. Try something for me, once you login and get the list of your accounts, try "refreshing the page" and tell us.... does it still show your accounts or does it ask for your password again?

Or alternatively, to see what a typical site does, if you have a gmail account open a tab and go to gmail.com and then login. Now go to another tab and go to gmail.com again and this time it shouldn't ask you for login details.


Oh, and going back to what I wrote up the top (and your question about it), by "connection" I did not mean your internet connection, I meant each individual TCP connection. In simplistic terms, when you navigate to a webpage a TCP connection is opened to request it and get the page data back, and then the TCP connection is closed. Now if you click a link on that page to go to a new page, a new TCP connection is opened to request that new page and to retrieve it, and then that TCP connection is closed. This is what I meant about "multiple connections".
I did some testing.  
yahoo mail, gmail, and experts-exchange.com  all work the way we have described.
I guess your banking site has some extra safe guards.  
The easiest way to learn about the session tracking mechanisms is to set up a stand alone Tomcat on your desktop and use the JSP that I posted above here.  By the way, google's Chrome browser allows you to block cookies(ask us if you don't know how). When cookies are blocked, the session id is added the url. Go ahead and play with the  JSP that I posted. You should be able to increment the count variable with and with out using cookies.  
The site we are using now(experts-exchange) is built with java.  If you look at the cookies for this site, then you will see one named jsessionid.  But, unfortunately this site doesn't allow us to not use cookies. So, you can't see the url rewriting mechanism here.
Avatar of gudii9

ASKER

gmail, and experts-exchange.com  all work the way we have described.

I tested too they works as you mentioned unlike bank.

google's Chrome browser allows you to block cookies(ask us if you don't know how).

Please let me know how to do it
To block cookies in Chrome:
Click on the button on the far right of the  address bar.
Choose Settings in the dropdown menu.
On the bottom of the Settings page, click on "Show advanced settings...".
Under Privacy heading click  "Content Settings..."  button.
Under Cookies heading select "Block sites from setting any data"
Click Done.
Close browser.
Avatar of gudii9

ASKER

I ran the JSP on tomcat.

When i refresh browser URL the count is increasing as below.


The session id is 878A76B14B41BC15B2E624B857361A32
Is the session new? true
Did the client send the session id in the url? false
Did the client send the session id in a cookie? false
path is /NewFile.jsp/CookiesProject
encodedPath is /NewFile.jsp/CookiesProject
count=0

Not encoded request

Encoded request


 But the below links are not working


Not encoded request

Encoded request

Please advice on how to fix them.
Avatar of gudii9

ASKER

You can use that code to see how the session tracking mechanisms work. If you have questions about it,then ask us here.

I ran JSP but not clear on how the session tracking mechanisms demonstrated in this jsp. Please advise
I am sorry. I made a cut paste error. I didn't notice it because I tested in my ROOT web app( which has a context path of ""). It  is just the second line that has the error.
<%
  String path = request.getContextPath() +  request.getServletPath();
  String encodedPath = response.encodeURL(path);
 Integer count = (Integer)session.getAttribute("count");
  if(count==null)count = new Integer(0);
  session.setAttribute("count",new Integer(count.intValue() + 1)); 
%>
The session id is ${pageContext.session.id}<br/>
Is the session new? ${pageContext.session['new']}<br/>
Did the client send the session id in the url? ${pageContext.request.requestedSessionIdFromURL}<br/>
Did the client send the session id in a cookie? ${pageContext.request.requestedSessionIdFromCookie}<br/>
path is <%=path%><br/>
encodedPath is <%=encodedPath%> <br/>
count=<%=count%><br/><br/>
<a href="<%=path%>">Not encoded request</a><br/><br/>
<a href="<%=encodedPath%>">Encoded request</a><br/>

Open in new window

You are almost there. Just get that path fixed.
Avatar of gudii9

ASKER

with new jsp i am seeing this error

HTTP Status 500 - Unable to compile class for JSP

--------------------------------------------------------------------------------

type Exception report

message Unable to compile class for JSP

description The server encountered an internal error that prevented it from fulfilling this request.

exception

org.apache.jasper.JasperException: Unable to compile class for JSP
      org.apache.jasper.JspCompilationContext.compile(JspCompilationContext


Please advise on how to fix it
Avatar of gudii9

ASKER

Here is complete stack trace

May 04, 2014 3:49:23 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jre7\bin;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jre7/bin/client;C:/Program Files/Java/jre7/bin;C:/Program Files/Java/jre7/lib/i386;C:\Windows\system32;C:\Windows;C:\Windows\System32\Wbem;C:\Windows\System32\WindowsPowerShell\v1.0\;C:\Users\ganesha\WorkngSesson_04152014\eclipse-jee-kepler-SR2-win32\eclipse;;.
May 04, 2014 3:49:23 PM org.apache.tomcat.util.digester.SetPropertiesRule begin
WARNING: [SetPropertiesRule]{Server/Service/Engine/Host/Context} Setting property 'source' to 'org.eclipse.jst.jee.server:CookiesProject' did not find a matching property.
May 04, 2014 3:49:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
May 04, 2014 3:49:24 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
May 04, 2014 3:49:24 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 1372 ms
May 04, 2014 3:49:24 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
May 04, 2014 3:49:24 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.52
May 04, 2014 3:49:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
May 04, 2014 3:49:25 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
May 04, 2014 3:49:25 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 1286 ms
May 04, 2014 3:49:28 PM org.apache.catalina.core.StandardWrapperValve invoke
SEVERE: Servlet.service() for servlet [jsp] in context with path [/CookiesProject] threw exception [Unable to compile class for JSP] with root cause
java.io.IOException: tmpFile.renameTo(classFile) failed
      at org.apache.jasper.compiler.SmapUtil$SDEInstaller.install(SmapUtil.java:204)
      at org.apache.jasper.compiler.SmapUtil.installSmap(SmapUtil.java:163)
      at org.apache.jasper.compiler.JDTCompiler.generateClass(JDTCompiler.java:483)
      at org.apache.jasper.compiler.Compiler.compile(Compiler.java:378)
      at org.apache.jasper.compiler.Compiler.compile(Compiler.java:353)
      at org.apache.jasper.compiler.Compiler.compile(Compiler.java:340)
      at org.apache.jasper.JspCompilationContext.compile(JspCompilationContext.java:657)
      at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:357)
      at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
      at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
      at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
      at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
      at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
      at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
      at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
      at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
      at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
      at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
      at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
      at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
      at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
      at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
      at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
      at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
      at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
      at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
      at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
      at java.lang.Thread.run(Unknown Source)



Please advice.
You were able to compile my original JSP.
Now, you must have a problem with your configuration. Are you able to run a simple hello JSP?
What is your configuration?  
Are you running Tomcat within Eclipse?  Since I see Kepler on your library path, I guess you are doing that. Please correct me if I wrong in my assumption.  
I am not an eclipse expert. But, I will try to help you. I googled for some ideas.  
Did you try cleaning your project?(click on clean in dropdown menu from clicking on Project at top menu bar)
I guess that you didn't change any permissions on your folders and you have permission to write to wherever tmpfile is being written.  Is that correct?    
Click on Server tab on Java EE perspective, double click on your Tomcat server. A Overview page should open up. Can you show us that?
Avatar of gudii9

ASKER

Are you running Tomcat within Eclipse?  Since I see Kepler on your library path, I guess you are doing that. Please correct me if I wrong in my assumption.

that is correct. I am using eclipse kepler with tomcat

You were able to compile my original JSP.

That i had initially compilation errors similar to now. But those resolved by themselves after eclipse, laptop restarts somehow. But now they are not going off. Not sure what is eclipse issue behind this.
Avatar of gudii9

ASKER

Now it worked.


what is  difference beween below links


Not encoded request

Encoded request

Both are incrementin g count similar to browser url refresh which also increments count.
please advice
>Now it worked.  
Good.  
>what is  difference beween below links  
The encoded request has the session id written in the url  if cookies are blocked. If the session cookie is used, then they are the same.
When the session is new, the encoded url always has the session id in it. That is because the servlet container(Tomcat) doesn't know how or if the client will join the session.  At this point in time, the client hasn't sent the cookie back yet or alternatively hasn't sent an  encoded request.
Avatar of gudii9

ASKER

I see Not encoded request also incrementing the count. I wonder if that also has session id in it. please advice. I am still not able to get complete picture about this whole thing
There are two different mechanisms that the servlet container(Tomcat) can use to track the user through his session. The servlet container can use a session cookie to hold the session id or encode the session id in  urls.  The cookie mechanism is automatically handled by the servlet container and the user's browser. But, if the cookie is not accepted by the browser,  then the servlet container can encode urls that it sends in it's response. This doesn't happen automatically. The web app coder must run his urls through the response.encodeURL(url).  The coder can make a habit of this because the servlet container will not bother encoding the urls if the session cookie is used.
For the first request from the user to the servlet container, he hasn't joined the session yet. So, for the first response, the servlet container will send the session cookie and encode the urls (if the coder has used the response.encodeURL method on his urls). The container will do both because the session is new and it doesn't know yet which mechanism the client will use to identify himself for the session.
If you browse to the JSP that I posted, you see this in the first response . The encoded request has the session id in it and the cookie has been sent.  

To see the session cookie in your Chrome browser:
Go to the Content settings page.
Under Cookies heading, click on the "All cookies and site data..." button.  
In the list, click on your site to see the cookie(assuming that you didn't block it).
Click on the cookie to see it's contents.  

If the user decides to join the session, then in his second request he must send the cookie back(done automatically by the browser) or use the encoded link.  When the container receives the second request that contains the session id,  it can identify the user and maintain his session. At this point, the session is no longer new.  In subsequent responses the container will use the mechanism the user has decided to use. This is assuming that the coder has encoded all the urls in the links to his site.
You should be able to increment the count variable in my JSP using either tracking mechanism.

All this is specified in the  "Java Servlet Specification". You can download the file  
servlet-3_0-final--spec.pdf  
from  
http://download.oracle.com/otndocs/jcp/servlet-3.0-fr-eval-oth-JSpec/   
You should read the whole thing if you want to learn the Servlet technology.
Avatar of gudii9

ASKER

I will read it. I heard after MVC introduction in 2000 year no need to worry about the servlets, jsps as mvc frameworks like struts, spring takes care of it. Is that assumption is correct and safe?
Avatar of gudii9

ASKER

When i click link below link multiple times
Encoded request

I see jsp output as below


The session id is 5C776E6379BDA2C63DAB5155F3890DCF
Is the session new? false
Did the client send the session id in the url? false
Did the client send the session id in a cookie? true
path is /CookiesProject/NewFile.jsp
encodedPath is /CookiesProject/NewFile.jsp
count=12


My question is since i click 'Encoded request'(which i suppose not cookie but URL rewriting encoding mechanism) so below line must come false right instead of true

Did the client send the session id in a cookie? true



Also below line must come true instead of false right.

Did the client send the session id in the url? false

Please advise.
Avatar of gudii9

ASKER

<%
  String path = request.getContextPath() +  request.getServletPath();
  String encodedPath = response.encodeURL(path);
 Integer count = (Integer)session.getAttribute("count");
  if(count==null)count = new Integer(0);
  session.setAttribute("count",new Integer(count.intValue() + 1));
%>

why jsp preview is not showing above code.

Also how the count is incrementing no matter which link i click. Please advice
>I heard after MVC introduction in 2000 year no need to worry about the servlets, jsps as mvc frameworks like struts, spring takes care of it      
That is a good question. Please ask a new question in this topic area. It will be interesting to read comments from the  experts.  
Personally, I don't use a frameworks. As far as Java on the server is concerned, I use Servlets, JSP, JSTL, JDO, and tag files.
My question is since i click 'Encoded request'(which i suppose not cookie but URL rewriting encoding mechanism) so below line must come false right instead of true

Did the client send the session id in a cookie? true
 
Since the client sent the session cookie,  Tomcat doesn't bother encoding the urls.  It doesn't matter which link you use.
Also below line must come true instead of false right.

Did the client send the session id in the url? false
   
No, since the sesssion cookie is being used, Tomcat will not bother encoding any url.  

If you BLOCK cookies, then  after you click on the "Encoded" request link 3 times, you should see the following.

The session id is 8A6190F0DED4014576F814FD5E23164F
 Is the session new? false
 Did the client send the session id in the url? true
 Did the client send the session id in a cookie? false
 path is /sessionTest.jsp
 encodedPath is /sessionTest.jsp;jsessionid=8A6190F0DED4014576F814FD5E23164F
 count=3
If next you click on the "Not encoded" request link, then you will lose the current session. You will lose it  because you didn't send the session id in a cookie or in your url. You should see something like the following.
The session id is E4B9414949F65186BFE42A0D6ABEC2D4
 Is the session new? true
 Did the client send the session id in the url? false
 Did the client send the session id in a cookie? false
 path is /sessionTest.jsp
 encodedPath is /sessionTest.jsp;jsessionid=E4B9414949F65186BFE42A0D6ABEC2D4
 count=0
The container sent a different session id and the session is new. Now click on the "Encoded" request link. You should see the following.
The session id is E4B9414949F65186BFE42A0D6ABEC2D4
 Is the session new? false
 Did the client send the session id in the url? true
 Did the client send the session id in a cookie? false
 path is /sessionTest.jsp
 encodedPath is /sessionTest.jsp;jsessionid=E4B9414949F65186BFE42A0D6ABEC2D4
 count=1
 The session has been maintained because Tomcat was asked by the web app coder(me)  to send the encoded url in the last response and the user sent it back to Tomcat in his current request.
>why jsp preview is not showing above code.    
That is not a preview. That is a scriptlet.  That code is executed on the server and is not part of the output. You need to know how JSP and Servlets work. Basically the requested Servlet  does some code execution and outputs some HTML(most common) to the client for a response .
Avatar of gudii9

ASKER

I went to chrom settings and cookie settings to see below cookie data
Name:      JSESSIONID
Content:      1C4B3E5FA36216578F5B52F2CA65DAC3
Domain:      localhost
Path:      /CookiesProject/
Send for:      Any kind of connection
Accessible to script:      No (HttpOnly)
Created:      Tuesday, May 6, 2014 2:10:39 PM
Expires:      When the browsing session ends


Now it make sense why it is true for cookie

The session id is 1C4B3E5FA36216578F5B52F2CA65DAC3
Is the session new? false
Did the client send the session id in the url? false
Did the client send the session id in a cookie? true
path is /CookiesProject/NewFile.jsp
encodedPath is /CookiesProject/NewFile.jsp
count=1

If you BLOCK cookies, then  after you click on the "Encoded" request link 3 times, you should see the following.

How to block cookie in chrome to test url encoding mechanism as well. Please advise
Avatar of gudii9

ASKER

If next you click on the "Not encoded" request link, then you will lose the current session. You will lose it  because you didn't send the session id in a cookie or in your url. You should see something like the following.


The session id is E4B9414949F65186BFE42A0D6ABEC2D4
 Is the session new? true
 Did the client send the session id in the url? false
 Did the client send the session id in a cookie? false
 path is /sessionTest.jsp
 encodedPath is /sessionTest.jsp;jsessionid=E4B9414949F65186BFE42A0D6ABEC2D4
 count=0


Not encoding is third mechanism( i see both cookie and url reqriting are coming false for you) apart from cookies mechanism, url rewriting mechanism.


If next you click on the "Not encoded" request link, then you will lose the current session. You will lose it  because you didn't send the session id in a cookie or in your url. You should see something like the following

but for me instead of false false always coming false true as given below even after clicking Not encoded request link many times.

The session id is 1C4B3E5FA36216578F5B52F2CA65DAC3
Is the session new? false
Did the client send the session id in the url? false
Did the client send the session id in a cookie? true
path is /CookiesProject/NewFile.jsp
encodedPath is /CookiesProject/NewFile.jsp 
count=16

Not encoded request

Encoded request

Open in new window



How do i see false false like your output. please advise
>I went to chrom settings and cookie settings to see below cookie data  
Ok good. You can find the cookies that your browser is storing.  

>How to block cookie in chrome to test url encoding mechanism as well. Please advise    
I already posted that  at    
https://www.experts-exchange.com/questions/28407296/http-session-event.html?anchorAnswerId=40033915#a40033915   

>Not encoding is third mechanism( i see both cookie and url reqriting are coming false for you) apart from cookies mechanism, url rewriting mechanism.  
I only  described two mechanisms. I don't know what third mechanism that you are talking about.    

>but for me instead of false false always coming false true as given below even after clicking Not encoded request link many times.    
You have the session cookie stored. You can look in Chrome's "Cookies and site data" page.  
When the output is
 Did the client send the session id in a cookie? true  
That means that your browser sent the cookie.
>How do i see false false like your output. please advise    
You must block  the cookie.  For an experiment try clicking on the remove button(it is below the cookie data).
Avatar of gudii9

ASKER

I blocked the cookie and saw both false and false as below


The session id is F280FB1A8371400F1459DE04E9DB515F
Is the session new? true
Did the client send the session id in the url? false
Did the client send the session id in a cookie? false
path is /CookiesProject/NewFile.jsp
encodedPath is /CookiesProject/NewFile.jsp;jsessionid=F280FB1A8371400F1459DE04E9DB515F
count=0

Not encoded request

Encoded request



Now URL rewriting mechanism seems kicked in.


I wonder why the count is not increasing when i click


Not encoded request



I see when i blocked cookies gmail stopped working. How to unblock cookies again so that gmail works. what is the default option i have to click back
( is it is ---->Allow local data to be set (recommended)??)
I got this error

Oops! Your browser seems to have cookies disabled. Make sure cookies are enabled or try opening a new browser window. [?]



(
experts exchanges works fine even after blocking cookies)
One more helpful hint that I just noticed:
After you have gone through the settings page and performed  the steps to block cookies that I posted,  when the Chrome browser blocks a cookie,  it displays a brown cookie with a red X across it.  You should see that icon in the address bar. It should appear right next to the bookmark star.  If you click on the cookie icon it will open up a dialog box.
>Now URL rewriting mechanism seems kicked in.  
Good. We are getting somewhere.  

>I wonder why the count is not increasing when i click   Not encoded request    
If you have cookies blocked and don't use encoded url, then the server can't identify you.  

>How to unblock cookies again so that gmail works. what is the default option i have to click back
( is it is ---->Allow local data to be set (recommended    
Yes
Or click on that cookie icon that I described in my last comment.

>experts exchanges works fine even after blocking cookies)  
Isn't the cookie for experts-exchange already stored ?  
I think blocking cookies means that no new ones will be accepted.
Avatar of gudii9

ASKER

I see since server cannot identify


  Integer count = (Integer)session.getAttribute("count");
  if(count==null)count = new Integer(0);
  session.setAttribute("count",new Integer(count.intValue() + 1));


Count increment not happening since session.setAttribute is not updating with new incremented count right?
>Count increment not happening since session.setAttribute is not updating with new incremented count right?    
Wrong.  
A JSP creates a session by default.  If a request is sent without a session id, then a new session will be created. Keep your eye on the session id.
   Let's take the code step by step.
session.getAttribute("count")

Open in new window

For the first request or for any request that doesn't send a session id,  the session is new and there are no attributes set yet. Therefore the session attribute "count"  is equal to null.  


  Integer count = (Integer)session.getAttribute("count");

Open in new window

Now the "scripting variable"  "count is null.



if(count==null)count = new Integer(0);

Open in new window

Since the condition is true, now the "scripting variable" count is equal to an Integer with a  value of 0.

In the lower part of the JSP we have  
count=<%=count%>

Open in new window


Therefore the value of the "scripting variable" count is written to the response.
Next in the scriptlet we have
session.setAttribute("count",new Integer(count.intValue() + 1));

Open in new window


Here we have set the session attribute "count" to 1.  But, we don't use that value until the next request and the page executes
 Integer count = (Integer)session.getAttribute("count");

Open in new window

 If the user joins the session(by returning his session id),  then  the "scripting variable" count is equal to an Integer with a value of 1 and for the output
count=<%=count%>

Open in new window

he will see
count =1
 I guess I should have defined count as the number of requests that the user has made since joining the session. What do you think?
Avatar of gudii9

ASKER

I agree it should have been better with noOfRequests etc rather than count.

  String path = request.getContextPath() +  request.getServletPath();
  String encodedPath = response.encodeURL(path);


What is patha dnwhat is encodedPath. How they are related in this context
>What is patha dnwhat is encodedPath.    
path is another name for url. In your case it was
  /CookiesProject/NewFile.jsp
This is what as known as a relative path. It begins with a "/"  therefore the browser interprets it as relative to the server.
encodedPath is the path encoded with  session id.  In your case it would look like
 /CookiesProject/NewFile.jsp;jsessionid=8A6190F0DED4014576F814FD5E23164F    
>How they are related in this context    
I needed a path in order to construct the links at the bottom of the JSP.  
>request.getContextPath() +  request.getServletPath();  
In order for you to begin to understand code, you must start reading the API.  
http://docs.oracle.com/javaee/7/api/overview-summary.html     
more specifically for this discussion
http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpServletRequest.html 
http://docs.oracle.com/javaee/7/api/javax/servlet/http/HttpSession.html
Avatar of gudii9

ASKER

Makes more sense.
Here we have set the session attribute "count" to 1.  But, we don't use that value until the next request and the page executes
 Integer count = (Integer)session.getAttribute("count");

How did you tell code not to use until next request and page executes?
Please advice
>How did you tell code not to use until next request and page executes?   Please advice      
That is the way I chose to write the code.
 
count=<%=count%> this is the scripting variable

Open in new window


The session-scoped variable is the following
session.getAttribute("count")

Open in new window

If I chose to display the session-scoped variable called count , then I would have used the following
count=${count} this is the scoped variable

Open in new window

 

I just used the session-scoped variable to store the value.   This way it was available for multiple requests from the user.  
I guess it is confusing that I used the same name for the scripting variable and the session-scoped variable. But once you learn how to read the code, it would perfectly clear. Look at  
http://javapapers.com/jsp/explain-the-scope-of-jsp-objects/   
http://strutscr.uw.hu/0059.html
http://hscripts.com/tutorials/jsp/jsp-scopes.php 
http://www.java-samples.com/showtutorial.php?tutorialid=1009
Avatar of gudii9

ASKER

I guess it is confusing that I used the same name for the scripting variable and the session-scoped variable.

can you please send the code by renaming them so that i can analyze whole code and understand based on the info and link you sent
Ok. Here is my rewrite.  Please tell me if there is anything I could change to make it more clear.
<%
  String url = request.getContextPath() +  request.getServletPath();
  String encodedURL = response.encodeURL(url);
  if(session.getAttribute("numberOfRequests") == null)session.setAttribute("numberOfRequests", 0);
  session.setAttribute("numberOfRequests", (Integer)session.getAttribute("numberOfRequests") + 1); 
%>
The session id is ${pageContext.session.id}<br/>
Is the session new? ${pageContext.session['new']}<br/>
Did the client send the session id in the url? ${pageContext.request.requestedSessionIdFromURL}<br/>
Did the client send the session id in a cookie? ${pageContext.request.requestedSessionIdFromCookie}<br/>
URL of this page is <%=url%><br/>
Encoded URL is <%=encodedURL%> <br/>
Number of requests in this session is ${numberOfRequests}<br/>
Use the links below to refresh this page.<br/>
<a href="<%=url%>">Not encoded request</a>&nbsp;&nbsp;&nbsp;<a href="<%=encodedURL%>">Encoded request</a>

Open in new window

Avatar of gudii9

ASKER

Line1: if(session.getAttribute("numberOfRequests") == null)session.setAttribute("numberOfRequests", 0);
Line2:  session.setAttribute("numberOfRequests", (Integer)session.getAttribute("numberOfRequests") + 1);

in above two lines there is no relation between line 1 and line 2 right. Is there is any relation like If session.getAttribute("numberOfRequests") is not null then execute line2 ?

Please advice
you cannot add 1 to a NULL.

So the only thing the first line is doing is checking for a NULL, and if it is equal to NULL it sets it to zero.
Then on the second line, it increments it by 1.

If you removed the first line, it is possible you could be trying to add 1 to NULL.
Avatar of gudii9

ASKER

so Line1 and Line2 are independent of each other. As the program continues to execute it goes through line by line like Line1 and then Line2 right. It is basically not like IF  ELSEIF kind of conditional statement right?
correct.
Avatar of gudii9

ASKER

To completely understand this program completerly i need to brush up some JSP skills from the links, info provided. I will get bak
>in above two lines there is no relation between line 1 and line 2 right.  
Right.
>Is there is any relation like If session.getAttribute("numberOfRequests") is not null then execute line2 ?  
No relation or condition. I did not use the keyword else.        

If the session is new, then there can't be any attributes set yet. So, my fourth  line(your line 1) creates and sets the attribute to 0.  
My fifth line(your line2) always increments the attribute.
i need to brush up some JSP skills

When you look at the code here... the fact that it is enclosed in "<%" and "%>" that tells you that the enclosed code is javascript.

So the formatting of the if (cond) expression; that you were asking about was concerning the syntax of javascript... not so much JSP's.
Ken,

Just one small correction to what you said above... The code in the JSP is actually Java (not JavaScript).
whoops!... thanks!  ;)
Avatar of gudii9

ASKER

I ran latest jsp.

I got output like this

The session id is 7CD8CF34DC876CED28DE0F69FC28ED99
Is the session new? false
Did the client send the session id in the url? false
Did the client send the session id in a cookie? true
URL of this page is /CookiesProject/NewFile2.jsp
Encoded URL is /CookiesProject/NewFile2.jsp
Number of requests in this session is 17
Use the links below to refresh this page.
Not encoded request   Encoded request

wheni click the Encoded Request link multiple times. It makes sense to me as i have not disabled cookies session tracking is being done using cookies mechanism rather than url rewriting.

I have one question. why both below URLs printing the same
URL of this page is /CookiesProject/NewFile2.jsp
Encoded URL is /CookiesProject/NewFile2.jsp

Please advice
URL encoding will take special characters (most of the time -- blanks) and convert the to hex.

if your URL were : /My Cookie Project/New File2.jsp
your encoded URL might be : /My%20Cookie%Project/New%20File2.jsp

but you didn't have any special characters in your URL that needed encoding.
Avatar of gudii9

ASKER

All that we are majorly doing in this jsp is to check if session tracking is done via cookies or URL rewriting
Then print count of number of visits in current session right.
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
@Ken Butters,
You are talking about HTML form encoding. Look at  
http://docs.oracle.com/javase/7/docs/api/java/net/URLEncoder.html
Avatar of gudii9

ASKER

The first response will show the session id in the "EncodedURL"  

Yea, I remember now I tested as you mentioned by disabling cookies and got the encoded url with the session id as well as below



The session id is F280FB1A8371400F1459DE04E9DB515F
Is the session new? true
Did the client send the session id in the url? false
Did the client send the session id in a cookie? false
path is /CookiesProject/NewFile.jsp
encodedPath is /CookiesProject/NewFile.jsp;jsessionid=F280FB1A8371400F1459DE04E9DB515F
count=0

Not encoded request

Encoded request