|
Page 6 of 6
Ok, now let’s add some codes to add attribute to the session. We will achieve it using Scriptlet. Scriptlet is basically Java codes that are embedded in our JSP. It helps us in creating our application dynamic. So please add below codes in your JSP.
<%
System.out.println("Adding attribute to Session...");
request.getSession().setAttribute("test", "test");
System.out.println("Adding attribute to Session completed!");
System.out.println("Removing Session...");
request.getSession().invalidate();
System.out.println("Removing Session completed!");
out.println("Successfully adding and removing attributes from Session");
%>
This scriptlet can be placed anywhere in your JSP. For this example, I can just put it within my <body></body> tag. If you are in the right track, it should look like below screenshot.
Create the JSP file by right click your Web Pages and choose New then JSP…
The newly created JSP should look like below illustration.
Add the scriptlet to test our HttpSessionListener.
Now, to try both Listeners, let’s deploy our web application again.
Try to execute the testSession.jsp by typing in the URL manually in your browser.
This is the desired output that I grabbed from my local Tomcat console.
Conclusion
Well, you should have successfully implemented both ServletContextListener as well as HttpSessionListener. These two listeners are the most widely used and I hope that by reading the tutorial, you have a clear way and objective when you are moving forward with J2EE programming. There are still much to be learnt and please do not worry as this is not hard. My suggestion is to try the sample in this tutorial and try to customize it. Your skills will be much improved by practicing more. There are also two additional Listeners that are not mentioned in this tutorial which are ServletContextAttributeListener and HttpSessionAttributeListener. They are just slightly different with our tutorial. Have a look at them and try them out.
You can find the NetBeans project for the tutorial source codes here.
The README file for the source codes is available here.
Related Tips
<< Start < Prev 1 2 3 4 5 6 Next > End >> |
You can share your information about this topic using the form below!
Please do not post your questions with this form! Thanks.