Skip to content

Instantly share code, notes, and snippets.

@PavloChechehov
Created June 29, 2022 19:35
Show Gist options
  • Save PavloChechehov/633ac6cb89767c4e9e104649670e57e0 to your computer and use it in GitHub Desktop.
Save PavloChechehov/633ac6cb89767c4e9e104649670e57e0 to your computer and use it in GitHub Desktop.
Evening Servlet with session
package com.pch;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import java.io.IOException;
@WebServlet("/evening")
public class EveningServlet extends HttpServlet {
private static final String greeting = "Good evening, %s!";
@Override
protected void doGet(HttpServletRequest req,
HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
String nameFromSession = (String) session.getAttribute("name");
String name = "Buddy";
var parameterMap = req.getParameterMap();
var queryParamName = parameterMap.get("name");
if (queryParamName != null && queryParamName[0] != null) {
name = queryParamName[0];
session.setAttribute("name", name);
} else if (nameFromSession != null) {
name = nameFromSession;
}
var writer = resp.getWriter();
writer.println(String.format(greeting, name));
writer.flush();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment