Skip to content

Instantly share code, notes, and snippets.

@PavloChechehov
Created June 29, 2022 19:32
Show Gist options
  • Save PavloChechehov/c2dd6450e5812e9c7a5f5a13d7411758 to your computer and use it in GitHub Desktop.
Save PavloChechehov/c2dd6450e5812e9c7a5f5a13d7411758 to your computer and use it in GitHub Desktop.
Custom session solution
package com.pch;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;
@WebServlet("/evening")
public class EveningServlet extends HttpServlet {
private static final String GREETING = "Good evening, %s!";
private static final String BUDDY = "Buddy";
private static final String CUSTOM_SESSION_ID = "CustomSessionId";
private final Map<String, String> sessionIdValues = new HashMap<>();
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
String paramValue = getQueryParamValue(req, "name");
String sessionId = saveToCustomSession(req, paramValue);
String value = getValue(sessionId, resp);
var writer = resp.getWriter();
writer.println(String.format(GREETING, value));
writer.flush();
}
private String saveToCustomSession(HttpServletRequest req,
String paramValue) {
String customSessionId = getCustomSessionId(req);
if (customSessionId == null) {
customSessionId = UUID.randomUUID().toString();
} else {
try {
UUID.fromString(customSessionId);
} catch (Exception e) {
System.out.println("Wrong format of custom session id ");
customSessionId = UUID.randomUUID().toString();
}
}
if (paramValue == null) {
String sessionValue = sessionIdValues.get(customSessionId);
paramValue = Objects.requireNonNullElse(sessionValue, BUDDY);
}
sessionIdValues.put(customSessionId, paramValue);
return customSessionId;
}
private String getQueryParamValue(HttpServletRequest req, String key) {
String value = null;
var parameterMap = req.getParameterMap();
var queryParamName = parameterMap.get(key);
if (queryParamName != null && queryParamName[0] != null) {
value = queryParamName[0];
}
return value;
}
public String getValue(String sessionId, HttpServletResponse resp) {
String value = sessionIdValues.get(sessionId);
resp.addCookie(new Cookie(CUSTOM_SESSION_ID, sessionId));
return value;
}
private String getCustomSessionId(HttpServletRequest req) {
String customSessionId = null;
for (Cookie cookie : req.getCookies()) {
if (cookie.getName().equals(CUSTOM_SESSION_ID)) {
customSessionId = cookie.getValue();
return customSessionId;
}
}
return customSessionId;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment