Skip to content

Instantly share code, notes, and snippets.

@raunakhajela
Created January 12, 2018 07:59
Show Gist options
  • Save raunakhajela/4fbaca6330832ba05898a45cc4986622 to your computer and use it in GitHub Desktop.
Save raunakhajela/4fbaca6330832ba05898a45cc4986622 to your computer and use it in GitHub Desktop.
JSP: Sessions - Writing Data
<!--
isNew() : boolean - returns true if the session is new
getId() : String - returns the session id
invalidate() : void - invalidates this session and unbinds any object associated with it
setMaxInactiveInterval(long mills) : void - sets the idle time for a session to expire, the value is supplied in milliseconds
-->
<%@ page import="java.util.*" %>
<html>
<body>
<!-- Step 1: Create html form -->
<form action="todo-demo.jsp">
Add new item: <input type="text" name="theItem" />
<input type="submit" value="Submit">
</form>
<!-- <br>
Item entered: <%= request.getParameter("theItem") %> -->
<!-- Step 2: add new item to "to do" list -->
<%
//get the todo items from the session
List<String> items = (List<String>) session.getAttribute("myTodoList");
//if the to do items doesn't exist, then create a new one
if (items == null) {
items = new ArrayList<String>();
session.setAttribute("myTodoList", items);
}
//see if there is form data to add
String theItem = request.getParameter("theItem");
if (theItem != null) {
items.add(theItem);
}
%>
<!-- Step 3: display all "to do" item from session -->
<hr>
<b>To do List Items:</b> <br>
<ol>
<%
for (String temp: items ) {
out.println("<li>" + temp + "</li>");
}
%>
</ol>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment