Tutorial

Session Management in Java - HttpServlet, Cookies, URL Rewriting

Published on August 3, 2022
author

Pankaj

Session Management in Java - HttpServlet, Cookies, URL Rewriting

Session Management in Java Servlet Web Applications is a very interesting topic. Session in Java Servlet are managed through different ways, such as Cookies, HttpSession API, URL rewriting etc. Session Management in Java, Session in Java Servlet using Cookies, HttpServlet, URL Rewriting This is the third article in the series of Web Applications tutorial in Java, you might want to check out earlier two articles too.

  1. Java Web Application Tutorial
  2. Java Servlet Tutorial

Session Management in Java

This article is aimed to explain about session management in servlets using different techniques and with example programs.

  1. What is a Session?

  2. Session Management in Java - Cookies

  3. Session in Java Servlet - HttpSession

  4. Session Management in Java Servlet - URL Rewriting

  5. What is a Session?

    HTTP protocol and Web Servers are stateless, what it means is that for web server every request is a new request to process and they can’t identify if it’s coming from client that has been sending request previously. But sometimes in web applications, we should know who the client is and process the request accordingly. For example, a shopping cart application should know who is sending the request to add an item and in which cart the item has to be added or who is sending checkout request so that it can charge the amount to correct client. Session is a conversional state between client and server and it can consists of multiple request and response between client and server. Since HTTP and Web Server both are stateless, the only way to maintain a session is when some unique information about the session (session id) is passed between server and client in every request and response. There are several ways through which we can provide unique identifier in request and response.

    1. User Authentication - This is the very common way where we user can provide authentication credentials from the login page and then we can pass the authentication information between server and client to maintain the session. This is not very effective method because it wont work if the same user is logged in from different browsers.

    2. HTML Hidden Field - We can create a unique hidden field in the HTML and when user starts navigating, we can set its value unique to the user and keep track of the session. This method can’t be used with links because it needs the form to be submitted every time request is made from client to server with the hidden field. Also it’s not secure because we can get the hidden field value from the HTML source and use it to hack the session.

    3. URL Rewriting - We can append a session identifier parameter with every request and response to keep track of the session. This is very tedious because we need to keep track of this parameter in every response and make sure it’s not clashing with other parameters.

    4. Cookies - Cookies are small piece of information that is sent by web server in response header and gets stored in the browser cookies. When client make further request, it adds the cookie to the request header and we can utilize it to keep track of the session. We can maintain a session with cookies but if the client disables the cookies, then it won’t work.

    5. Session Management API - Session Management API is built on top of above methods for session tracking. Some of the major disadvantages of all the above methods are:

      • Most of the time we don’t want to only track the session, we have to store some data into the session that we can use in future requests. This will require a lot of effort if we try to implement this.
      • All the above methods are not complete in themselves, all of them won’t work in a particular scenario. So we need a solution that can utilize these methods of session tracking to provide session management in all cases.

      That’s why we need Session Management API and J2EE Servlet technology comes with session management API that we can use.

  6. Session Management in Java - Cookies

    Cookies are used a lot in web applications to personalize response based on your choice or to keep track of session. Before moving forward to the Servlet Session Management API, I would like to show how can we keep track of session with cookies through a small web application. We will create a dynamic web application ServletCookieExample with project structure like below image. Session in Java using Cookies Deployment descriptor web.xml of the web application is:

    <?xml version="1.0" encoding="UTF-8"?>
    <web-app xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance" xmlns="https://java.sun.com/xml/ns/javaee" xsi:schemaLocation="https://java.sun.com/xml/ns/javaee https://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
      <display-name>ServletCookieExample</display-name>
      <welcome-file-list>
        <welcome-file>login.html</welcome-file>
      </welcome-file-list>
    </web-app>
    

    Welcome page of our application is login.html where we will get authentication details from user.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="US-ASCII">
    <title>Login Page</title>
    </head>
    <body>
    
    <form action="LoginServlet" method="post">
    
    Username: <input type="text" name="user">
    <br>
    Password: <input type="password" name="pwd">
    <br>
    <input type="submit" value="Login">
    </form>
    </body>
    </html>
    

    Here is the LoginServlet that takes care of the login request.

    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String userID = "Pankaj";
    	private final String password = "journaldev";
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		// get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			Cookie loginCookie = new Cookie("user",user);
    			//setting cookie to expiry in 30 mins
    			loginCookie.setMaxAge(30*60);
    			response.addCookie(loginCookie);
    			response.sendRedirect("LoginSuccess.jsp");
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    		}
    
    	}
    
    }
    

    Notice the cookie that we are setting to the response and then forwarding it to LoginSuccess.jsp, this cookie will be used there to track the session. Also notice that cookie timeout is set to 30 minutes. Ideally there should be a complex logic to set the cookie value for session tracking so that it won’t collide with any other request.

    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    String userName = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    if(userName == null) response.sendRedirect("login.html");
    %>
    <h3>Hi <%=userName %>, Login successful.</h3>
    <br>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    Notice that if we try to access the JSP directly, it will forward us to the login page. When we will click on Logout button, we should make sure that cookie is removed from client browser.

    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LogoutServlet
     */
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        	response.setContentType("text/html");
        	Cookie loginCookie = null;
        	Cookie[] cookies = request.getCookies();
        	if(cookies != null){
        	for(Cookie cookie : cookies){
        		if(cookie.getName().equals("user")){
        			loginCookie = cookie;
        			break;
        		}
        	}
        	}
        	if(loginCookie != null){
        		loginCookie.setMaxAge(0);
            	response.addCookie(loginCookie);
        	}
        	response.sendRedirect("login.html");
        }
    
    }
    

    There is no method to remove the cookie but we can set the maximum age to 0 so that it will be deleted from client browser immediately. When we run above application, we get response like below images. Session Management in Java using Cookies Java Servlet Session Management using Cookies

  7. Session in Java Servlet - HttpSession

    Servlet API provides Session management through HttpSession interface. We can get session from HttpServletRequest object using following methods. HttpSession allows us to set objects as attributes that can be retrieved in future requests.

    1. HttpSession getSession() - This method always returns a HttpSession object. It returns the session object attached with the request, if the request has no session attached, then it creates a new session and return it.
    2. HttpSession getSession(boolean flag) - This method returns HttpSession object if request has session else it returns null.

    Some of the important methods of HttpSession are:

    1. String getId() - Returns a string containing the unique identifier assigned to this session.
    2. Object getAttribute(String name) - Returns the object bound with the specified name in this session, or null if no object is bound under the name. Some other methods to work with Session attributes are getAttributeNames(), removeAttribute(String name) and setAttribute(String name, Object value).
    3. long getCreationTime() - Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT. We can get last accessed time with getLastAccessedTime() method.
    4. setMaxInactiveInterval(int interval) - Specifies the time, in seconds, between client requests before the servlet container will invalidate this session. We can get session timeout value from getMaxInactiveInterval() method.
    5. ServletContext getServletContext() - Returns ServletContext object for the application.
    6. boolean isNew() - Returns true if the client does not yet know about the session or if the client chooses not to join the session.
    7. void invalidate() - Invalidates this session then unbinds any objects bound to it.

    When we use HttpServletRequest getSession() method and it creates a new request, it creates the new HttpSession object and also add a Cookie to the response object with name JSESSIONID and value as session id. This cookie is used to identify the HttpSession object in further requests from client. If the cookies are disabled at client side and we are using URL rewriting then this method uses the jsessionid value from the request URL to find the corresponding session. JSESSIONID cookie is used for session tracking, so we should not use it for our application purposes to avoid any session related issues. Let’s see example of session management using HttpSession object. We will create a dynamic web project in Eclipse with servlet context as ServletHttpSessionExample. The project structure will look like below image. HttpSession servlet session management login.html is same like earlier example and defined as welcome page for the application in web.xml LoginServlet servlet will create the session and set attributes that we can use in other resources or in future requests.

    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String userID = "admin";
    	private final String password = "password";
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		// get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			HttpSession session = request.getSession();
    			session.setAttribute("user", "Pankaj");
    			//setting session to expiry in 30 mins
    			session.setMaxInactiveInterval(30*60);
    			Cookie userName = new Cookie("user", user);
    			userName.setMaxAge(30*60);
    			response.addCookie(userName);
    			response.sendRedirect("LoginSuccess.jsp");
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    		}
    
    	}
    
    }
    

    Our LoginSuccess.jsp code is given below.

    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    String user = null;
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }else user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    	if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
    <br>
    User=<%=user %>
    <br>
    <a href="CheckoutPage.jsp">Checkout Page</a>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    When a JSP resource is used, container automatically creates a session for it, so we can’t check if session is null to make sure if user has come through login page, so we are using session attribute to validate request. CheckoutPage.jsp is another page and it’s code is given below.

    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, do the checkout.</h3>
    <br>
    <form action="LogoutServlet" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    

    Our LogoutServlet code is given below.

    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LogoutServlet
     */
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        	response.setContentType("text/html");
        	Cookie[] cookies = request.getCookies();
        	if(cookies != null){
        	for(Cookie cookie : cookies){
        		if(cookie.getName().equals("JSESSIONID")){
        			System.out.println("JSESSIONID="+cookie.getValue());
        			break;
        		}
        	}
        	}
        	//invalidate the session if exists
        	HttpSession session = request.getSession(false);
        	System.out.println("User="+session.getAttribute("user"));
        	if(session != null){
        		session.invalidate();
        	}
        	response.sendRedirect("login.html");
        }
    
    }
    

    Notice that I am printing JSESSIONID cookie value in logs, you can check server log where it will be printing the same value as Session Id in LoginSuccess.jsp Below images shows the execution of our web application. Session in Java Servlet web application HttpSession Session in Java Servlet web application Session in Java Servlet web application destroy

  8. Session Management in Java Servlet - URL Rewriting

    As we saw in last section that we can manage a session with HttpSession but if we disable the cookies in browser, it won’t work because server will not receive the JSESSIONID cookie from client. Servlet API provides support for URL rewriting that we can use to manage session in this case. The best part is that from coding point of view, it’s very easy to use and involves one step - encoding the URL. Another good thing with Servlet URL Encoding is that it’s a fallback approach and it kicks in only if browser cookies are disabled. We can encode URL with HttpServletResponse encodeURL() method and if we have to redirect the request to another resource and we want to provide session information, we can use encodeRedirectURL() method. We will create a similar project like above except that we will use URL rewriting methods to make sure session management works fine even if cookies are disabled in browser. ServletSessionURLRewriting project structure in eclipse looks like below image. Session in Java Servlet URL Rewriting

    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    import java.io.PrintWriter;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LoginServlet
     */
    @WebServlet("/LoginServlet")
    public class LoginServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    	private final String userID = "admin";
    	private final String password = "password";
    
    	protected void doPost(HttpServletRequest request,
    			HttpServletResponse response) throws ServletException, IOException {
    
    		// get request parameters for userID and password
    		String user = request.getParameter("user");
    		String pwd = request.getParameter("pwd");
    		
    		if(userID.equals(user) && password.equals(pwd)){
    			HttpSession session = request.getSession();
    			session.setAttribute("user", "Pankaj");
    			//setting session to expiry in 30 mins
    			session.setMaxInactiveInterval(30*60);
    			Cookie userName = new Cookie("user", user);
    			response.addCookie(userName);
    			//Get the encoded URL string
    			String encodedURL = response.encodeRedirectURL("LoginSuccess.jsp");
    			response.sendRedirect(encodedURL);
    		}else{
    			RequestDispatcher rd = getServletContext().getRequestDispatcher("/login.html");
    			PrintWriter out= response.getWriter();
    			out.println("<font color=red>Either user name or password is wrong.</font>");
    			rd.include(request, response);
    		}
    
    	}
    
    }
    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    //allow access only if session exists
    String user = null;
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }else user = (String) session.getAttribute("user");
    String userName = null;
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    	if(cookie.getName().equals("JSESSIONID")) sessionID = cookie.getValue();
    }
    }else{
    	sessionID = session.getId();
    }
    %>
    <h3>Hi <%=userName %>, Login successful. Your Session ID=<%=sessionID %></h3>
    <br>
    User=<%=user %>
    <br>
    <!-- need to encode all the URLs where we want session information to be passed -->
    <a href="<%=response.encodeURL("CheckoutPage.jsp") %>">Checkout Page</a>
    <form action="<%=response.encodeURL("LogoutServlet") %>" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    
    <%@ page language="java" contentType="text/html; charset=US-ASCII"
        pageEncoding="US-ASCII"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "https://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
    <title>Login Success Page</title>
    </head>
    <body>
    <%
    String userName = null;
    //allow access only if session exists
    if(session.getAttribute("user") == null){
    	response.sendRedirect("login.html");
    }else userName = (String) session.getAttribute("user");
    String sessionID = null;
    Cookie[] cookies = request.getCookies();
    if(cookies !=null){
    for(Cookie cookie : cookies){
    	if(cookie.getName().equals("user")) userName = cookie.getValue();
    }
    }
    %>
    <h3>Hi <%=userName %>, do the checkout.</h3>
    <br>
    <form action="<%=response.encodeURL("LogoutServlet") %>" method="post">
    <input type="submit" value="Logout" >
    </form>
    </body>
    </html>
    
    package com.journaldev.servlet.session;
    
    import java.io.IOException;
    
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.Cookie;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import javax.servlet.http.HttpSession;
    
    /**
     * Servlet implementation class LogoutServlet
     */
    @WebServlet("/LogoutServlet")
    public class LogoutServlet extends HttpServlet {
    	private static final long serialVersionUID = 1L;
           
        protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        	response.setContentType("text/html");
        	Cookie[] cookies = request.getCookies();
        	if(cookies != null){
        	for(Cookie cookie : cookies){
        		if(cookie.getName().equals("JSESSIONID")){
        			System.out.println("JSESSIONID="+cookie.getValue());
        		}
        		cookie.setMaxAge(0);
        		response.addCookie(cookie);
        	}
        	}
        	//invalidate the session if exists
        	HttpSession session = request.getSession(false);
        	System.out.println("User="+session.getAttribute("user"));
        	if(session != null){
        		session.invalidate();
        	}
        	//no encoding because we have invalidated the session
        	response.sendRedirect("login.html");
        }
    
    }
    

    When we run this project keeping cookies disabled in the browser, below images shows the response pages, notice the jsessionid in URL of browser address bar. Also notice that on LoginSuccess page, user name is null because browser is not sending the cookie send in the last response. Session in Java URL Rewriting Session Management in Java URL Rewriting Session in Java URL Rewriting Logout If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.

Thats all for session management in java servlets, we will look into Servlet Filters and Listeners and Cookies in future articles. Update: Check out next article in the series Servlet Filter.

Download Projects

Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.

Learn more about our products

About the author(s)

Category:
Tutorial

While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.

Still looking for an answer?

Ask a questionSearch for more help

Was this helpful?
 
JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 13, 2013

i had implemented the example following above steps. coming to this line : response.sendRedirect(“LoginSuccess.jsp”); i was getting http 404 error .can you please help me.

- krishna

JournalDev
DigitalOcean Employee
DigitalOcean Employee badge
August 13, 2013

404 error comes when requested resource is not available, please check if LoginSuccess.jsp is present in the root of your web application. Are you deploying directly to Tomcat from Eclipse or you are exporting as WAR file and then deploying it?

- Pankaj

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 20, 2013

    Hi, Interesting article. I’ve tried it and it does work. I thought that it was not possible to set a session attribute and then do a response.sendRedirect without loosing the attribute set in the session. /Gunnar

    - Gunnar Boström

    JournalDev
    DigitalOcean Employee
    DigitalOcean Employee badge
    August 21, 2013

    It’s because the session is still valid and when client send further requests and we call getSession(), we get the same session and it has the attribute in it.

    - Pankaj

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 29, 2013

      how to maintain session between login and logout if i DO session.invalidate(); for logout page but when i press back button browser at the time show information between login and logout….? plz sir how to stop show information after log-out plz tell me…. i m waiting u response ……

      - naveen

      JournalDev
      DigitalOcean Employee
      DigitalOcean Employee badge
      August 30, 2013

      You need to tell browser not to cache the page, you can do this with below code. response.setHeader("Cache-Control", "no-cache, no-store, must-revalidate"); // HTTP 1.1. response.setHeader("Pragma", "no-cache"); // HTTP 1.0. ``` `` response.setDateHeader("Expires", 0); // Proxies. `If there are several pages, best way to do is create a Filter where you will add these headers in response and configure the filter for all the URIs you don't want to be cached.` `` ```

      - Pankaj

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 2, 2013

        Hi, the example which you have demonstrated for URLRewriting is not exact.The idea of rewriting is you will append the sessionid which you have set in session.setatttribute along with the response.But you have not done anything like that in URL rewriting.Please clarify.

        - indra

        JournalDev
        DigitalOcean Employee
        DigitalOcean Employee badge
        September 2, 2013

        Hi Indra, The concept of URL rewriting is to add the session id in the URLs, servlet response encodeURL and encodeRedirectURL does the same thing for us behind the scene IF cookies are disabled. So basically it’s the same thing where we are using Servlet API for URL rewriting.

        - Pankaj

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 4, 2013

          Thanks for your tutorials. Very well-prepared and explained. Look forward to reading your future posts.

          - michael

          JournalDev
          DigitalOcean Employee
          DigitalOcean Employee badge
          September 4, 2013

          Thanks Michael, these positive comments push me in continuing my effort.

          - Pankaj

            JournalDev
            DigitalOcean Employee
            DigitalOcean Employee badge
            September 16, 2013

            Fantastic Job broo… keep posting

            - Gowtham

              JournalDev
              DigitalOcean Employee
              DigitalOcean Employee badge
              October 16, 2013

              Can you please explain shopping cart using 3-tier architecture in netbeans 7.3.1?

              - jagroop singh

                JournalDev
                DigitalOcean Employee
                DigitalOcean Employee badge
                October 24, 2013

                Thanks Pankaj Great way to explain with the output, it really helps the beginner to learn new things. Looking forward to some new examples on Springs and other Technology.

                - James

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  November 5, 2013

                  hi, will u please provide some examples to insert login and logout timings into SQL Server database using jsps? Thank you

                  - deepthi

                  JournalDev
                  DigitalOcean Employee
                  DigitalOcean Employee badge
                  November 11, 2013

                  JSPs should not contain business logic, that is a bad programming model. For DB Operations example read this post https://www.journaldev.com/1997/servlet-example-in-java-with-database-connection-and-log4j-integration

                  - Pankaj

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 6, 2013

                    I must be missing something, because I don’t understand why you need to store the user’s name in a cookie. Couldn’t this simply be set in the session (session.setAttribute(“user”, user) )? Also, isn’t this still vulnerable to a theft of the session ID (i.e., if somebody simply steals my session ID cookie, they will then authenticate as me)? Am I correct in thinking that the session data remains stored on the server and is not available on the client? Thanks.

                    - H S J

                    JournalDev
                    DigitalOcean Employee
                    DigitalOcean Employee badge
                    November 11, 2013

                    HttpSession work on Cookies only and it adds a cookie jsessionid with some random generated value for the session id. Please read the post again clearly, cookies can be used for session management but as you stated that if the logic is simple then anyone can hack it. That’s why we should use the Servlet API HttpSession for session management.

                    - Pankaj

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 30, 2013

                      Your tutorial is very resourceful for beginners like me. If you dont mind can i suggest if you could explain the concepts while using different variable names. For eg. in URL rewriting you have used the variable “user” repeatedly for different purposes to “setattribute”, “cookie request” etc. If you could use different variables like user, uid, usid etc. it would be easier for beginners like me to understand the code in one go. Thanks, Vinay Shetty

                      - Vinay Shetty

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 30, 2013

                      also can you please explain this line. " for(Cookie cookie : cookies) " What does this line do in a for loop? I don’t know about this kind of syntax…

                      - Vinay Shetty

                      JournalDev
                      DigitalOcean Employee
                      DigitalOcean Employee badge
                      November 30, 2013

                      This is the improved for loop where we can traverse through collection or array easily. Its as replacement of for(int i=0; i

                      - Pankaj

                        JournalDev
                        DigitalOcean Employee
                        DigitalOcean Employee badge
                        November 30, 2013

                        Hmm makes sense, I will try to keep different variable names going forward.

                        - Pankaj

                          JournalDev
                          DigitalOcean Employee
                          DigitalOcean Employee badge
                          December 5, 2013

                          Hi Pankaj, Nice explanation. Keep up the good work.

                          - Yuga

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            December 7, 2013

                            hi Pankaj, thanks for your tutorial :D but i have problem,in chrome it doesn’t work. pliz help me :)

                            - David

                            JournalDev
                            DigitalOcean Employee
                            DigitalOcean Employee badge
                            December 7, 2013

                            what do you mean that it doesn’t work in Chrome?

                            - Pankaj

                              JournalDev
                              DigitalOcean Employee
                              DigitalOcean Employee badge
                              December 28, 2013

                              Its General.Use Firefox or IE instead.

                              - jagdish tiwari

                                JournalDev
                                DigitalOcean Employee
                                DigitalOcean Employee badge
                                January 6, 2014

                                with your tutorial script,in firefox has working. but in chrome the url cannot rewrite session id. thanks

                                - David

                                  JournalDev
                                  DigitalOcean Employee
                                  DigitalOcean Employee badge
                                  December 20, 2013

                                  i want to create session id and that id will stored into a database

                                  - vajjapelli raju

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    February 10, 2014

                                    Thanks very much for the article, this is very thorough and informative. I have two questions if I may. First, you mentioned that by using url encoding, we can manage session data even if cookies are disabled. In the code, you still use cookies though - why is it that it’s possible to use cookies with url encoding ? My second question, is it necessary to use Java code in jsp pages to retrieve cookie information ? The data couldn’t be retrieved by e.g. javascript ? Thank you

                                    - Brian Forbes

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    February 10, 2014

                                    We are still using Cookie because we don’t know if the Client browser accepts Cookies or not. So URL rewriting will come for rescue when cookies are disabled for any browser. Regarding retrieving Cookies in JSP pages, we should never use Scriptlets. Since it’s a example, I am using Java code to keep it simple and not overwhelm with lots of information. We can use JSP EL cookie implicit object for this. Read more at https://www.journaldev.com/2064/jsp-expression-language-el-example-tutorial

                                    - Pankaj

                                    JournalDev
                                    DigitalOcean Employee
                                    DigitalOcean Employee badge
                                    February 19, 2014

                                    Thanks for your reply ! This makes sense. Thanks for the excellent article, very well written and easy to understand.

                                    - Brian Forbes

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      February 18, 2014

                                      Hi Pankaj, What happens if the user forgets to logout/closes the browser and login from another browser or machine? Is it being handled and how is it handled?

                                      - Ricky

                                      JournalDev
                                      DigitalOcean Employee
                                      DigitalOcean Employee badge
                                      February 18, 2014

                                      Same browser logins depend on cookies timeout. For different browser and machine, you need to login again because cookies are not there.

                                      - Pankaj

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        February 21, 2014

                                        Hi Pankaj, My question is from URL Rewriting. Question is, Suppose a session object is created at server side and we use URL Rewriting for maintaining session. After that I close my browser but session object at the server side is still there(not timed out). then again I open the browser goto the history and click on the link in which Jsesionid is attached. I still get acccess to the resource(either cookies enabled or disabled). Even though I copy the link and paste it to another browser then also i access due to publicly supplying jsessionid as url. So i need help how I make website secure while I using URLRewriting…

                                        - Rahul Kumar

                                        JournalDev
                                        DigitalOcean Employee
                                        DigitalOcean Employee badge
                                        February 21, 2014

                                        In that case, you can keep request client IP and browser information in the session attributes and when request arrives, check them in the filter to make sure they match.

                                        - Pankaj

                                          JournalDev
                                          DigitalOcean Employee
                                          DigitalOcean Employee badge
                                          March 7, 2014

                                          Consider using hidden form fields instead for session tracking. These dont show up in the url

                                          - andrew

                                            JournalDev
                                            DigitalOcean Employee
                                            DigitalOcean Employee badge
                                            March 4, 2014

                                            Pankaj, I always learn new things from your article. Super work !!!

                                            - shahrooh

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              March 9, 2014

                                              your tutorial is very good. example are also good. provide some real time example (on authentication, session, logout and others that is used in making site) like we making real time company project. we take care of all these things that is mention above(auth, session etc…) in project. so we can know how it work in real time. like how facebook,twitter session works.

                                              - Ankur

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              March 10, 2014

                                              Real life projects are more complex and if I put 10K lines of code here, that will not be a guide or tutorial. You should knows the basics and have the idea of how things work and then build over it based on your requirements.

                                              - Pankaj

                                              JournalDev
                                              DigitalOcean Employee
                                              DigitalOcean Employee badge
                                              April 17, 2015

                                              For a newbie it is awesome tutorial to understand how session works. And if we talk about spring and struts f/w’s , they are also using this type of mechanisms in optimized way. Keep it up pankaj…

                                              - Sagar Mali

                                                JournalDev
                                                DigitalOcean Employee
                                                DigitalOcean Employee badge
                                                March 21, 2014

                                                Hi, I tried this example. After successfully loged in, when i close the browser, and reopen it, my session expires and make me to log in again. Can you please tell me that even if we set age of cookie, why the session get expires. I should allow me to remain loged in.

                                                - Nakul

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  April 1, 2014

                                                  Very helpful article. It really cleared my basic idea about sessions and cookies. I am having really hard time understanding login process using Facebook API specially access token mechanism and logout process. After reading this tutorial, I am sure you will write a great tutorial explaining a simple(if it is!) login-logout process in a Java based web app using Facebook API. Thank you for this tutorial.

                                                  - Murtuza

                                                  JournalDev
                                                  DigitalOcean Employee
                                                  DigitalOcean Employee badge
                                                  April 4, 2014

                                                  Hi Pankaj, Thanks for ur tutorial, but i am facing some problem when i am navigating from one server to another in case of URL rewriting(cookie disabled). For eg, when coming back to shopping site after making payment at bank site the initial session id is not retained. It’s showing different session id. Could u please help me. Thanks in advance Aishwarya Singh, pune

                                                  - Aishwarya Singh

                                                    JournalDev
                                                    DigitalOcean Employee
                                                    DigitalOcean Employee badge
                                                    April 4, 2014

                                                    Thanks for the tutorial. It gives a very good understanding and idea of all the various concepts. It always helps me prep for my interviews. Thanks again and continue posting and sharing the knowledge.

                                                    - Anonym

                                                      JournalDev
                                                      DigitalOcean Employee
                                                      DigitalOcean Employee badge
                                                      April 19, 2014

                                                      Hi Pankaj, With the existing session management we also have to make the Cookie Secure using setSecure() and Httponly flag.

                                                      - HIMANSU NAYAK

                                                        JournalDev
                                                        DigitalOcean Employee
                                                        DigitalOcean Employee badge
                                                        April 21, 2014

                                                        can you post source code of this tutorial again. i cant get link download above. thanks

                                                        - tinhvh55

                                                          JournalDev
                                                          DigitalOcean Employee
                                                          DigitalOcean Employee badge
                                                          April 28, 2014

                                                          Hi! Great tutorial! When i’ve logged in, log out and then goes to the home-page, i get a nullPointerException. Do you know what might be the problem?

                                                          - Robin

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            May 3, 2014

                                                            Hi, I am testing with your code posted above in tutorial it is understanding very clearly… but i am getting an 404 error in webpage. (Servlet 3.0 Annotations) “message /SessionMgCooki/LoginServlet description The requested resource (/SessionMgCooki/LoginServlet) is not available.” This is my problem… Thanks.

                                                            - Prabhu.g

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            May 3, 2014

                                                            URI is not right, check the configuration for correct URI.

                                                            - Pankaj

                                                            JournalDev
                                                            DigitalOcean Employee
                                                            DigitalOcean Employee badge
                                                            May 3, 2014

                                                            Ya sir. I have check the URI. but the same 404 response from server.

                                                            - Prabhu.g

                                                              JournalDev
                                                              DigitalOcean Employee
                                                              DigitalOcean Employee badge
                                                              May 3, 2014

                                                              Pankaj Sir, as per above example n article its very knowledgeable i want use with database can u help me for above example how to use with database it my pleasure to if u guide me… thnks in advance…

                                                              - Jiral Dekhtawala

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                May 26, 2014

                                                                Sir, I have read the tutorial and i want to thnakyou for writing this tutorial.It is really helpful. I have a question to ask that how can i disable the back button after the logout button is clicked. As for now when i click the back button in the browser then it goes to the LoginSuccess page which we dont want. So, how can i prevent that. Thanks in advance.

                                                                - Saurabh

                                                                JournalDev
                                                                DigitalOcean Employee
                                                                DigitalOcean Employee badge
                                                                May 26, 2014

                                                                When you click back button, browser uses the cache to load the page. So there is nothing we can do from server side, however we can add javascript code to detect back button usage and forward to login page.

                                                                - Pankaj

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  May 28, 2014

                                                                  Hi sir,iam having small doubt related to SessionManagement and Servlet Listeners.Question is whenever User is Directly Closing the Browser Window,how do we made session.invalidate() or some changes in database side,how to do sir?please help me Sir.

                                                                  - Venkata Sriram

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  May 28, 2014

                                                                  When user is closing window, you can’t do anything at server side. However we use cookies for session tracking and if you set the cookie to expire as soon as browser is closed, it will invalidate automatically.

                                                                  - Pankaj

                                                                  JournalDev
                                                                  DigitalOcean Employee
                                                                  DigitalOcean Employee badge
                                                                  May 28, 2014

                                                                  Hi sir thanks for reply but iam not using cookies explicitly for session handling sir.by using servletListener Events (HttpSessionEvent) also we cant perform any updation of status or something in database level sir.Correct me if iam wrong.Thanks Venkata Sriram

                                                                  - Venkata Sriram

                                                                    JournalDev
                                                                    DigitalOcean Employee
                                                                    DigitalOcean Employee badge
                                                                    June 11, 2014

                                                                    Hi pankaj, Thanks a lot. It works…!!.. :-) :-) continue your work…!!

                                                                    - Rebecca

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      June 20, 2014

                                                                      i have one doubt,how much data can store in session and cookies exactly can u tel me briefly

                                                                      - rahul

                                                                      JournalDev
                                                                      DigitalOcean Employee
                                                                      DigitalOcean Employee badge
                                                                      June 22, 2014

                                                                      It all depends on the memory for session data, you should keep it small to avoid memory issues. You can have many cookies but its value size is limited. Also it will add network overhead because it will be sent from both sides in every request and response, so you should keep it small.

                                                                      - Pankaj

                                                                        JournalDev
                                                                        DigitalOcean Employee
                                                                        DigitalOcean Employee badge
                                                                        July 22, 2014

                                                                        sir muze ek system pe kitne log har din me browser pe something search karte hai unka count banana hai to plz give me any suggestions.

                                                                        - tushar

                                                                          JournalDev
                                                                          DigitalOcean Employee
                                                                          DigitalOcean Employee badge
                                                                          July 27, 2014

                                                                          I have downloaded your files and tried to run the program in eclipse but whenever I submit the form from the login.html, I got this error: HTTP Status 404 - /practice/LogoutServlet. I have checked that I have all of your files (jsp, html, web, and java) locate in the same folder as yours but it still gives me this error. Please help me.

                                                                          - Derek Nguyen

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            August 6, 2014

                                                                            This examples looks good, but non of your examples work, after I login using admin and password I got a 404 error and import javax.servlet.annotation.WebServlet; and @WebServlet(“/LoginServlet”) give me an error, I try deleting them, I downloaded your examples, and import it in eclipse, I also copied and pasted them, I typed them and the same error 404. I like the definitions and the concepts use, but the example does not work.

                                                                            - JS

                                                                            JournalDev
                                                                            DigitalOcean Employee
                                                                            DigitalOcean Employee badge
                                                                            August 6, 2014

                                                                            Is your servlet container supports Servlet Spec 3? If not you will get these errors, try using Tomcat 7. Also check server logs for exact issue.

                                                                            - Pankaj

                                                                              JournalDev
                                                                              DigitalOcean Employee
                                                                              DigitalOcean Employee badge
                                                                              August 20, 2014

                                                                              Thanks for the article “If cookies are not disabled, you won’t see jsessionid in the URL because Servlet Session API will use cookies in that case.” i didnt understand this, please elloborate

                                                                              - micheal

                                                                                JournalDev
                                                                                DigitalOcean Employee
                                                                                DigitalOcean Employee badge
                                                                                August 25, 2014

                                                                                Hi I was trying Httpsession example but while running it Im getting value as null.Please help

                                                                                - farah

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  September 24, 2014

                                                                                  Hi Sir, i want to remove .jsp extension from url in my java web application. I tried servlet mapping tag in web.xml file and i also tried to define my jsp file as servlet in web.xml file but its not working… so please give me some solution… thanks in advance…

                                                                                  - Sultan Khan

                                                                                  JournalDev
                                                                                  DigitalOcean Employee
                                                                                  DigitalOcean Employee badge
                                                                                  November 20, 2014

                                                                                  Start learning struts… u can do this and many more thing very easily…

                                                                                  - Amit

                                                                                    JournalDev
                                                                                    DigitalOcean Employee
                                                                                    DigitalOcean Employee badge
                                                                                    September 29, 2014

                                                                                    i am working on a web application project…the problem is that when i deploy then it runs good…the problem is that when i enter my inside page which must open after login but they open…so what can i do for this???

                                                                                    - Roopam

                                                                                      JournalDev
                                                                                      DigitalOcean Employee
                                                                                      DigitalOcean Employee badge
                                                                                      October 5, 2014

                                                                                      thank you so much sir

                                                                                      - rajeswari

                                                                                        JournalDev
                                                                                        DigitalOcean Employee
                                                                                        DigitalOcean Employee badge
                                                                                        October 11, 2014

                                                                                        Thanks… it’s nice

                                                                                        - Chetana

                                                                                          JournalDev
                                                                                          DigitalOcean Employee
                                                                                          DigitalOcean Employee badge
                                                                                          October 11, 2014

                                                                                          thanks sir … for session tutorial ,…

                                                                                          - amit

                                                                                            JournalDev
                                                                                            DigitalOcean Employee
                                                                                            DigitalOcean Employee badge
                                                                                            October 13, 2014

                                                                                            Hi, I m new to session management. I have a couple of questions. 1) In Session Management with HttpSession topic above, user name is set on both cookie and session. I don’t understand why do we have to set in both. Why cant we use only session object? 2) How to maintain the same session for multiple http requests? for example, on page refresh i need to access the value in the previously created session.

                                                                                            - Saravanan

                                                                                              JournalDev
                                                                                              DigitalOcean Employee
                                                                                              DigitalOcean Employee badge
                                                                                              October 16, 2014

                                                                                              Session Management with HttpSession LoginServlet.java Line number 33 session.setAttribute(“user”, “Pankaj”); can someone explain why use name pankaj in setAttribute

                                                                                              - zoyeb

                                                                                                JournalDev
                                                                                                DigitalOcean Employee
                                                                                                DigitalOcean Employee badge
                                                                                                October 21, 2014

                                                                                                Good one

                                                                                                - Ashok Korlakunta

                                                                                                  JournalDev
                                                                                                  DigitalOcean Employee
                                                                                                  DigitalOcean Employee badge
                                                                                                  November 8, 2014

                                                                                                  Hi Sir… After logout, I m able to back page. But I want when we press back button it redirect to login page not back to loginsuccess page after logout.

                                                                                                  - sud

                                                                                                    JournalDev
                                                                                                    DigitalOcean Employee
                                                                                                    DigitalOcean Employee badge
                                                                                                    December 2, 2014

                                                                                                    Here is below what i am doing while(rs.next()){ LoadQueueProperties prop = new LoadQueueProperties(); prop.setGuid(rs.getString(“guid”)); prop.setHost_name(rs.getString(“host_name”)); prop.setColl_name(rs.getString(“collection_name”)); prop.setStage_id(rs.getInt(“stage_id”)); prop.setClient_name(rs.getString(“client_name”)); prop.setStatus_code(rs.getInt(“status_code”)); list.add(prop); } HttpSession session = request.getSession(); session.setAttribute(“loadQueueList”, list); response.sendRedirect(“LoadQueue.jsp”); in the jsp i am donig as below ${list.guid} ${list.host_name} ${list.coll_name} ${list.stage_id} but loadQueueList is coming as empty Any solution?

                                                                                                    - swapnajit

                                                                                                      JournalDev
                                                                                                      DigitalOcean Employee
                                                                                                      DigitalOcean Employee badge
                                                                                                      January 16, 2015

                                                                                                      Hatts Off…!

                                                                                                      - puff

                                                                                                        JournalDev
                                                                                                        DigitalOcean Employee
                                                                                                        DigitalOcean Employee badge
                                                                                                        January 19, 2015

                                                                                                        Really very good explanation with good example. Can you please tell me, By default which approach is used to maintain session by a web server like Apache tomcat?

                                                                                                        - Ankit

                                                                                                          JournalDev
                                                                                                          DigitalOcean Employee
                                                                                                          DigitalOcean Employee badge
                                                                                                          March 16, 2015

                                                                                                          Good tutorial Sir, looking forward for the future posts.

                                                                                                          - shams

                                                                                                            JournalDev
                                                                                                            DigitalOcean Employee
                                                                                                            DigitalOcean Employee badge
                                                                                                            April 2, 2015

                                                                                                            You sir, are the real MVP. Thank you so much, amazing tutorial!

                                                                                                            - Luis Delgado

                                                                                                              Try DigitalOcean for free

                                                                                                              Click below to sign up and get $200 of credit to try our products over 60 days!

                                                                                                              Sign up

                                                                                                              Join the Tech Talk
                                                                                                              Success! Thank you! Please check your email for further details.

                                                                                                              Please complete your information!

                                                                                                              Congratulations on unlocking the whale ambience easter egg!

                                                                                                              Click the whale button in the bottom left of your screen to toggle some ambient whale noises while you read.

                                                                                                              Thank you to the Glacier Bay National Park & Preserve and Merrick079 for the sounds behind this easter egg.

                                                                                                              Interested in whales, protecting them, and their connection to helping prevent climate change? We recommend checking out the Whale and Dolphin Conservation.

                                                                                                              Become a contributor for community

                                                                                                              Get paid to write technical tutorials and select a tech-focused charity to receive a matching donation.

                                                                                                              DigitalOcean Documentation

                                                                                                              Full documentation for every DigitalOcean product.

                                                                                                              Resources for startups and SMBs

                                                                                                              The Wave has everything you need to know about building a business, from raising funding to marketing your product.

                                                                                                              Get our newsletter

                                                                                                              Stay up to date by signing up for DigitalOcean’s Infrastructure as a Newsletter.

                                                                                                              New accounts only. By submitting your email you agree to our Privacy Policy

                                                                                                              The developer cloud

                                                                                                              Scale up as you grow — whether you're running one virtual machine or ten thousand.

                                                                                                              Get started for free

                                                                                                              Sign up and get $200 in credit for your first 60 days with DigitalOcean.*

                                                                                                              *This promotional offer applies to new accounts only.