Custom ID in session handling by Java Servlet API

Is it possible to assign a custom ID to a HTTP session through Servlet API?

I know that session handling from any application server, Tomcat for example, it's enough good to generate unique IDs. But I have custom unique session IDs based on information per user and time, so it won't be repeated.

And I looked at every documentation about session handling but nowhere I find what I need.

It's a requirement for a project, so if it's not possible, I need to know the reasons (or it's only not available through API?).


Asked by: Stella972 | Posted: 28-01-2022






Answer 1

If you are using Tomcat, you may be able to create a custom session manager (see this discussion). You would then have access to the Tomcat Session object and could call setId.

Answered by: Briony459 | Posted: 01-03-2022



Answer 2

The servlet API does not support creating your own cookie value. In fact, it does not guarantee that sessions are maintained via cookies... it specifically states that they can be maintained via a mechanism such as "URL Rewriting". It DOES guarantee that the session is maintained in some fashion, and that pretty much requires some sort of unique ID which is passed to the browser and returned, but no mechanism is provided in the Servlet API for servlet code to control what value is used. Nor do common servlet containers that I know of (such as Tomcat) provide a means for controlling this value.

However, none of this should be a problem for you if I understand your requirements properly. Just because Tomcat (or whatever servlet container you use) is creating a unique ID based on its own algorithms (that contain things like cryptographically secure random number generators to prevent "guessing" of session IDs), doesn't mean that you cannot create a SEPARATE ID which meets your requirements (based on user and time, unique across all sessions... whatever you need). This ID can be stored in the session (if that's all you need), or can be stored on the browser in a separate cookie (if you need it maintained across sessions). The only effect would be that the browser was storing TWO cookies -- and most websites store many more cookies than that!

Answered by: Emily674 | Posted: 01-03-2022



Answer 3

Um...if you have the code to generate a unique ID, you can just do this:

/** 
 * The String key of the user id attribute.
 */
public static final String USER_ID_KEY = "userIdKey";

// Set the user attribute (createUniqueUserId's parameters and return type are up to you)
httpSession.setAttribute(USER_ID_KEY, createUniqueUserId());

// Retrieve the user attribute later
httpSession.getAttribute(USER_ID_KEY);

The HttpSession interface also provides a getId() method, which is documented here (copying the documentation for reference):

public java.lang.String getId()

Returns a string containing the unique identifier assigned to this session. The identifier is assigned by the servlet container and is implementation dependent.

Returns: a string specifying the identifier assigned to this session

Answered by: Jared479 | Posted: 01-03-2022



Similar questions

java - Handling user session in jsf 2

I'm building a web application using jsf2. I use a @ManagedBean with a @SessionScope. In it I store the username etc in a User object. Let's say I want to create an article, for that I have another @ManagedBean @RequestScope that has a createArticle() method, but it needs to set the article author. Should I inject the user session bean through cdi to get the user user object, is it ok to inject managedbeans into other mana...


java - Handling Session timeout on Client side

The scenario is that a user should get notification (say via typical JS alert or redirect etc) when her session is about to be expired. Couple of ways this can be done is Using javascript time out function as explained here. Using


java - session handling in JSF 1.2

How do we handle session variables (add/fetch) in JSF 1.2? A scenario: Consider a login screen where the user logs in successfully, the user model is stored in session. The user modes contains the user role. Next time onwards, for every user action, check the user role from the user model and display the form accordingly. In such a case how to add the user odel in session and how to etrieve it ev...


Flex Session Handling with Java

I have implemented session handling in Flex Java application, But I am facing one issue in that. When I login after that I am creating new flex session by : session = FlexContext.getFlexSession(); But If I test my application in two different browser then : • IE browser : If I login my application then its giving me some session ID like (0704943129C2D91539D989EA1DB70...


java - Spring MVC handling session expired

I'm working with Jboss EAP 6.2, Java EE 6 and Spring MVC 4.0.2. When the session expired I want to execute a page redirect. I have developed a Spring Interceptor @Component public class SessionExpiredInterceptor extends HandlerInterceptorAdapter { static final Logger logger = Logger.getLogger(SessionExpiredInterceptor.class); @Override public bool...


java - Session handling in simple http server

I was coding a little Http web server based on next model: public class HttpServer { public static void main(String[] args) throws Throwable { ServerSocket ss = new ServerSocket(8080); while (true) { Socket s = ss.accept(); System.err.println("Client accepted"); new Thread(new SocketProcessor(s)).start(); } } private static class Sock...


java - Tomcat - Custom Session Cookie Handling

my issue is as follows: We are working on deploying our application as a WebApp inside Tomcat. However, our software is capable of running in a multi-tenancy mode, i.e. have multiple "clients" (tenants) served by one instance of the WebApp. The URLs would look like this (let's assume the WebApp's context is /app: For the client Customer 1, the data would be served for URLs /app/cust...


java - Session handling in backend program

I've have written a little game in Java and using a Webpage as frontend (using Tomcat 8 integrated in Eclipse). The session handling on the front end is no problem. However I got none on the backend. <% //Prepare Game request.getSession(); Controller master = (Controller) session.getAttribute("master"); if (master == null){ master = new Controller(); master.prepareGame(); ...


java - Session handling in Spring MVC

I am trying to wrap my head around how sessions would work in Sprint MVC. If I intend to build a server that just processes requests and returns information, how should I persist sessions? I know there are many ways to do so like using cookies or sessions , but how should the architecture be overall? Let's assume a user makes an httpRequest to a server issuing a login function and sending a body with username and p...


java - Session Handling is Not working in JSP Page?

When I submit a form present in Index.jsp it goes to Home.jsp page and if log out it also redirects to Index.jsp page. But when I try to access Home.jsp page without login is shows an error. Ideally it should redirect to Index .jsp page because session at Home.jsp <%@page import="com.bean.UsersBean"%> <%@page import="com.util.DAO"%> <%@ page language="java" contentType=...


Java: handling combined keyboard input

What is the correct way to separate between F1 and i.e. CTRL+F1 respective SHIFT-CTRL+F1 within an KeyListener registered behind i.e. a JButton? public void keyPressed(KeyEvent event) { int key = event.getKeyCode(); logger.debug("KeyBoard pressed char(" + event.getKeyChar() + ") code (" + key + ")"); } .. always giv...


java - Handling logins to a XMPP server via servlets

I would like to hear some comments about how to manage long lived XMPP connections on a servlet container i.e. Tomcat. Basically we have a client that submits login credentials to a servlet and we create a XMPPConnection for each session and store it in HttpSession. To simplistic, the client can perform 4 operations: login, send/receive messages, logout. (1) As you can see, the lifetime of the XMPPC...


build process - Handling different API versions in same Java source

I'm sure this is a dumb question, but.. We have the same Java source files and we want to use a different version of a Java API (jar file) depending on the client we are building our app for. The newer version of the API has the methods setAAA() and setBBB() which we reference in our Java source: if (...) { api.setAAA(a); api.setBBB(b); } This code will fail if compiled wit...


java - Is JDBC capable of handling huge database?

I am working on a project, which is having huge database. [ around 32gb data in one week ]. We are using DB2, and spring-framework + jdbc. I just wanted to know is JDBC capable of handling this much of data? Or should i use something else? Or if JDBC is capable of doing this then should i use some specific technique for this thing.


java - Spring MVC Domain Object handling Best Practice

Lets assume a simple Spring MVC Controller that receives the ID of a domain object. The Controller should call a service that should do something with that domain object. Where do you "convert" the ID of the domain object into the domain object by loading it from the database? This should not be done by the Controller. So the service method interface has to use accept the ID of the domain object inst...


Java event handling with a delay

import java.awt.Color; import java.awt.Dimension; import javax.swing.JPanel; import javax.swing.Timer; import org.jfree.chart.ChartFactory; import org.jfree.chart.ChartMouseEvent; import org.jfree.chart.ChartMouseListener; import org.jfree.chart.ChartPanel; import org.jfree.chart.JFreeChart; import org.jfree.chart.entity.ChartEntity; import org.jfree.chart.plot.PiePlot; import org.jfree.chart.plot.PiePlot3D; impo...


Best XML handling class in Java

Closed. This question is opinion-based. It is not c...


XML handling in Java

Need to select all nodes from the path a/b/c as NodeList from a Document using getElementsByTagName() . How do i provide path of node as input? eg: - <root> <a> <b> <c>1</c> <c>2</c> <c>3</c> <c>4</c> <c>5</c> ...


java - Handling Shutdown Event

Hi I have an Standalone application in which when an user logs in a abc.lck file gets created when the application is closed it gets deleted.I have used addshutdownhook() to delete the file when power supply is interrupted that is switching off the power supply when my application is running.My problem is the file is not getting deleted when I manually shutdown the system i.e by start-->shutdown


java - Signal handling using "TERM"

I have a standalone application in which I have to prompt the user with an confirm dialog box to save the changes made by him when he tries to shutdown the system by start-->shutdown. I came to know that by using signalhandlers we can do it. Can some one help me how to use signal handlers






Still can't find your answer? Check out these amazing Java communities for help...



Java Reddit Community | Java Help Reddit Community | Dev.to Java Community | Java Discord | Java Programmers (Facebook) | Java developers (Facebook)



top