Session Management


Published on

This paper is assignment for my Web Programming course. In this paper, I explain about various session management techniques that can be used in Web development.

I assume that people who is reading this have a lil bit background in Web Programming, mainly in JSP. But, the theory can also be applied to other Web programming language as well.

Published in: Education
1 Like
  • Be the first to comment

No Downloads
Total views
On SlideShare
From Embeds
Number of Embeds
Embeds 0
No embeds

No notes for slide

Session Management

  1. 1. Session Management Fiona Angelina 04PAC (1301025890)Expected Duration: 150 minsI. Introduction (Expected duration: 15 minutes)HTTP (HyperText Transfer Protocol) is a network protocol that is used to transfer documents overthe Internet. HTTP allows the web servers and client browsers to communicate with each other.With HTTP, we can develop a website that is hosted on a web server and that website can be seenthrough client browsers.Client always initiates the HTTP connection by making a HTTP request. Web server will give aresponse to the client and finally closes the connection. Because web server always closes theconnections after responding to client, the HTTP cannot identify the client. Identify means webserver does not know whether the one which request connection is a new client or a client that hasrequested before. That is why HTTP is said to be stateless.To understand about the concept, just imagine that the server is a forgetful old man. Afterresponding to your request, he won’t remember anything. Simpons characters are the property of Fox. I reproduce this image on my own using Adobe Photoshop CS3.This behavior of HTTP can bring problems. Imagine you want to access your email account, but everytime you want to do something (for example, checking your inbox, opening an email from yourfriend, or even only to refresh your current page), you have to input your account and password. Ibet after opening 3 or 4 more pages, you’ll get tired of it.
  2. 2. In order to solve this problem, there is a way called “session management”. With sessionmanagement, the HTTP can now identify which client is requesting from it. There are severaltechniques in session management. It is important to understand each of session managementtechniques (not only one technique) since each technique has their own strengths and weaknesses.So, which techniques to be used are depends on the problem that you want to solve.Back to the analogy of a forgetful old man, the session management techniques are just like givingthe old man a note. So whenever you make a request to him, he can look at the note and rememberwhat you’re talking about.There are several techniques to be discussed:  URL rewriting  Hidden fields  Servlet config and servlet context  Cookies  Session
  3. 3. II. URL Rewriting (Expected duration: 10 minutes)Do you remember that when you are using method GET inside the form, the parameter that youpass from a page is exposed in the URL?The URL rewriting technique uses the ability of passing parameter through the URL. Programmermodifies the URL to send parameter from 1 servlet to the other. Yes you can pass a parameter via the URL. See how the parameter x and y are exposed in the URL.Notice how the URL is written:http://localhost:8084/PassingParamHTTPServlet/page3.jsp?x=5&y=4The token “?” separates the URL of the page with the parameters. Name and value of the parameterare separated using token “=”. Parameters are separated using token “&”.Now open the PassingParamHTTPServlet project in your NetBeans and let’s examine how theparameter is being passed through the URL.There are in total 4 files in this project. 3 of them are JSP files, and 1 Java files which acts as theservlet. Open the index.jsp. Index page asks input from user to get the X value. The value is passed tothe servlet MyServlet.
  4. 4. Next open the MyServlet and scrolls down to the doGet method. We look inside the doGet methodbecause the form from index page is using method GET to pass the parameter. Look how thesendRedirect method is written. The parameter X that is received by servlet from index page, isbeing passed again to page2 by modifying the URL.Open the page2.jsp. The X parameter that is received is being passed to the MyServlet by usinghidden fields (which will be covered next). X and Y are being passed again to MyServlet, this timeusing the POST method.Open again MyServlet, and look inside the doPost method. X and Y are being passed to the page 3 bymodifying the URL.Open page3.jsp. In the page 3, the parameters that are being passed from servlet is being printed tothe web browser. By examining this project, we can conclude that we can actually send parameterthrough the URL.
  5. 5. Run the project, and see how the parameters are being passed.There are several things to be noted when using URL rewriting: (Kurniawan, 2006)  The number of characters that can be passed in a URL is limited. Typically a browser can pass up to 2,000 characters.  The value that you pass can be seen in the URL. Sometimes client prefer their password not to appear on the URL.  You need to encode certain characters such as “&”, “?”, “=”, and whitespaces that you append to a URL.
  6. 6. III. Hidden Fields (Expected duration: 10 minutes)Hidden fields technique makes use of hidden text fields which is provided by HTML form. The valuethat are being passed are not exposed in the URL, but it still can be seen in the source code of thepage.In order to understand how the hidden fields work, run the LoginDB project. Looking at the web page of blatantly, you see that there are only 3 text fields and 1 submit button inside the form. Try viewing the source code. In the picture, I use Mozilla Firefox 4.0. If you use other browsers, you can try finding it on your own.
  7. 7. Looking at the source code, you can see that there are actually three more parameters that will bepassed to other page if client presses the submit button. These parameters aren’t shown because we use hidden text fields.
  8. 8. IV. Servlet Config and Servlet Context (Expected duration: 15 minutes)Servlet ConfigWe can specify initial parameter name/value inside our servlet. These parameters can be laterretrieved using the ServletConfig object.When creating a servlet in NetBeans, you are being asked to set some parameters (if you want to).Try opening the web.xml, and you can see the value you’ve entered during the creation of theservlet.These value can be retrieved from the servlet by using ServletConfig object. The ServletConfig ispassed when the servlet is initialized. In the HttpServlet class, you can just override the public voidinit(ServletConfig config) throws ServletException method.See the code below that tries to get data from ServletConfig.
  9. 9. Pay attention to the code that are red-squared. In the init() method, we take the ServletConfigobject. In the processRequest method, we take the initial parameters from the ServletConfig. Usethe getInitParameter method to get the initial parameter value, and getInitParameterName methodto get the initial parameter name.Servlet ContextThe servlet container creates a ServletContext object that you can use to access information aboutthe servlet’s environment. You can use servlet context to store parameters that are shared amongfiles inside the Web Application. Servlet context can be both accessed from the Servlet or JSP files.You can get the servlet context from the servlet config.ServletContext servletContext = servletConfig.getAttributeNames();To set attributes inside the servlet context, you can use the method setAttribute method, and toretrieve it you can use getAttribute method.See Page 27-31 to learn more about how to use Servlet Context to store parameters. Here, I assumestudents have known a lot about servlet context (because they have learnt it during the week 3).
  10. 10. V. Cookies (Expected duration: 30 minutes)Refer to page 174-178 to understand how cookies really work.Cookie is a small piece of information that is passed back and forth in the HTTP request andresponse. (Kurniawan, 2006)Cookie is stored in the client’s computer. Whenever client makes a request to servlet, the servlet cangive response according to the cookie inside client’s computer.Cookie has expiration date. The default setting of cookie’s expiration date is when the browser isclosed. We can set the expiration date by using the method setMaxAge. The setMaxAge methodreceives parameter in seconds.cookie.setMaxAge(3600); //cookie will live for 3600 secondsThe advantage of using cookie:  Do not expose the sensitive information directly in the web browser like URL rewriting (in the URL) or hidden values (in page source). But note that user can also open his/her cookies information. So passing password in the user’s cookies can be dangerous as well (if being opened by irresponsible party).  Do not need to use any form. You can look at the cookies that are stored in your browser.The disadvantage of using cookie:  Some client can choose not to accept the cookie in his/her web browser. The normal practice is to use cookies with warnings to the client. The warning could be as a simple message telling the user to activate his/her cookie setting.
  11. 11. User can choose whether to accept cookies or not in his/her web browsers.How dangerous a cookie is when being used to store username and password? Try open the projectLoginCookies and run it in your NetBeans. Enter your username and password inside the fields and press “Submit Query” A notification will appear that the cookie has been stored in the web browser.Now check your cookies in your web browser. For Mozilla Firefox 4.0, open Tools > Options. Click onPrivacy tab. Change the combo box besides Firefox will… into “Use custom settings for history”.
  12. 12. Click “Show cookies” and you are being provided by list of cookies that are being stored in your web browser. Find localhost folder and click on the little arrow on the left. You are being provided by a lot of cookies that are being stored by your localhost. Find the “username” and “password” cookies since we are storing the cookie using that name. If this information is being seen by irresponsible party, the user’s account can be hijacked.
  13. 13. VI. Session (Expected duration: 10 minutes)Refer to page 191-194 to understand how session object really work.For each user, the servlet can create an HttpSession object that is associated with that user only andcan only be accessed by that particular user. HttpSession object acts like a Hashtable into which youcan store any number of key/object pairs. (Kurniawan, 2006)To ease the understanding, imagine HttpSession works like a deposit counter. When you want tostore something (which is object) in the deposit counter, you will be given a tag. This tag is thesession ID. It is used to access your object inside the deposit counter.Session ID is treated as a cookie in your web browser. With this session ID, you can access yoursession which is stored inside the servlet memory. How JSessionID looks like in our web browserWarning! Since Session also uses Cookies, user still needs to enable his/her cookie setting to ON.
  14. 14. VII. Class Exercise (Expected duration: 45 minutes)Objective:  To learn how to implements Session in your Java Web application.Description:Create a simple log in page. User can log in if he/she has an account. If not, he/she can register. Inthis exercise, you have to use JDBC to store the username and password of users.After user logged in/register successfully, he/she will be redirected to the Welcome page which willprint: “Hello”.If user has successfully logged in before, when he/she opens the login page, he/she will beredirected to the Welcome page. User can also go to Welcome page directly without having to log inagain. Use Session to solve this problem.Use simple Math verification if you’d like (it’s optional). Log in page Log in failed. After user log in successfully, he/she will be redirected to welcome page.
  15. 15. Sign up page.Notes: Solution can be found inside the folder Resources, with the name “LoginDB”.
  16. 16. VII. Conclusion (Expected duration: 10 minutes)See the table below to see the difference between each approach. URL Hidden Servlet Servlet Cookies Session Rewriting fields config contextScope Request Request Application Application Session SessionParameter is Yes No No No No Nobeing shownin URLAbility to set Yes Yes No Yes Yes YesparameterObject No request No Never Never Expired Expireddeleted request (default: until (default: untilwhen… the browser is the browser is closed) closed)Can others No No Yes Yes No Nosee storedparameters?By looking at the table, we can figure out which techniques to be used in solving our problems.Each technique has its own strength and weakness. Servlet config and servlet context can be usedwithout having to worry with user’s cookie setting. But there is limitation: users are treateduniformly since all users see the same parameters. Sometimes, it is important to treat each userdifferently. For example, in a welcome page, a page that welcomes user using his/her name wouldbe felt more user-friendly. A welcome page that welcome user using his/her name.URL rewriting and hidden fields are another way to manage session without having to worry forcookie settings. But its scope is only per request. URL rewriting is commonly used for passing errorparameter. Hidden fields are commonly used when you need to separate forms into smaller ones. URL Rewriting is being used to pass error parameter
  17. 17. Finally cookie and session objects are probably the most powerful techniques in managing session.But you must pay attention that to use cookie and session objects, user must turn ON its cookiesetting.The most common usage of cookie to greet user using his/her own name. Cookie will store theuser’s name, so next time he/she opens the welcome page, the Web will display “Welcome, Fiona”instead of “Welcome, user”.The most common usage of session is to store login information and shopping cart. Storing logininformation is safer using Session compare to Cookie (though still dangerous if it can’t be managedwell, example: through session hijacking). Shopping cart is also easier to be managed using Sessionsince Session object can store object, while Cookie can only store String.So, choose your session management technique wisely depending on your needs.
  18. 18. VII. Common QuestionsWhat is the purpose of Session Management?As it has been explained before, HTTP can’t remember anything because it always closes connection.Because of that session management is needed. With session management, Web can know whetheryou are a visitor that has visited the website before or not. If you are a visitor that is coming back,we may not need to log in again. If you are a new visitor, you will be asked to log in. Without sessionmanagement, these things are impossible to achieve.Session management is used for a lot of things such as shopping cart, log in system, and does notallow unauthorized user to enter some restricted pages (for example, the administrator page).What does request, application, session scope means?In request scope, parameter can be passed during a specific request. In application scope, parametercan be passed as long as user is using the Web application. In session scope, parameter can bepassed as long as user is in the same session. Example of a session is as long as the browser has notbeen closed (the default setting for cookie & session).Is cookie the same with session?Session uses cookies, but the way it works is different. Cookie stores information in client’scomputer. Session stores information in the server side. Only SessionID is being stored in client’sside (which is treated as a cookie).I have set the expiry date of my cookie to 1 day. I close my browser and open it again. I still needto input my username and password again. What’s wrong?Always remember that cookie won’t work if your browser doesn’t accept cookie. You have to turnthe cookie setting to ON.Here is how to turn the cookie setting in Mozilla Firefox:Tools > Option
  19. 19. Go to Privacy tab and change the combo box into “Use custom settings for history”. Make sure to tickthe “Accept cookies from sites”.Here is how to turn cookie setting in Google Chrome:Click the button and choose Options. New Settings tab will appear in your Chrome.
  20. 20. Choose “Under the Hood” and click on the “Content settings…” button.Make sure to untick the “Clear cookies and other site data when I close my browser”, and choose“Allow local data to be set”.Here is how the tutorial for Safari:Click icon and choose preferences.
  21. 21. Choose Security and ensure to choose “Always” or “Only from sites I visit”.Here is tutorial for Internet Explorer:Click icon and then choose “Internet options”Choose Privacy tab, and ensure your setting for Internet zone is Medium at minimum.
  22. 22. BibliographyKurniawan, B. (2006). Java for the Web with Servlets, JSP, and EJB. Indiana: New Riders Publishing.