Skip to content

Loading…

Added session support. #12

Closed
wants to merge 4 commits into from

4 participants

@kumai

I want to use session in Spark, so I have written some code for session support with Jetty.

@Arnauld

Would be great to merge it!

@perwendel
Owner

HI, I'll have a look at this as soon as possible.
I'm a bit busy being on parental leave until august (takes more time than I thought...)
Br,
Per

@perwendel

Should throw IllegalArgumentException instead of Nullpointer.

@perwendel

I would like this to be removed and the attribute related methods in Session should be used instead. Would make more sense design wise.

@perwendel

I would like this to be removed and the attribute related methods in Session should be used instead. Would make more sense design wise.

@perwendel

Javadoc on public classes and methods.

@perwendel
Owner

Had a quick lock and added a few comments. Will look more on it when i get a "window"

@kumai

Thanks for your reply!

I've added some changes as you pointed out, so please check it out when you have time. :-)

@strigona

Any news on this pull request?

@perwendel
Owner

Sry, having a hard time finding the spare time to do this. Will try to have a look at this today.

@strigona

Thanks for the reply. To be honest, my need for this pull request isn't very significant as I've implemented my own session handling for my application.

@perwendel
Owner

Sorry for taking so long time. I've had attended ALOT of personal business lately which has kept me from working on Spark.

I've added these changes now. I found it easier to just copy and paste since github wouldn't let me merge it automatically! Thanks for a very nice contribution :-).

@perwendel perwendel closed this
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
View
36 src/main/java/spark/Request.java
@@ -26,6 +26,7 @@
import java.util.TreeSet;
import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpSession;
import spark.route.HttpMethod;
import spark.route.RouteMatch;
@@ -53,6 +54,8 @@
private Set<String> headers = null;
+ private Session session = null;
+
// request.body # request body sent by the client (see below), DONE
// request.scheme # "http" DONE
// request.path_info # "/foo", DONE
@@ -298,5 +301,36 @@ public HttpServletRequest raw() {
}
return Collections.unmodifiableMap(params);
}
-
+
+ /**
+ * Returns the current session associated with this request,
+ * or if the request does not have a session, creates one.
+ *
+ * @return the session associated with this request
+ */
+ public Session session() {
+ if (session == null) {
+ session = new Session(servletRequest.getSession());
+ }
+ return session;
+ }
+
+ /**
+ * Returns the current session associated with this request, or if there is
+ * no current session and <code>create</code> is true, returns a new session.
+ *
+ * @param create <code>true</code> to create a new session for this request if necessary;
+ * <code>false</code> to return null if there's no current session
+ * @return the session associated with this request or <code>null</code> if
+ * <code>create</code> is <code>false</code> and the request has no valid session
+ */
+ public Session session(boolean create) {
+ if (session == null) {
+ HttpSession httpSession = servletRequest.getSession(create);
+ if (httpSession != null) {
+ session = new Session(httpSession);
+ }
+ }
+ return session;
+ }
}
View
131 src/main/java/spark/Session.java
@@ -0,0 +1,131 @@
+package spark;
+
+import java.util.Enumeration;
+import java.util.Set;
+import java.util.TreeSet;
+
+import javax.servlet.http.HttpSession;
+
+/**
+ * Provides session information.
+ */
+public class Session {
+
+ private HttpSession session;
+
+ /**
+ * Creates a session with the <code>HttpSession</code>.
+ * @param session
+ * @throws IllegalArgumentException If the session is null.
+ */
+ Session(HttpSession session) throws IllegalArgumentException {
+ if (session == null) {
+ throw new IllegalArgumentException("session cannot be null");
+ }
+ this.session = session;
+ }
+
+ /**
+ * Returns the raw <code>HttpSession</code> object handed in by the servlet container.
+ */
+ public HttpSession raw() {
+ return session;
+ }
+
+ /**
+ * Returns the object bound with the specified name in this session, or null if no object is bound under the name.
+ *
+ * @param name a string specifying the name of the object
+ * @return the object with the specified name
+ */
+ @SuppressWarnings("unchecked")
+ public <T> T attribute(String name) {
+ return (T) session.getAttribute(name);
+ }
+
+ /**
+ * Binds an object to this session, using the name specified.
+ *
+ * @param name the name to which the object is bound; cannot be null
+ * @param value the object to be bound
+ */
+ public void attribute(String name, Object value) {
+ session.setAttribute(name, value);
+ }
+
+ /**
+ * Returns an <code>Enumeration</code> of <code>String</code> objects
+ * containing the names of all the objects bound to this session.
+ */
+ @SuppressWarnings("unchecked")
+ public Set<String> attributes() {
+ TreeSet<String> attributes = new TreeSet<String>();
+ Enumeration<String> enumeration = session.getAttributeNames();
+ while (enumeration.hasMoreElements()) {
+ attributes.add(enumeration.nextElement());
+ }
+ return attributes;
+ }
+
+ /**
+ * Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
+ */
+ public long creationTime() {
+ return session.getCreationTime();
+ }
+
+ /**
+ * Returns a string containing the unique identifier assigned to this session.
+ */
+ public String id() {
+ return session.getId();
+ }
+
+ /**
+ * Returns the last time the client sent a request associated with this session,
+ * as the number of milliseconds since midnight January 1, 1970 GMT, and marked
+ * by the time the container received the request.
+ */
+ public long lastAccessedTime() {
+ return session.getLastAccessedTime();
+ }
+
+ /**
+ * Returns the maximum time interval, in seconds, that the container
+ * will keep this session open between client accesses.
+ */
+ public int maxInactiveInterval() {
+ return session.getMaxInactiveInterval();
+ }
+
+ /**
+ * Specifies the time, in seconds, between client requests the web container will invalidate this session.
+ *
+ * @param interval
+ */
+ public void maxInactiveInterval(int interval) {
+ session.setMaxInactiveInterval(interval);
+ }
+
+ /**
+ * Invalidates this session then unbinds any objects bound to it.
+ */
+ public void invalidate() {
+ session.invalidate();
+ }
+
+ /**
+ * Returns true if the client does not yet know about the session or if the client chooses not to join the session.
+ */
+ public boolean isNew() {
+ return session.isNew();
+ }
+
+ /**
+ * Removes the object bound with the specified name from this session.
+ * @param name the name of the object to remove from this session
+ */
+ public void removeAttribute(String name) {
+ session.removeAttribute(name);
+ }
+}
View
7 src/main/java/spark/webserver/JettyHandler.java
@@ -24,7 +24,7 @@
import javax.servlet.http.HttpServletResponse;
import org.eclipse.jetty.server.Request;
-import org.eclipse.jetty.server.handler.AbstractHandler;
+import org.eclipse.jetty.server.session.SessionHandler;
import org.eclipse.jetty.util.log.Log;
/**
@@ -32,7 +32,7 @@
*
* @author Per Wendel
*/
-class JettyHandler extends AbstractHandler {
+class JettyHandler extends SessionHandler {
private Filter filter;
@@ -41,11 +41,12 @@ public JettyHandler(Filter filter) {
}
@Override
- public void handle(String target, Request baseRequest, HttpServletRequest request,
+ public void doHandle(String target, Request baseRequest, HttpServletRequest request,
HttpServletResponse response) throws IOException, ServletException {
Log.debug("jettyhandler, handle();");
filter.doFilter(request, response, null);
baseRequest.setHandled(true);
+ super.doHandle(target, baseRequest, request, response);
}
}
View
11 src/main/java/spark/webserver/RequestWrapper.java
@@ -21,6 +21,7 @@
import javax.servlet.http.HttpServletRequest;
import spark.Request;
+import spark.Session;
final class RequestWrapper extends Request {
@@ -150,4 +151,14 @@ public Object attribute(String attribute) {
return delegate.attributes();
}
+ @Override
+ public Session session() {
+ return delegate.session();
+ }
+
+ @Override
+ public Session session(boolean create) {
+ return delegate.session(create);
+ }
+
}
View
47 src/test/java/spark/examples/session/SessionExample.java
@@ -0,0 +1,47 @@
+package spark.examples.session;
+
+import static spark.Spark.*;
+
+import spark.Request;
+import spark.Response;
+import spark.Route;
+
+public class SessionExample {
+ private static final String SESSION_NAME = "username";
+
+ public static void main(String[] args) {
+ get(new Route("/") {
+ @Override
+ public Object handle(Request request, Response response) {
+ String name = request.session().attribute(SESSION_NAME);
+ if (name == null) {
+ return "<html><body>What's your name?: <form action=\"/entry\" method=\"POST\"><input type=\"text\" name=\"name\"/><input type=\"submit\" value=\"go\"/></form></body></html>";
+ } else {
+ return String.format("<html><body>Hello, %s!</body></html>", name);
+ }
+ }
+ });
+
+ post(new Route("/entry") {
+ @Override
+ public Object handle(Request request, Response response) {
+ String name = request.queryParams("name");
+ if (name != null) {
+ request.session().attribute(SESSION_NAME, name);
+ }
+ response.redirect("/");
+ return null;
+ }
+ });
+
+ get(new Route("/clear") {
+ @Override
+ public Object handle(Request request, Response response) {
+ request.session().removeAttribute(SESSION_NAME);
+ response.redirect("/");
+ return null;
+ }
+ });
+ }
+
+}
Something went wrong with that request. Please try again.